Updated for OSP Toolkit 4.0.0.
[asterisk/asterisk.git] / apps / app_osplookup.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  * \brief Open Settlement Protocol (OSP) Applications
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \extref The OSP Toolkit: http://www.transnexus.com
26  * \extref OpenSSL http://www.openssl.org
27  *
28  * \ingroup applications
29  */
30
31 /*** MODULEINFO
32         <depend>osptk</depend>
33         <depend>openssl</depend>
34         <support_level>extended</support_level>
35  ***/
36
37 #include "asterisk.h"
38
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40
41 #include <osp/osp.h>
42 #include <osp/osputils.h>
43 #include <osp/ospb64.h>
44
45 #include "asterisk/paths.h"
46 #include "asterisk/lock.h"
47 #include "asterisk/config.h"
48 #include "asterisk/utils.h"
49 #include "asterisk/causes.h"
50 #include "asterisk/channel.h"
51 #include "asterisk/app.h"
52 #include "asterisk/module.h"
53 #include "asterisk/pbx.h"
54 #include "asterisk/cli.h"
55 #include "asterisk/astosp.h"
56
57 /*** DOCUMENTATION
58         <application name="OSPAuth" language="en_US">
59                 <synopsis>
60                         OSP Authentication.
61                 </synopsis>
62                 <syntax>
63                         <parameter name="provider">
64                                 <para>The name of the provider that authenticates the call.</para>
65                         </parameter>
66                         <parameter name="options">
67                                 <para>Reserverd.</para>
68                         </parameter>
69                 </syntax>
70                 <description>
71                         <para>Authenticate a call by OSP.</para>
72                         <para>Input variables:</para>
73                         <variablelist>
74                                 <variable name="OSPINPEERIP">
75                                         <para>The last hop IP address.</para>
76                                 </variable>
77                                 <variable name="OSPINTOKEN">
78                                         <para>The inbound OSP token.</para>
79                                 </variable>
80                         </variablelist>
81                         <para>Output variables:</para>
82                         <variablelist>
83                                 <variable name="OSPINHANDLE">
84                                         <para>The inbound call OSP transaction handle.</para>
85                                 </variable>
86                                 <variable name="OSPINTIMELIMIT">
87                                         <para>The inbound call duration limit in seconds.</para>
88                                 </variable>
89                         </variablelist>
90                         <para>This application sets the following channel variable upon completion:</para>
91                         <variablelist>
92                                 <variable name="OSPAUTHSTATUS">
93                                         <para>The status of OSPAuth attempt as a text string, one of</para>
94                                         <value name="SUCCESS" />
95                                         <value name="FAILED" />
96                                         <value name="ERROR" />
97                                 </variable>
98                         </variablelist>
99                 </description>
100                 <see-also>
101                         <ref type="application">OSPLookup</ref>
102                         <ref type="application">OSPNext</ref>
103                         <ref type="application">OSPFinish</ref>
104                 </see-also>
105         </application>
106         <application name="OSPLookup" language="en_US">
107                 <synopsis>
108                         Lookup destination by OSP.
109                 </synopsis>
110                 <syntax>
111                         <parameter name="exten" required="true">
112                                 <para>The exten of the call.</para>
113                         </parameter>
114                         <parameter name="provider">
115                                 <para>The name of the provider that is used to route the call.</para>
116                         </parameter>
117                         <parameter name="options">
118                                 <enumlist>
119                                         <enum name="h">
120                                                 <para>generate H323 call id for the outbound call</para>
121                                         </enum>
122                                         <enum name="s">
123                                                 <para>generate SIP call id for the outbound call. Have not been implemented</para>
124                                         </enum>
125                                         <enum name="i">
126                                                 <para>generate IAX call id for the outbound call. Have not been implemented</para>
127                                         </enum>
128                                 </enumlist>
129                         </parameter>
130                 </syntax>
131                 <description>
132                         <para>Looks up destination via OSP.</para>
133                         <para>Input variables:</para>
134                         <variablelist>
135                                 <variable name="OSPINACTUALSRC">
136                                         <para>The actual source device IP address in indirect mode.</para>
137                                 </variable>
138                                 <variable name="OSPINPEERIP">
139                                         <para>The last hop IP address.</para>
140                                 </variable>
141                                 <variable name="OSPINTECH">
142                                         <para>The inbound channel technology for the call.</para>
143                                 </variable>
144                                 <variable name="OSPINHANDLE">
145                                         <para>The inbound call OSP transaction handle.</para>
146                                 </variable>
147                                 <variable name="OSPINTIMELIMIT">
148                                         <para>The inbound call duration limit in seconds.</para>
149                                 </variable>
150                                 <variable name="OSPINNETWORKID">
151                                         <para>The inbound source network ID.</para>
152                                 </variable>
153                                 <variable name="OSPINNPRN">
154                                         <para>The inbound routing number.</para>
155                                 </variable>
156                                 <variable name="OSPINNPCIC">
157                                         <para>The inbound carrier identification code.</para>
158                                 </variable>
159                                 <variable name="OSPINNPDI">
160                                         <para>The inbound number portability database dip indicator.</para>
161                                 </variable>
162                                 <variable name="OSPINSPID">
163                                         <para>The inbound service provider identity.</para>
164                                 </variable>
165                                 <variable name="OSPINOCN">
166                                         <para>The inbound operator company number.</para>
167                                 </variable>
168                                 <variable name="OSPINSPN">
169                                         <para>The inbound service provider name.</para>
170                                 </variable>
171                                 <variable name="OSPINALTSPN">
172                                         <para>The inbound alternate service provider name.</para>
173                                 </variable>
174                                 <variable name="OSPINMCC">
175                                         <para>The inbound mobile country code.</para>
176                                 </variable>
177                                 <variable name="OSPINMNC">
178                                         <para>The inbound mobile network code.</para>
179                                 </variable>
180                                 <variable name="OSPINTOHOST">
181                                         <para>The inbound To header host part.</para>
182                                 </variable>
183                                 <variable name="OSPINRPIDUSER">
184                                         <para>The inbound Remote-Party-ID header user part.</para>
185                                 </variable>
186                                 <variable name="OSPINPAIUSER">
187                                         <para>The inbound P-Asserted-Identify header user part.</para>
188                                 </variable>
189                                 <variable name="OSPINDIVUSER">
190                                         <para>The inbound Diversion header user part.</para>
191                                 </variable>
192                                 <variable name="OSPINDIVHOST">
193                                         <para>The inbound Diversion header host part.</para>
194                                 </variable>
195                                 <variable name="OSPINPCIUSER">
196                                         <para>The inbound P-Charge-Info header user part.</para>
197                                 </variable>
198                                 <variable name="OSPINCUSTOMINFOn">
199                                         <para>The inbound custom information, where <literal>n</literal> is the index beginning with <literal>1</literal>
200                                         upto <literal>8</literal>.</para>
201                                 </variable>
202                         </variablelist>
203                         <para>Output variables:</para>
204                         <variablelist>
205                                 <variable name="OSPOUTHANDLE">
206                                         <para>The outbound call OSP transaction handle.</para>
207                                 </variable>
208                                 <variable name="OSPOUTTECH">
209                                         <para>The outbound channel technology for the call.</para>
210                                 </variable>
211                                 <variable name="OSPDESTINATION">
212                                         <para>The outbound destination IP address.</para>
213                                 </variable>
214                                 <variable name="OSPOUTCALLING">
215                                         <para>The outbound calling number.</para>
216                                 </variable>
217                                 <variable name="OSPOUTCALLED">
218                                         <para>The outbound called number.</para>
219                                 </variable>
220                                 <variable name="OSPOUTNETWORKID">
221                                         <para>The outbound destination network ID.</para>
222                                 </variable>
223                                 <variable name="OSPOUTNPRN">
224                                         <para>The outbound routing number.</para>
225                                 </variable>
226                                 <variable name="OSPOUTNPCIC">
227                                         <para>The outbound carrier identification code.</para>
228                                 </variable>
229                                 <variable name="OSPOUTNPDI">
230                                         <para>The outbound number portability database dip indicator.</para>
231                                 </variable>
232                                 <variable name="OSPOUTSPID">
233                                         <para>The outbound service provider identity.</para>
234                                 </variable>
235                                 <variable name="OSPOUTOCN">
236                                         <para>The outbound operator company number.</para>
237                                 </variable>
238                                 <variable name="OSPOUTSPN">
239                                         <para>The outbound service provider name.</para>
240                                 </variable>
241                                 <variable name="OSPOUTALTSPN">
242                                         <para>The outbound alternate service provider name.</para>
243                                 </variable>
244                                 <variable name="OSPOUTMCC">
245                                         <para>The outbound mobile country code.</para>
246                                 </variable>
247                                 <variable name="OSPOUTMNC">
248                                         <para>The outbound mobile network code.</para>
249                                 </variable>
250                                 <variable name="OSPOUTTOKEN">
251                                         <para>The outbound OSP token.</para>
252                                 </variable>
253                                 <variable name="OSPDESTREMAILS">
254                                         <para>The number of remained destinations.</para>
255                                 </variable>
256                                 <variable name="OSPOUTTIMELIMIT">
257                                         <para>The outbound call duration limit in seconds.</para>
258                                 </variable>
259                                 <variable name="OSPOUTCALLIDTYPES">
260                                         <para>The outbound Call-ID types.</para>
261                                 </variable>
262                                 <variable name="OSPOUTCALLID">
263                                         <para>The outbound Call-ID. Only for H.323.</para>
264                                 </variable>
265                                 <variable name="OSPDIALSTR">
266                                         <para>The outbound Dial command string.</para>
267                                 </variable>
268                         </variablelist>
269                         <para>This application sets the following channel variable upon completion:</para>
270                         <variablelist>
271                                 <variable name="OSPLOOKUPSTATUS">
272                                         <para>The status of OSPLookup attempt as a text string, one of</para>
273                                         <value name="SUCCESS" />
274                                         <value name="FAILED" />
275                                         <value name="ERROR" />
276                                 </variable>
277                         </variablelist>
278                 </description>
279                 <see-also>
280                         <ref type="application">OSPAuth</ref>
281                         <ref type="application">OSPNext</ref>
282                         <ref type="application">OSPFinish</ref>
283                 </see-also>
284         </application>
285         <application name="OSPNext" language="en_US">
286                 <synopsis>
287                         Lookup next destination by OSP.
288                 </synopsis>
289                 <description>
290                         <para>Looks up the next destination via OSP.</para>
291                         <para>Input variables:</para>
292                         <variablelist>
293                                 <variable name="OSPINHANDLE">
294                                         <para>The inbound call OSP transaction handle.</para>
295                                 </variable>
296                                 <variable name="OSPOUTHANDLE">
297                                         <para>The outbound call OSP transaction handle.</para>
298                                 </variable>
299                                 <variable name="OSPINTIMELIMIT">
300                                         <para>The inbound call duration limit in seconds.</para>
301                                 </variable>
302                                 <variable name="OSPOUTCALLIDTYPES">
303                                         <para>The outbound Call-ID types.</para>
304                                 </variable>
305                                 <variable name="OSPDESTREMAILS">
306                                         <para>The number of remained destinations.</para>
307                                 </variable>
308                         </variablelist>
309                         <para>Output variables:</para>
310                         <variablelist>
311                                 <variable name="OSPOUTTECH">
312                                         <para>The outbound channel technology.</para>
313                                 </variable>
314                                 <variable name="OSPDESTINATION">
315                                         <para>The destination IP address.</para>
316                                 </variable>
317                                 <variable name="OSPOUTCALLING">
318                                         <para>The outbound calling number.</para>
319                                 </variable>
320                                 <variable name="OSPOUTCALLED">
321                                         <para>The outbound called number.</para>
322                                 </variable>
323                                 <variable name="OSPOUTNETWORKID">
324                                         <para>The outbound destination network ID.</para>
325                                 </variable>
326                                 <variable name="OSPOUTNPRN">
327                                         <para>The outbound routing number.</para>
328                                 </variable>
329                                 <variable name="OSPOUTNPCIC">
330                                         <para>The outbound carrier identification code.</para>
331                                 </variable>
332                                 <variable name="OSPOUTNPDI">
333                                         <para>The outbound number portability database dip indicator.</para>
334                                 </variable>
335                                 <variable name="OSPOUTSPID">
336                                         <para>The outbound service provider identity.</para>
337                                 </variable>
338                                 <variable name="OSPOUTOCN">
339                                         <para>The outbound operator company number.</para>
340                                 </variable>
341                                 <variable name="OSPOUTSPN">
342                                         <para>The outbound service provider name.</para>
343                                 </variable>
344                                 <variable name="OSPOUTALTSPN">
345                                         <para>The outbound alternate service provider name.</para>
346                                 </variable>
347                                 <variable name="OSPOUTMCC">
348                                         <para>The outbound mobile country code.</para>
349                                 </variable>
350                                 <variable name="OSPOUTMNC">
351                                         <para>The outbound mobile network code.</para>
352                                 </variable>
353                                 <variable name="OSPOUTTOKEN">
354                                         <para>The outbound OSP token.</para>
355                                 </variable>
356                                 <variable name="OSPDESTREMAILS">
357                                         <para>The number of remained destinations.</para>
358                                 </variable>
359                                 <variable name="OSPOUTTIMELIMIT">
360                                         <para>The outbound call duration limit in seconds.</para>
361                                 </variable>
362                                 <variable name="OSPOUTCALLID">
363                                         <para>The outbound Call-ID. Only for H.323.</para>
364                                 </variable>
365                                 <variable name="OSPDIALSTR">
366                                         <para>The outbound Dial command string.</para>
367                                 </variable>
368                         </variablelist>
369                         <para>This application sets the following channel variable upon completion:</para>
370                         <variablelist>
371                                 <variable name="OSPNEXTSTATUS">
372                                         <para>The status of the OSPNext attempt as a text string, one of</para>
373                                         <value name="SUCCESS" />
374                                         <value name="FAILED" />
375                                         <value name="ERROR" />
376                                 </variable>
377                         </variablelist>
378                 </description>
379                 <see-also>
380                         <ref type="application">OSPAuth</ref>
381                         <ref type="application">OSPLookup</ref>
382                         <ref type="application">OSPFinish</ref>
383                 </see-also>
384         </application>
385         <application name="OSPFinish" language="en_US">
386                 <synopsis>
387                         Report OSP entry.
388                 </synopsis>
389                 <syntax>
390                         <parameter name="cause">
391                                 <para>Hangup cause.</para>
392                         </parameter>
393                         <parameter name="options">
394                                 <para>Reserved.</para>
395                         </parameter>
396                 </syntax>
397                 <description>
398                         <para>Report call state.</para>
399                         <para>Input variables:</para>
400                         <variablelist>
401                                 <variable name="OSPINHANDLE">
402                                         <para>The inbound call OSP transaction handle.</para>
403                                 </variable>
404                                 <variable name="OSPOUTHANDLE">
405                                         <para>The outbound call OSP transaction handle.</para>
406                                 </variable>
407                                 <variable name="OSPAUTHSTATUS">
408                                         <para>The OSPAuth status.</para>
409                                 </variable>
410                                 <variable name="OSPLOOKUPSTATUS">
411                                         <para>The OSPLookup status.</para>
412                                 </variable>
413                                 <variable name="OSPNEXTSTATUS">
414                                         <para>The OSPNext status.</para>
415                                 </variable>
416                                 <variable name="OSPINAUDIOQOS">
417                                         <para>The inbound call leg audio QoS string.</para>
418                                 </variable>
419                                 <variable name="OSPOUTAUDIOQOS">
420                                         <para>The outbound call leg audio QoS string.</para>
421                                 </variable>
422                         </variablelist>
423                         <para>This application sets the following channel variable upon completion:</para>
424                         <variablelist>
425                                 <variable name="OSPFINISHSTATUS">
426                                         <para>The status of the OSPFinish attempt as a text string, one of</para>
427                                         <value name="SUCCESS" />
428                                         <value name="FAILED" />
429                                         <value name="ERROR" />
430                                 </variable>
431                         </variablelist>
432                 </description>
433                 <see-also>
434                         <ref type="application">OSPAuth</ref>
435                         <ref type="application">OSPLookup</ref>
436                         <ref type="application">OSPNext</ref>
437                 </see-also>
438         </application>
439  ***/
440
441 /* OSP Buffer Sizes */
442 #define OSP_SIZE_INTSTR         ((unsigned int)16)                      /* OSP signed/unsigned int string buffer size */
443 #define OSP_SIZE_NORSTR         ((unsigned int)256)                     /* OSP normal string buffer size */
444 #define OSP_SIZE_KEYSTR         ((unsigned int)1024)            /* OSP certificate string buffer size */
445 #define OSP_SIZE_TOKSTR         ((unsigned int)4096)            /* OSP token string buffer size */
446 #define OSP_SIZE_TECHSTR        ((unsigned int)32)                      /* OSP signed/unsigned int string buffer size */
447 #define OSP_SIZE_UUID           ((unsigned int)16)                      /* UUID size */
448 #define OSP_SIZE_UUIDSTR        ((unsigned int)36)                      /* UUID string size */
449 #define OSP_SIZE_QOSSTR         ((unsigned int)1024)            /* QoS string buffer size */
450
451 /* Call ID Type*/
452 #define OSP_CALLID_UNDEF        ((unsigned int)0)                       /* Undefined */
453 #define OSP_CALLID_SIP          ((unsigned int)(1 << 0))        /* SIP */
454 #define OSP_CALLID_H323         ((unsigned int)(1 << 1))        /* H.323 */
455 #define OSP_CALLID_IAX          ((unsigned int)(1 << 2))        /* IAX2 */
456 #define OSP_CALLID_MAXNUM       ((unsigned int)3)                       /* Max number of call ID types */
457
458 /* OSP Supported Destination Protocols */
459 #define OSP_PROT_SIP            ((const char*)"SIP")            /* SIP protocol name */
460 #define OSP_PROT_H323           ((const char*)"H323")           /* H.323 Q.931 protocol name*/
461 #define OSP_PROT_IAX            ((const char*)"IAX")            /* IAX2 protocol name */
462 #define OSP_PROT_SKYPE          ((const char*)"SKYPE")          /* Skype protocol name */
463
464 /* OSP supported Destination Tech */
465 #define OSP_TECH_SIP            ((const char*)"SIP")            /* SIP tech name */
466 #define OSP_TECH_H323           ((const char*)"H323")           /* OH323 tech name */
467 #define OSP_TECH_IAX            ((const char*)"IAX2")           /* IAX2 tech name */
468 #define OSP_TECH_SKYPE          ((const char*)"SKYPE")          /* Skype tech name */
469
470 /* SIP OSP header field name */
471 #define OSP_SIP_HEADER          ((const char*)"P-OSP-Auth-Token")
472
473 /* OSP Authentication Policy */
474 enum osp_authpolicy {
475         OSP_AUTH_NO = 0,        /* Accept any call */
476         OSP_AUTH_YES,           /* Accept call with valid OSP token or without OSP token */
477         OSP_AUTH_EXC            /* Only accept call with valid OSP token */
478 };
479
480 /* OSP Work Mode */
481 enum osp_workmode {
482         OSP_MODE_DIRECT= 0,     /* Direct */
483         OSP_MODE_INDIRECT       /* Indirect */
484 };
485
486 /* OSP Service Type */
487 enum osp_srvtype {
488         OSP_SRV_VOICE = 0,      /* Normal voice service */
489         OSP_SRV_NPQUERY         /* Ported number query service */
490 };
491
492 /* OSP Constants */
493 #define OSP_OK                                  ((int)1)                                        /* OSP function call successful */
494 #define OSP_FAILED                              ((int)0)                                        /* OSP function call failed */
495 #define OSP_ERROR                               ((int)-1)                                       /* OSP function call error */
496 #define OSP_AST_OK                              ((int)0)                                        /* Asterisk function call successful */
497 #define OSP_AST_ERROR                   ((int)-1)                                       /* Asterisk function call error */
498 #define OSP_INVALID_HANDLE              ((int)-1)                                       /* Invalid OSP handle, provider, transaction etc. */
499 #define OSP_CONFIG_FILE                 ((const char*)"osp.conf")       /* OSP configuration file name */
500 #define OSP_GENERAL_CAT                 ((const char*)"general")        /* OSP global configuration context name */
501 #define OSP_DEF_PROVIDER                ((const char*)"default")        /* OSP default provider context name */
502 #define OSP_MAX_CERTS                   ((unsigned int)10)                      /* OSP max number of cacerts */
503 #define OSP_MAX_SPOINTS                 ((unsigned int)10)                      /* OSP max number of service points */
504 #define OSP_DEF_MAXCONNECT              ((unsigned int)20)                      /* OSP default max_connections */
505 #define OSP_MIN_MAXCONNECT              ((unsigned int)1)                       /* OSP min max_connections */
506 #define OSP_MAX_MAXCONNECT              ((unsigned int)1000)            /* OSP max max_connections */
507 #define OSP_DEF_RETRYDELAY              ((unsigned int)0)                       /* OSP default retry delay */
508 #define OSP_MIN_RETRYDELAY              ((unsigned int)0)                       /* OSP min retry delay */
509 #define OSP_MAX_RETRYDELAY              ((unsigned int)10)                      /* OSP max retry delay */
510 #define OSP_DEF_RETRYLIMIT              ((unsigned int)2)                       /* OSP default retry times */
511 #define OSP_MIN_RETRYLIMIT              ((unsigned int)0)                       /* OSP min retry times */
512 #define OSP_MAX_RETRYLIMIT              ((unsigned int)100)                     /* OSP max retry times */
513 #define OSP_DEF_TIMEOUT                 ((unsigned int)500)                     /* OSP default timeout in ms */
514 #define OSP_MIN_TIMEOUT                 ((unsigned int)200)                     /* OSP min timeout in ms */
515 #define OSP_MAX_TIMEOUT                 ((unsigned int)10000)           /* OSP max timeout in ms */
516 #define OSP_DEF_AUTHPOLICY              OSP_AUTH_YES                            /* OSP default auth policy, yes */
517 #define OSP_AUDIT_URL                   ((const char*)"localhost")      /* OSP default Audit URL */
518 #define OSP_LOCAL_VALIDATION    ((int)1)                                        /* Validate OSP token locally */
519 #define OSP_SSL_LIFETIME                ((unsigned int)300)                     /* SSL life time, in seconds */
520 #define OSP_HTTP_PERSISTENCE    ((int)1)                                        /* In seconds */
521 #define OSP_CUSTOMER_ID                 ((const char*)"")                       /* OSP customer ID */
522 #define OSP_DEVICE_ID                   ((const char*)"")                       /* OSP device ID */
523 #define OSP_DEF_MAXDESTS                ((unsigned int)5)                       /* OSP default max number of destinations */
524 #define OSP_DEF_TIMELIMIT               ((unsigned int)0)                       /* OSP default duration limit, no limit */
525 #define OSP_DEF_PROTOCOL                OSP_PROT_SIP                            /* OSP default signaling protocol, SIP */
526 #define OSP_DEF_WORKMODE                OSP_MODE_DIRECT                         /* OSP default work mode, direct */
527 #define OSP_DEF_SRVTYPE                 OSP_SRV_VOICE                           /* OSP default service type, voice */
528 #define OSP_MAX_CUSTOMINFO              ((unsigned int)8)                       /* OSP max number of custom info */
529 #define OSP_DEF_INTSTATS                ((int)-1)                                       /* OSP default int statistic */
530 #define OSP_DEF_FLOATSTATS              ((float)-1)                                     /* OSP default float statistic */
531
532 /* OSP Provider */
533 struct osp_provider {
534         OSPTPROVHANDLE handle;                                                  /* OSP provider handle */
535         char name[OSP_SIZE_NORSTR];                                             /* OSP provider context name */
536         char privatekey[OSP_SIZE_NORSTR];                               /* OSP private key file name */
537         char localcert[OSP_SIZE_NORSTR];                                /* OSP local cert file name */
538         unsigned int canum;                                                             /* Number of cacerts */
539         char cacerts[OSP_MAX_CERTS][OSP_SIZE_NORSTR];   /* Cacert file names */
540         unsigned int spnum;                                                             /* Number of service points */
541         char spoints[OSP_MAX_SPOINTS][OSP_SIZE_NORSTR]; /* Service point URLs */
542         unsigned int maxconnect;                                                /* Max number of connections */
543         unsigned int retrydelay;                                                /* Retry delay */
544         unsigned int retrylimit;                                                /* Retry limit */
545         unsigned int timeout;                                                   /* Timeout in ms */
546         char source[OSP_SIZE_NORSTR];                                   /* IP of self */
547         enum osp_authpolicy authpolicy;                                 /* OSP authentication policy */
548         const char* defprotocol;                                                /* OSP default signaling protocol */
549         enum osp_workmode workmode;                                             /* OSP work mode */
550         enum osp_srvtype srvtype;                                               /* OSP service type */
551         struct osp_provider* next;                                              /* Pointer to next OSP provider */
552 };
553
554 /* Call ID */
555 struct osp_callid {
556         unsigned char buf[OSP_SIZE_NORSTR];             /* Call ID string */
557         unsigned int len;                                               /* Call ID length */
558 };
559
560 /* Number Portability Data */
561 struct osp_npdata {
562         const char* rn;                                                 /* Rounding Number */
563         const char* cic;                                                /* Carrier Identification Code */
564         int npdi;                                                               /* NP Database Dip Indicator */
565         const char* opname[OSPC_OPNAME_NUMBER]; /* Operator Names */
566 };
567
568 /* SIP Header Parameters */
569 struct osp_headers {
570         const char* rpiduser;                                   /* Remote-Party-ID header user info */
571         const char* paiuser;                                    /* P-Asserted-Identity header user info */
572         const char* divuser;                                    /* Diversion header user info */
573         const char* divhost;                                    /* Diversion header host info */
574         const char* pciuser;                                    /* P-Charge-Info header user info */
575 };
576
577 /* OSP Application In/Output Results */
578 struct osp_results {
579         int inhandle;                                                                           /* Inbound transaction handle */
580         int outhandle;                                                                          /* Outbound transaction handle */
581         unsigned int intimelimit;                                                       /* Inbound duration limit */
582         unsigned int outtimelimit;                                                      /* Outbound duration limit */
583         char intech[OSP_SIZE_TECHSTR];                                          /* Inbound Asterisk TECH string */
584         char outtech[OSP_SIZE_TECHSTR];                                         /* Outbound Asterisk TECH string */
585         char dest[OSP_SIZE_NORSTR];                                                     /* Outbound destination IP address */
586         char calling[OSP_SIZE_NORSTR];                                          /* Outbound calling number, may be translated */
587         char called[OSP_SIZE_NORSTR];                                           /* Outbound called number, may be translated */
588         char token[OSP_SIZE_TOKSTR];                                            /* Outbound OSP token */
589         char networkid[OSP_SIZE_NORSTR];                                        /* Outbound network ID */
590         char nprn[OSP_SIZE_NORSTR];                                                     /* Outbound NP routing number */
591         char npcic[OSP_SIZE_NORSTR];                                            /* Outbound NP carrier identification code */
592         int npdi;                                                                                       /* Outbound NP database dip indicator */
593         char opname[OSPC_OPNAME_NUMBER][OSP_SIZE_NORSTR];       /* Outbound Operator names */
594         unsigned int numdests;                                                          /* Number of remain outbound destinations */
595         struct osp_callid outcallid;                                            /* Outbound call ID */
596 };
597
598 /* OSP Call Leg */
599 enum osp_callleg {
600         OSP_CALL_INBOUND,       /* Inbound call leg */
601         OSP_CALL_OUTBOUND       /* Outbound call leg */
602 };
603
604 /* OSP Media Stream Direction */
605 enum osp_direction {
606         OSP_DIR_RX = 0,         /* Receive */
607         OSP_DIR_TX,                     /* Send */
608         OSP_DIR_NUMBER          /* Number of directions */
609 };
610
611 /* OSP Metrics */
612 struct osp_metrics {
613         int value;                      /* Value */
614         float min;                      /* Minimum */
615         float max;                      /* Maximum */
616         float avg;                      /* Average */
617         float ndev;                     /* Normal deviation */
618         float sdev;                     /* Standard deviation */
619 };
620
621 /* OSP Module Global Variables */
622 AST_MUTEX_DEFINE_STATIC(osp_lock);                                                      /* Lock of OSP provider list */
623 static int osp_initialized = 0;                                                         /* Init flag */
624 static int osp_hardware = 0;                                                            /* Hardware accelleration flag */
625 static int osp_security = 0;                                                            /* Using security features flag */
626 static struct osp_provider* osp_providers = NULL;                       /* OSP provider list */
627 static unsigned int osp_tokenformat = TOKEN_ALGO_SIGNED;        /* Token format supported */
628
629 /* OSP default certificates */
630 const char* B64PKey = "MIIBOgIBAAJBAK8t5l+PUbTC4lvwlNxV5lpl+2dwSZGW46dowTe6y133XyVEwNiiRma2YNk3xKs/TJ3Wl9Wpns2SYEAJsFfSTukCAwEAAQJAPz13vCm2GmZ8Zyp74usTxLCqSJZNyMRLHQWBM0g44Iuy4wE3vpi7Wq+xYuSOH2mu4OddnxswCP4QhaXVQavTAQIhAOBVCKXtppEw9UaOBL4vW0Ed/6EA/1D8hDW6St0h7EXJAiEAx+iRmZKhJD6VT84dtX5ZYNVk3j3dAcIOovpzUj9a0CECIEduTCapmZQ5xqAEsLXuVlxRtQgLTUD4ZxDElPn8x0MhAiBE2HlcND0+qDbvtwJQQOUzDgqg5xk3w8capboVdzAlQQIhAMC+lDL7+gDYkNAft5Mu+NObJmQs4Cr+DkDFsKqoxqrm";
631 const char* B64LCert = "MIIBeTCCASMCEHqkOHVRRWr+1COq3CR/xsowDQYJKoZIhvcNAQEEBQAwOzElMCMGA1UEAxMcb3NwdGVzdHNlcnZlci50cmFuc25leHVzLmNvbTESMBAGA1UEChMJT1NQU2VydmVyMB4XDTA1MDYyMzAwMjkxOFoXDTA2MDYyNDAwMjkxOFowRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCvLeZfj1G0wuJb8JTcVeZaZftncEmRluOnaME3ustd918lRMDYokZmtmDZN8SrP0yd1pfVqZ7NkmBACbBX0k7pAgMBAAEwDQYJKoZIhvcNAQEEBQADQQDnV8QNFVVJx/+7IselU0wsepqMurivXZzuxOmTEmTVDzCJx1xhA8jd3vGAj7XDIYiPub1PV23eY5a2ARJuw5w9";
632 const char* B64CACert = "MIIBYDCCAQoCAQEwDQYJKoZIhvcNAQEEBQAwOzElMCMGA1UEAxMcb3NwdGVzdHNlcnZlci50cmFuc25leHVzLmNvbTESMBAGA1UEChMJT1NQU2VydmVyMB4XDTAyMDIwNDE4MjU1MloXDTEyMDIwMzE4MjU1MlowOzElMCMGA1UEAxMcb3NwdGVzdHNlcnZlci50cmFuc25leHVzLmNvbTESMBAGA1UEChMJT1NQU2VydmVyMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAPGeGwV41EIhX0jEDFLRXQhDEr50OUQPq+f55VwQd0TQNts06BP29+UiNdRW3c3IRHdZcJdC1Cg68ME9cgeq0h8CAwEAATANBgkqhkiG9w0BAQQFAANBAGkzBSj1EnnmUxbaiG1N4xjIuLAWydun7o3bFk2tV8dBIhnuh445obYyk1EnQ27kI7eACCILBZqi2MHDOIMnoN0=";
633
634 /* OSP Client Wrapper APIs */
635
636 /*!
637  * \brief Create OSP provider handle according to configuration
638  * \param cfg OSP configuration
639  * \param name OSP provider context name
640  * \return OSP_OK Success, OSP_FAILED Failed, OSP_ERROR Error
641  */
642 static int osp_create_provider(
643         struct ast_config* cfg,
644         const char* name)
645 {
646         int res = OSP_FAILED;
647         struct ast_variable* var;
648         struct osp_provider* provider;
649         OSPTPRIVATEKEY privatekey;
650         OSPT_CERT localcert;
651         OSPT_CERT cacerts[OSP_MAX_CERTS];
652         const OSPT_CERT* pcacerts[OSP_MAX_CERTS];
653         const char* pspoints[OSP_MAX_SPOINTS];
654         unsigned char privatekeydata[OSP_SIZE_KEYSTR];
655         unsigned char localcertdata[OSP_SIZE_KEYSTR];
656         unsigned char cacertdata[OSP_SIZE_KEYSTR];
657         int i, num, error = OSPC_ERR_NO_ERROR;
658
659         if (!(provider = ast_calloc(1, sizeof(*provider)))) {
660                 ast_log(LOG_ERROR, "Out of memory\n");
661                 return OSP_ERROR;
662         }
663
664         /* ast_calloc has set 0 in provider */
665         provider->handle = OSP_INVALID_HANDLE;
666         ast_copy_string(provider->name, name, sizeof(provider->name));
667         snprintf(provider->privatekey, sizeof(provider->privatekey), "%s/%s-privatekey.pem", ast_config_AST_KEY_DIR, name);
668         snprintf(provider->localcert, sizeof(provider->localcert), "%s/%s-localcert.pem", ast_config_AST_KEY_DIR, name);
669         snprintf(provider->cacerts[0], sizeof(provider->cacerts[0]), "%s/%s-cacert_0.pem", ast_config_AST_KEY_DIR, name);
670         provider->maxconnect = OSP_DEF_MAXCONNECT;
671         provider->retrydelay = OSP_DEF_RETRYDELAY;
672         provider->retrylimit = OSP_DEF_RETRYLIMIT;
673         provider->timeout = OSP_DEF_TIMEOUT;
674         provider->authpolicy = OSP_DEF_AUTHPOLICY;
675         provider->defprotocol = OSP_DEF_PROTOCOL;
676         provider->workmode = OSP_DEF_WORKMODE;
677         provider->srvtype = OSP_DEF_SRVTYPE;
678
679         for (var = ast_variable_browse(cfg, name); var != NULL; var = var->next) {
680                 if (!strcasecmp(var->name, "privatekey")) {
681                         if (osp_security) {
682                                 if (var->value[0] == '/') {
683                                         ast_copy_string(provider->privatekey, var->value, sizeof(provider->privatekey));
684                                 } else {
685                                         snprintf(provider->privatekey, sizeof(provider->privatekey), "%s/%s", ast_config_AST_KEY_DIR, var->value);
686                                 }
687                                 ast_debug(1, "OSP: privatekey '%s'\n", provider->privatekey);
688                         }
689                 } else if (!strcasecmp(var->name, "localcert")) {
690                         if (osp_security) {
691                                 if (var->value[0] == '/') {
692                                         ast_copy_string(provider->localcert, var->value, sizeof(provider->localcert));
693                                 } else {
694                                         snprintf(provider->localcert, sizeof(provider->localcert), "%s/%s", ast_config_AST_KEY_DIR, var->value);
695                                 }
696                                 ast_debug(1, "OSP: localcert '%s'\n", provider->localcert);
697                         }
698                 } else if (!strcasecmp(var->name, "cacert")) {
699                         if (osp_security) {
700                                 if (provider->canum < OSP_MAX_CERTS) {
701                                         if (var->value[0] == '/') {
702                                                 ast_copy_string(provider->cacerts[provider->canum], var->value, sizeof(provider->cacerts[provider->canum]));
703                                         } else {
704                                                 snprintf(provider->cacerts[provider->canum], sizeof(provider->cacerts[provider->canum]), "%s/%s", ast_config_AST_KEY_DIR, var->value);
705                                         }
706                                         ast_debug(1, "OSP: cacerts[%d]: '%s'\n", provider->canum, provider->cacerts[provider->canum]);
707                                         provider->canum++;
708                                 } else {
709                                         ast_log(LOG_WARNING, "OSP: Too many CA Certificates at line %d\n", var->lineno);
710                                 }
711                         }
712                 } else if (!strcasecmp(var->name, "servicepoint")) {
713                         if (provider->spnum < OSP_MAX_SPOINTS) {
714                                 ast_copy_string(provider->spoints[provider->spnum], var->value, sizeof(provider->spoints[provider->spnum]));
715                                 ast_debug(1, "OSP: servicepoint[%d]: '%s'\n", provider->spnum, provider->spoints[provider->spnum]);
716                                 provider->spnum++;
717                         } else {
718                                 ast_log(LOG_WARNING, "OSP: Too many Service Points at line %d\n", var->lineno);
719                         }
720                 } else if (!strcasecmp(var->name, "maxconnect")) {
721                         if ((sscanf(var->value, "%30d", &num) == 1) && (num >= OSP_MIN_MAXCONNECT) && (num <= OSP_MAX_MAXCONNECT)) {
722                                 provider->maxconnect = num;
723                                 ast_debug(1, "OSP: maxconnect '%d'\n", num);
724                         } else {
725                                 ast_log(LOG_WARNING, "OSP: maxconnect should be an integer from %d to %d, not '%s' at line %d\n",
726                                         OSP_MIN_MAXCONNECT, OSP_MAX_MAXCONNECT, var->value, var->lineno);
727                         }
728                 } else if (!strcasecmp(var->name, "retrydelay")) {
729                         if ((sscanf(var->value, "%30d", &num) == 1) && (num >= OSP_MIN_RETRYDELAY) && (num <= OSP_MAX_RETRYDELAY)) {
730                                 provider->retrydelay = num;
731                                 ast_debug(1, "OSP: retrydelay '%d'\n", num);
732                         } else {
733                                 ast_log(LOG_WARNING, "OSP: retrydelay should be an integer from %d to %d, not '%s' at line %d\n",
734                                         OSP_MIN_RETRYDELAY, OSP_MAX_RETRYDELAY, var->value, var->lineno);
735                         }
736                 } else if (!strcasecmp(var->name, "retrylimit")) {
737                         if ((sscanf(var->value, "%30d", &num) == 1) && (num >= OSP_MIN_RETRYLIMIT) && (num <= OSP_MAX_RETRYLIMIT)) {
738                                 provider->retrylimit = num;
739                                 ast_debug(1, "OSP: retrylimit '%d'\n", num);
740                         } else {
741                                 ast_log(LOG_WARNING, "OSP: retrylimit should be an integer from %d to %d, not '%s' at line %d\n",
742                                         OSP_MIN_RETRYLIMIT, OSP_MAX_RETRYLIMIT, var->value, var->lineno);
743                         }
744                 } else if (!strcasecmp(var->name, "timeout")) {
745                         if ((sscanf(var->value, "%30d", &num) == 1) && (num >= OSP_MIN_TIMEOUT) && (num <= OSP_MAX_TIMEOUT)) {
746                                 provider->timeout = num;
747                                 ast_debug(1, "OSP: timeout '%d'\n", num);
748                         } else {
749                                 ast_log(LOG_WARNING, "OSP: timeout should be an integer from %d to %d, not '%s' at line %d\n",
750                                         OSP_MIN_TIMEOUT, OSP_MAX_TIMEOUT, var->value, var->lineno);
751                         }
752                 } else if (!strcasecmp(var->name, "source")) {
753                         ast_copy_string(provider->source, var->value, sizeof(provider->source));
754                         ast_debug(1, "OSP: source '%s'\n", provider->source);
755                 } else if (!strcasecmp(var->name, "authpolicy")) {
756                         if ((sscanf(var->value, "%30d", &num) == 1) && ((num == OSP_AUTH_NO) || (num == OSP_AUTH_YES) || (num == OSP_AUTH_EXC))) {
757                                 provider->authpolicy = num;
758                                 ast_debug(1, "OSP: authpolicy '%d'\n", num);
759                         } else {
760                                 ast_log(LOG_WARNING, "OSP: authpolicy should be %d, %d or %d, not '%s' at line %d\n",
761                                         OSP_AUTH_NO, OSP_AUTH_YES, OSP_AUTH_EXC, var->value, var->lineno);
762                         }
763                 } else if (!strcasecmp(var->name, "defprotocol")) {
764                         if (!strcasecmp(var->value, OSP_PROT_SIP)) {
765                                 provider->defprotocol = OSP_PROT_SIP;
766                                 ast_debug(1, "OSP: default protocol SIP\n");
767                         } else if (!strcasecmp(var->value, OSP_PROT_H323)) {
768                                 provider->defprotocol = OSP_PROT_H323;
769                                 ast_debug(1, "OSP: default protocol H.323\n");
770                         } else if (!strcasecmp(var->value, OSP_PROT_IAX)) {
771                                 provider->defprotocol = OSP_PROT_IAX;
772                                 ast_debug(1, "OSP: default protocol IAX\n");
773                         } else if (!strcasecmp(var->value, OSP_PROT_SKYPE)) {
774                                 provider->defprotocol = OSP_PROT_SKYPE;
775                                 ast_debug(1, "OSP: default protocol Skype\n");
776                         } else {
777                                 ast_log(LOG_WARNING, "OSP: default protocol should be %s, %s, %s or %s not '%s' at line %d\n",
778                                         OSP_PROT_SIP, OSP_PROT_H323, OSP_PROT_IAX, OSP_PROT_SKYPE, var->value, var->lineno);
779                         }
780                 } else if (!strcasecmp(var->name, "workmode")) {
781                         if ((sscanf(var->value, "%30d", &num) == 1) && ((num == OSP_MODE_DIRECT) || (num == OSP_MODE_INDIRECT))) {
782                                 provider->workmode = num;
783                                 ast_debug(1, "OSP: workmode '%d'\n", num);
784                         } else {
785                                 ast_log(LOG_WARNING, "OSP: workmode should be %d or %d, not '%s' at line %d\n",
786                                         OSP_MODE_DIRECT, OSP_MODE_INDIRECT, var->value, var->lineno);
787                         }
788                 } else if (!strcasecmp(var->name, "servicetype")) {
789                         if ((sscanf(var->value, "%30d", &num) == 1) && ((num == OSP_SRV_VOICE) || (num == OSP_SRV_NPQUERY))) {
790                                 provider->srvtype = num;
791                                 ast_debug(1, "OSP: servicetype '%d'\n", num);
792                         } else {
793                                 ast_log(LOG_WARNING, "OSP: servicetype should be %d or %d, not '%s' at line %d\n",
794                                         OSP_SRV_VOICE, OSP_SRV_NPQUERY, var->value, var->lineno);
795                         }
796                 }
797         }
798
799         if (provider->canum == 0) {
800                 provider->canum = 1;
801         }
802
803         for (i = 0; i < provider->spnum; i++) {
804                 pspoints[i] = provider->spoints[i];
805         }
806
807         if (osp_security) {
808                 privatekey.PrivateKeyData = NULL;
809                 privatekey.PrivateKeyLength = 0;
810
811                 localcert.CertData = NULL;
812                 localcert.CertDataLength = 0;
813
814                 for (i = 0; i < provider->canum; i++) {
815                         cacerts[i].CertData = NULL;
816                         cacerts[i].CertDataLength = 0;
817                 }
818
819                 if ((error = OSPPUtilLoadPEMPrivateKey((unsigned char*)provider->privatekey, &privatekey)) != OSPC_ERR_NO_ERROR) {
820                         ast_log(LOG_WARNING, "OSP: Unable to load privatekey '%s', error '%d'\n", provider->privatekey, error);
821                 } else if ((error = OSPPUtilLoadPEMCert((unsigned char*)provider->localcert, &localcert)) != OSPC_ERR_NO_ERROR) {
822                         ast_log(LOG_WARNING, "OSP: Unable to load localcert '%s', error '%d'\n", provider->localcert, error);
823                 } else {
824                         for (i = 0; i < provider->canum; i++) {
825                                 if ((error = OSPPUtilLoadPEMCert((unsigned char*)provider->cacerts[i], &cacerts[i])) != OSPC_ERR_NO_ERROR) {
826                                         ast_log(LOG_WARNING, "OSP: Unable to load cacert '%s', error '%d'\n", provider->cacerts[i], error);
827                                         break;
828                                 } else {
829                                         pcacerts[i] = &cacerts[i];
830                                 }
831                         }
832                 }
833         } else {
834                 privatekey.PrivateKeyData = privatekeydata;
835                 privatekey.PrivateKeyLength = sizeof(privatekeydata);
836
837                 localcert.CertData = localcertdata;
838                 localcert.CertDataLength = sizeof(localcertdata);
839
840                 cacerts[0].CertData = cacertdata;
841                 cacerts[0].CertDataLength = sizeof(cacertdata);
842                 pcacerts[0] = &cacerts[0];
843
844                 if ((error = OSPPBase64Decode(B64PKey, strlen(B64PKey), privatekey.PrivateKeyData, &privatekey.PrivateKeyLength)) != OSPC_ERR_NO_ERROR) {
845                         ast_log(LOG_WARNING, "OSP: Unable to decode private key, error '%d'\n", error);
846                 } else if ((error = OSPPBase64Decode(B64LCert, strlen(B64LCert), localcert.CertData, &localcert.CertDataLength)) != OSPC_ERR_NO_ERROR) {
847                         ast_log(LOG_WARNING, "OSP: Unable to decode local cert, error '%d'\n", error);
848                 } else if ((error = OSPPBase64Decode(B64CACert, strlen(B64CACert), cacerts[0].CertData, &cacerts[0].CertDataLength)) != OSPC_ERR_NO_ERROR) {
849                         ast_log(LOG_WARNING, "OSP: Unable to decode cacert, error '%d'\n", error);
850                 }
851         }
852
853         if (error == OSPC_ERR_NO_ERROR) {
854                 error = OSPPProviderNew(provider->spnum,
855                         pspoints,
856                         NULL,
857                         OSP_AUDIT_URL,
858                         &privatekey,
859                         &localcert,
860                         provider->canum,
861                         pcacerts,
862                         OSP_LOCAL_VALIDATION,
863                         OSP_SSL_LIFETIME,
864                         provider->maxconnect,
865                         OSP_HTTP_PERSISTENCE,
866                         provider->retrydelay,
867                         provider->retrylimit,
868                         provider->timeout,
869                         OSP_CUSTOMER_ID,
870                         OSP_DEVICE_ID,
871                         &provider->handle);
872                 if (error != OSPC_ERR_NO_ERROR) {
873                         ast_log(LOG_WARNING, "OSP: Unable to create provider '%s', error '%d'\n", name, error);
874                         res = OSP_ERROR;
875                 } else {
876                         ast_debug(1, "OSP: provider '%s'\n", name);
877                         ast_mutex_lock(&osp_lock);
878                         provider->next = osp_providers;
879                         osp_providers = provider;
880                         ast_mutex_unlock(&osp_lock);
881                         res = OSP_OK;
882                 }
883         }
884
885         if (osp_security) {
886                 for (i = 0; i < provider->canum; i++) {
887                         if (cacerts[i].CertData) {
888                                 ast_free(cacerts[i].CertData);
889                         }
890                 }
891                 if (localcert.CertData) {
892                         ast_free(localcert.CertData);
893                 }
894                 if (privatekey.PrivateKeyData) {
895                         ast_free(privatekey.PrivateKeyData);
896                 }
897         }
898
899         if (res != OSP_OK) {
900                 ast_free(provider);
901         }
902
903         return res;
904 }
905
906 /*!
907  * \brief Get OSP provider by name
908  * \param name OSP provider context name
909  * \param provider OSP provider structure
910  * \return OSP_OK Success, OSP_FAILED Failed, OSP_ERROR Error
911  */
912 static int osp_get_provider(
913         const char* name,
914         struct osp_provider** provider)
915 {
916         int res = OSP_FAILED;
917         struct osp_provider* p;
918
919         *provider = NULL;
920
921         ast_mutex_lock(&osp_lock);
922         for (p = osp_providers; p != NULL; p = p->next) {
923                 if (!strcasecmp(p->name, name)) {
924                         *provider = p;
925                         ast_debug(1, "OSP: find provider '%s'\n", name);
926                         res = OSP_OK;
927                         break;
928                 }
929         }
930         ast_mutex_unlock(&osp_lock);
931
932         return res;
933 }
934
935 /*!
936  * \brief Create OSP transaction handle
937  * \param name OSP provider context name
938  * \param trans OSP transaction handle, output
939  * \param source Source of provider, output
940  * \param srcsize Size of source buffer, in
941  * \return OSK_OK Success, OSK_FAILED Failed, OSP_ERROR Error
942  */
943 static int osp_create_transaction(
944         const char* name,
945         int* trans,
946         char* source,
947         unsigned int srcsize)
948 {
949         int res = OSP_FAILED;
950         struct osp_provider* provider;
951         int error;
952
953         if ((trans == NULL) || (source == NULL) || (srcsize <= 0)) {
954                 ast_log(LOG_ERROR, "Invalid parameters\n");
955                 return OSP_ERROR;
956         }
957
958         *trans = OSP_INVALID_HANDLE;
959         *source = '\0';
960
961         ast_mutex_lock(&osp_lock);
962         for (provider = osp_providers; provider; provider = provider->next) {
963                 if (!strcasecmp(provider->name, name)) {
964                         error = OSPPTransactionNew(provider->handle, trans);
965                         if (error == OSPC_ERR_NO_ERROR) {
966                                 ast_debug(1, "OSP: transaction '%d'\n", *trans);
967                                 ast_copy_string(source, provider->source, srcsize);
968                                 ast_debug(1, "OSP: source '%s'\n", source);
969                                 res = OSP_OK;
970                         } else {
971                                 *trans = OSP_INVALID_HANDLE;
972                                 ast_debug(1, "OSP: Unable to create transaction handle, error '%d'\n", error);
973                                 *source = '\0';
974                                 res = OSP_ERROR;
975                         }
976                         break;
977                 }
978         }
979         ast_mutex_unlock(&osp_lock);
980
981         return res;
982 }
983
984 /*!
985  * \brief Convert "address:port" to "[x.x.x.x]:port" or "hostname:port" format
986  * \param src Source address string
987  * \param dest Destination address string
988  * \param destsize Size of dest buffer
989  */
990 static void osp_convert_inout(
991         const char* src,
992         char* dest,
993         unsigned int destsize)
994 {
995         struct in_addr inp;
996         char buffer[OSP_SIZE_NORSTR];
997         char* port;
998
999         if ((dest != NULL) && (destsize > 0)) {
1000                 if (!ast_strlen_zero(src)) {
1001                         ast_copy_string(buffer, src, sizeof(buffer));
1002
1003                         if((port = strchr(buffer, ':')) != NULL) {
1004                                 *port = '\0';
1005                                 port++;
1006                         }
1007
1008                         if (inet_pton(AF_INET, buffer, &inp) == 1) {
1009                                 if (port != NULL) {
1010                                         snprintf(dest, destsize, "[%s]:%s", buffer, port);
1011                                 } else {
1012                                         snprintf(dest, destsize, "[%s]", buffer);
1013                                 }
1014                                 dest[destsize - 1] = '\0';
1015                         } else {
1016                                 ast_copy_string(dest, src, destsize);
1017                         }
1018                 } else {
1019                         *dest = '\0';
1020                 }
1021         }
1022 }
1023
1024 /*!
1025  * \brief Convert "[x.x.x.x]:port" or "hostname:prot" to "address:port" format
1026  * \param src Source address string
1027  * \param dest Destination address string
1028  * \param destsize Size of dest buffer
1029  */
1030 static void osp_convert_outin(
1031         const char* src,
1032         char* dest,
1033         unsigned int destsize)
1034 {
1035         char buffer[OSP_SIZE_NORSTR];
1036         char* end;
1037         char* port;
1038
1039         if ((dest != NULL) && (destsize > 0)) {
1040                 if (!ast_strlen_zero(src)) {
1041                         ast_copy_string(buffer, src, sizeof(buffer));
1042
1043                         if (buffer[0] == '[') {
1044                                 if((port = strchr(buffer + 1, ':')) != NULL) {
1045                                         *port = '\0';
1046                                         port++;
1047                                 }
1048
1049                                 if ((end = strchr(buffer + 1, ']')) != NULL) {
1050                                         *end = '\0';
1051                                 }
1052
1053                                 if (port != NULL) {
1054                                         snprintf(dest, destsize, "%s:%s", buffer + 1, port);
1055                                         dest[destsize - 1] = '\0';
1056                                 } else {
1057                                         ast_copy_string(dest, buffer + 1, destsize);
1058                                 }
1059                         } else {
1060                                 ast_copy_string(dest, src, destsize);
1061                         }
1062                 } else {
1063                         *dest = '\0';
1064                 }
1065         }
1066 }
1067
1068 /*!
1069  * \brief Validate OSP token of inbound call
1070  * \param trans OSP transaction handle
1071  * \param source Source of inbound call
1072  * \param destination Destination of inbound call
1073  * \param calling Calling number
1074  * \param called Called number
1075  * \param token OSP token, may be empty
1076  * \param timelimit Call duration limit, output
1077  * \return OSP_OK Success, OSP_FAILED Failed, OSP_ERROR Error
1078  */
1079 static int osp_validate_token(
1080         int trans,
1081         const char* source,
1082         const char* destination,
1083         const char* calling,
1084         const char* called,
1085         const char* token,
1086         unsigned int* timelimit)
1087 {
1088         int res;
1089         int tokenlen;
1090         unsigned char tokenstr[OSP_SIZE_TOKSTR];
1091         char src[OSP_SIZE_NORSTR];
1092         char dest[OSP_SIZE_NORSTR];
1093         unsigned int authorised;
1094         unsigned int dummy = 0;
1095         int error;
1096
1097         if (timelimit == NULL) {
1098                 ast_log(LOG_ERROR, "Invalid parameters\n");
1099                 return OSP_ERROR;
1100         }
1101
1102         tokenlen = ast_base64decode(tokenstr, token, strlen(token));
1103         osp_convert_inout(source, src, sizeof(src));
1104         osp_convert_inout(destination, dest, sizeof(dest));
1105         error = OSPPTransactionValidateAuthorisation(trans,
1106                 src,
1107                 dest,
1108                 NULL,
1109                 NULL,
1110                 calling ? calling : "",
1111                 OSPC_NFORMAT_E164,
1112                 called,
1113                 OSPC_NFORMAT_E164,
1114                 0,
1115                 NULL,
1116                 tokenlen,
1117                 (char*)tokenstr,
1118                 &authorised,
1119                 timelimit,
1120                 &dummy,
1121                 NULL,
1122                 osp_tokenformat);
1123         if (error != OSPC_ERR_NO_ERROR) {
1124                 ast_log(LOG_WARNING, "OSP: Unable to validate inbound token, error '%d'\n", error);
1125                 *timelimit = 0;
1126                 res = OSP_ERROR;
1127         } else if (authorised) {
1128                 ast_debug(1, "OSP: Authorised\n");
1129                 res = OSP_OK;
1130         } else {
1131                 ast_debug(1, "OSP: Unauthorised\n");
1132                 res = OSP_FAILED;
1133         }
1134
1135         return res;
1136 }
1137
1138 /*!
1139  * \brief Choose min duration limit
1140  * \param in Inbound duration limit
1141  * \param out Outbound duration limit
1142  * \return min duration limit
1143  */
1144 static unsigned int osp_choose_timelimit(
1145         unsigned int in,
1146         unsigned int out)
1147 {
1148         if (in == OSP_DEF_TIMELIMIT) {
1149                 return out;
1150         } else if (out == OSP_DEF_TIMELIMIT) {
1151                 return in;
1152         } else {
1153                 return in < out ? in : out;
1154         }
1155 }
1156
1157 /*!
1158  * \brief Choose min duration limit
1159  * \param provider OSP provider
1160  * \param calling Calling number
1161  * \param called Called number
1162  * \param destination Destination IP in '[x.x.x.x]' format
1163  * \param tokenlen OSP token length
1164  * \param token OSP token
1165  * \param reason Failure reason, output
1166  * \param results OSP lookup results, in/output
1167  * \return OSP_OK Success, OSP_FAILED Failed, OSP_ERROR Error
1168  */
1169 static int osp_check_destination(
1170         struct osp_provider* provider,
1171         const char* calling,
1172         const char* called,
1173         const char* destination,
1174         unsigned int tokenlen,
1175         const char* token,
1176         OSPEFAILREASON* reason,
1177         struct osp_results* results)
1178 {
1179         int res;
1180         OSPE_DEST_OSPENABLED enabled;
1181         OSPE_PROTOCOL_NAME protocol;
1182         char dest[OSP_SIZE_NORSTR];
1183         OSPE_OPERATOR_NAME type;
1184         int error;
1185
1186         if ((provider == NULL) || (reason == NULL) || (results == NULL)) {
1187                 ast_log(LOG_ERROR, "Invalid parameters\n");
1188                 return OSP_ERROR;
1189         }
1190
1191         if ((error = OSPPTransactionIsDestOSPEnabled(results->outhandle, &enabled)) != OSPC_ERR_NO_ERROR) {
1192                 ast_debug(1, "OSP: Unable to get destination OSP version, error '%d'\n", error);
1193                 *reason = OSPC_FAIL_NORMAL_UNSPECIFIED;
1194                 return OSP_ERROR;
1195         }
1196
1197         if (enabled == OSPC_DOSP_FALSE) {
1198                 results->token[0] = '\0';
1199         } else {
1200                 ast_base64encode(results->token, (const unsigned char*)token, tokenlen, sizeof(results->token) - 1);
1201         }
1202
1203         if ((error = OSPPTransactionGetDestinationNetworkId(results->outhandle, sizeof(results->networkid), results->networkid)) != OSPC_ERR_NO_ERROR) {
1204                 ast_debug(1, "OSP: Unable to get destination network ID, error '%d'\n", error);
1205                 results->networkid[0] = '\0';
1206         }
1207
1208         error = OSPPTransactionGetNumberPortabilityParameters(results->outhandle,
1209                 sizeof(results->nprn),
1210                 results->nprn,
1211                 sizeof(results->npcic),
1212                 results->npcic,
1213                 &results->npdi);
1214         if (error != OSPC_ERR_NO_ERROR) {
1215                 ast_debug(1, "OSP: Unable to get number portability parameters, error '%d'\n", error);
1216                 results->nprn[0] = '\0';
1217                 results->npcic[0] = '\0';
1218                 results->npdi = 0;
1219         }
1220
1221         for (type = OSPC_OPNAME_START; type < OSPC_OPNAME_NUMBER; type++) {
1222                 error = OSPPTransactionGetOperatorName(results->outhandle, type, sizeof(results->opname[type]), results->opname[type]);
1223                 if (error != OSPC_ERR_NO_ERROR) {
1224                         ast_debug(1, "OSP: Unable to get operator name of type '%d', error '%d'\n", type, error);
1225                         results->opname[type][0] = '\0';
1226                 }
1227         }
1228
1229         if ((error = OSPPTransactionGetDestProtocol(results->outhandle, &protocol)) != OSPC_ERR_NO_ERROR) {
1230                 ast_debug(1, "OSP: Unable to get destination protocol, error '%d'\n", error);
1231                 *reason = OSPC_FAIL_NORMAL_UNSPECIFIED;
1232                 results->token[0] = '\0';
1233                 results->networkid[0] = '\0';
1234                 results->nprn[0] = '\0';
1235                 results->npcic[0] = '\0';
1236                 results->npdi = 0;
1237                 for (type = OSPC_OPNAME_START; type < OSPC_OPNAME_NUMBER; type++) {
1238                         results->opname[type][0] = '\0';
1239                 }
1240                 return OSP_ERROR;
1241         }
1242
1243         res = OSP_OK;
1244         osp_convert_outin(destination, dest, sizeof(dest));
1245         switch(protocol) {
1246         case OSPC_PROTNAME_SIP:
1247                 ast_debug(1, "OSP: protocol SIP\n");
1248                 ast_copy_string(results->outtech, OSP_TECH_SIP, sizeof(results->outtech));
1249                 ast_copy_string(results->dest, dest, sizeof(results->dest));
1250                 ast_copy_string(results->calling, calling, sizeof(results->calling));
1251                 ast_copy_string(results->called, called, sizeof(results->called));
1252                 break;
1253         case OSPC_PROTNAME_Q931:
1254                 ast_debug(1, "OSP: protocol Q.931\n");
1255                 ast_copy_string(results->outtech, OSP_TECH_H323, sizeof(results->outtech));
1256                 ast_copy_string(results->dest, dest, sizeof(results->dest));
1257                 ast_copy_string(results->calling, calling, sizeof(results->calling));
1258                 ast_copy_string(results->called, called, sizeof(results->called));
1259                 break;
1260         case OSPC_PROTNAME_IAX:
1261                 ast_debug(1, "OSP: protocol IAX\n");
1262                 ast_copy_string(results->outtech, OSP_TECH_IAX, sizeof(results->outtech));
1263                 ast_copy_string(results->dest, dest, sizeof(results->dest));
1264                 ast_copy_string(results->calling, calling, sizeof(results->calling));
1265                 ast_copy_string(results->called, called, sizeof(results->called));
1266                 break;
1267         case OSPC_PROTNAME_SKYPE:
1268                 ast_debug(1, "OSP: protocol Skype\n");
1269                 ast_copy_string(results->outtech, OSP_TECH_SKYPE, sizeof(results->outtech));
1270                 ast_copy_string(results->dest, dest, sizeof(results->dest));
1271                 ast_copy_string(results->calling, calling, sizeof(results->calling));
1272                 ast_copy_string(results->called, called, sizeof(results->called));
1273                 break;
1274         case OSPC_PROTNAME_UNDEFINED:
1275         case OSPC_PROTNAME_UNKNOWN:
1276                 ast_debug(1, "OSP: unknown/undefined protocol '%d'\n", protocol);
1277                 ast_debug(1, "OSP: use default protocol '%s'\n", provider->defprotocol);
1278                 ast_copy_string(results->outtech, provider->defprotocol, sizeof(results->outtech));
1279                 ast_copy_string(results->dest, dest, sizeof(results->dest));
1280                 ast_copy_string(results->calling, calling, sizeof(results->calling));
1281                 ast_copy_string(results->called, called, sizeof(results->called));
1282                 break;
1283         case OSPC_PROTNAME_LRQ:
1284         case OSPC_PROTNAME_T37:
1285         case OSPC_PROTNAME_T38:
1286         case OSPC_PROTNAME_SMPP:
1287         case OSPC_PROTNAME_XMPP:
1288         default:
1289                 ast_log(LOG_WARNING, "OSP: unsupported protocol '%d'\n", protocol);
1290                 *reason = OSPC_FAIL_PROTOCOL_ERROR;
1291                 results->token[0] = '\0';
1292                 results->networkid[0] = '\0';
1293                 results->nprn[0] = '\0';
1294                 results->npcic[0] = '\0';
1295                 results->npdi = 0;
1296                 for (type = OSPC_OPNAME_START; type < OSPC_OPNAME_NUMBER; type++) {
1297                         results->opname[type][0] = '\0';
1298                 }
1299                 res = OSP_FAILED;
1300                 break;
1301         }
1302
1303         return res;
1304 }
1305
1306 /*!
1307  * \brief Convert Asterisk status to TC code
1308  * \param cause Asterisk hangup cause
1309  * \return OSP TC code
1310  */
1311 static OSPEFAILREASON asterisk2osp(
1312         int cause)
1313 {
1314         return (OSPEFAILREASON)cause;
1315 }
1316
1317 /*!
1318  * \brief OSP Authentication function
1319  * \param name OSP provider context name
1320  * \param trans OSP transaction handle, output
1321  * \param source Source of inbound call
1322  * \param calling Calling number
1323  * \param called Called number
1324  * \param token OSP token, may be empty
1325  * \param timelimit Call duration limit, output
1326  * \return OSP_OK Authenricated, OSP_FAILED Unauthenticated, OSP_ERROR Error
1327  */
1328 static int osp_auth(
1329         const char* name,
1330         int* trans,
1331         const char* source,
1332         const char* calling,
1333         const char* called,
1334         const char* token,
1335         unsigned int* timelimit)
1336 {
1337         int res;
1338         struct osp_provider* provider = NULL;
1339         char dest[OSP_SIZE_NORSTR];
1340
1341         if ((trans == NULL) || (timelimit == NULL)) {
1342                 ast_log(LOG_ERROR, "Invalid parameters\n");
1343                 return OSP_ERROR;
1344         }
1345
1346         *trans = OSP_INVALID_HANDLE;
1347         *timelimit = OSP_DEF_TIMELIMIT;
1348
1349         if ((res = osp_get_provider(name, &provider)) <= 0) {
1350                 ast_debug(1, "OSP: Unabe to find OSP provider '%s'\n", name);
1351                 return res;
1352         }
1353
1354         switch (provider->authpolicy) {
1355         case OSP_AUTH_NO:
1356                 res = OSP_OK;
1357                 break;
1358         case OSP_AUTH_EXC:
1359                 if (ast_strlen_zero(token)) {
1360                         res = OSP_FAILED;
1361                 } else if ((res = osp_create_transaction(name, trans, dest, sizeof(dest))) <= 0) {
1362                         ast_debug(1, "OSP: Unable to generate transaction handle\n");
1363                         *trans = OSP_INVALID_HANDLE;
1364                         res = OSP_FAILED;
1365                 } else if((res = osp_validate_token(*trans, source, dest, calling, called, token, timelimit)) <= 0) {
1366                         OSPPTransactionRecordFailure(*trans, OSPC_FAIL_CALL_REJECTED);
1367                 }
1368                 break;
1369         case OSP_AUTH_YES:
1370         default:
1371                 if (ast_strlen_zero(token)) {
1372                         res = OSP_OK;
1373                 } else if ((res = osp_create_transaction(name, trans, dest, sizeof(dest))) <= 0) {
1374                         ast_debug(1, "OSP: Unable to generate transaction handle\n");
1375                         *trans = OSP_INVALID_HANDLE;
1376                         res = OSP_FAILED;
1377                 } else if((res = osp_validate_token(*trans, source, dest, calling, called, token, timelimit)) <= 0) {
1378                         OSPPTransactionRecordFailure(*trans, OSPC_FAIL_CALL_REJECTED);
1379                 }
1380                 break;
1381         }
1382
1383         return res;
1384 }
1385
1386 /*!
1387  * \brief Create a UUID
1388  * \param uuid UUID buffer
1389  * \param bufsize UUID buffer size
1390  * \return OSK_OK Created, OSP_ERROR Error
1391  */
1392 static int osp_create_uuid(
1393         unsigned char* uuid,
1394         unsigned int* bufsize)
1395 {
1396         int i, res;
1397         long int tmp[OSP_SIZE_UUID / sizeof(long int)];
1398
1399         if ((uuid != NULL) && (*bufsize >= OSP_SIZE_UUID)) {
1400                 for (i = 0; i < OSP_SIZE_UUID / sizeof(long int); i++) {
1401                         tmp[i] = ast_random();
1402                 }
1403                 memcpy(uuid, tmp, OSP_SIZE_UUID);
1404                 *bufsize = OSP_SIZE_UUID;
1405                 res = OSP_OK;
1406         } else {
1407                 ast_log(LOG_ERROR, "Invalid parameters\n");
1408                 res = OSP_ERROR;
1409         }
1410
1411         return res;
1412 }
1413
1414 /*!
1415  * \brief UUID to string
1416  * \param uuid UUID
1417  * \param buffer String buffer
1418  * \param bufsize String buffer size
1419  * \return OSP_OK Successed, OSP_ERROR Error
1420  */
1421 static int osp_uuid2str(
1422         unsigned char* uuid,
1423         char* buffer,
1424         unsigned int bufsize)
1425 {
1426         int res;
1427
1428         if ((uuid != NULL) && (bufsize > OSP_SIZE_UUIDSTR)) {
1429                 snprintf(buffer, bufsize, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
1430                         uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7],
1431                         uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
1432                 res = OSP_OK;
1433         } else {
1434                 ast_log(LOG_ERROR, "Invalid parameters\n");
1435                 res = OSP_ERROR;
1436         }
1437
1438         return res;
1439 }
1440
1441 /*!
1442  * \brief Create a call ID according to the type
1443  * \param type Call ID type
1444  * \param callid Call ID buffer
1445  * \return OSK_OK Created, OSP_FAILED Not create, OSP_ERROR Error
1446  */
1447 static int osp_create_callid(
1448         unsigned int type,
1449         struct osp_callid* callid)
1450 {
1451         int res;
1452
1453         if (callid == NULL) {
1454                 ast_log(LOG_ERROR, "Invalid parameters\n");
1455                 res = OSP_ERROR;
1456         }
1457
1458         callid->len = sizeof(callid->buf);
1459         switch (type) {
1460         case OSP_CALLID_H323:
1461                 res = osp_create_uuid(callid->buf, &callid->len);
1462                 break;
1463         case OSP_CALLID_SIP:
1464         case OSP_CALLID_IAX:
1465                 res = OSP_FAILED;
1466         default:
1467                 res = OSP_ERROR;
1468                 break;
1469         }
1470
1471         if ((res != OSP_OK) && (callid->len != 0)) {
1472                 callid->buf[0] = '\0';
1473                 callid->len = 0;
1474         }
1475
1476         return res;
1477 }
1478
1479 /*!
1480  * \brief OSP Lookup function
1481  * \param name OSP provider context name
1482  * \param callidtypes Call ID types
1483  * \param actualsrc Actual source device in indirect mode
1484  * \param srcdev Source device of outbound call
1485  * \param calling Calling number
1486  * \param called Called number
1487  * \param snetid Source network ID
1488  * \param np NP parameters
1489  * \param headers SIP header parameters
1490  * \param cinfo Custom info
1491  * \param results Lookup results
1492  * \return OSP_OK Found , OSP_FAILED No route, OSP_ERROR Error
1493  */
1494 static int osp_lookup(
1495         const char* name,
1496         unsigned int callidtypes,
1497         const char* actualsrc,
1498         const char* srcdev,
1499         const char* calling,
1500         const char* called,
1501         const char* snetid,
1502         struct osp_npdata* np,
1503         struct osp_headers* headers,
1504         const char* cinfo[],
1505         struct osp_results* results)
1506 {
1507         int res;
1508         struct osp_provider* provider = NULL;
1509         OSPE_PROTOCOL_NAME protocol;
1510         char source[OSP_SIZE_NORSTR];
1511         char callingnum[OSP_SIZE_NORSTR];
1512         char callednum[OSP_SIZE_NORSTR];
1513         char destination[OSP_SIZE_NORSTR];
1514         char* tmp;
1515         unsigned int tokenlen;
1516         char token[OSP_SIZE_TOKSTR];
1517         char src[OSP_SIZE_NORSTR];
1518         char dev[OSP_SIZE_NORSTR];
1519         char host[OSP_SIZE_NORSTR];
1520         unsigned int i, type;
1521         struct osp_callid callid;
1522         unsigned int callidnum;
1523         OSPT_CALL_ID* callids[OSP_CALLID_MAXNUM];
1524         char dest[OSP_SIZE_NORSTR];
1525         const char* preferred[2] = { NULL };
1526         unsigned int dummy = 0;
1527         OSPEFAILREASON reason;
1528         int error;
1529
1530         if (results == NULL) {
1531                 ast_log(LOG_ERROR, "Invalid parameters\n");
1532                 res = OSP_ERROR;
1533         }
1534
1535         osp_convert_inout(results->dest, dest, sizeof(dest));
1536
1537         results->outhandle = OSP_INVALID_HANDLE;
1538         results->outtech[0] = '\0';
1539         results->calling[0] = '\0';
1540         results->called[0] = '\0';
1541         results->token[0] = '\0';
1542         results->networkid[0] = '\0';
1543         results->nprn[0] = '\0';
1544         results->npcic[0] = '\0';
1545         results->npdi = 0;
1546         for (type = OSPC_OPNAME_START; type < OSPC_OPNAME_NUMBER; type++) {
1547                 results->opname[type][0] = '\0';
1548         }
1549         results->numdests = 0;
1550         results->outtimelimit = OSP_DEF_TIMELIMIT;
1551
1552         if ((res = osp_get_provider(name, &provider)) <= 0) {
1553                 ast_debug(1, "OSP: Unabe to find OSP provider '%s'\n", name);
1554                 return res;
1555         }
1556
1557         if ((res = osp_create_transaction(name, &results->outhandle, source, sizeof(source))) <= 0) {
1558                 ast_debug(1, "OSP: Unable to generate transaction handle\n");
1559                 results->outhandle = OSP_INVALID_HANDLE;
1560                 if (results->inhandle != OSP_INVALID_HANDLE) {
1561                         OSPPTransactionRecordFailure(results->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
1562                 }
1563                 return OSP_ERROR;
1564         }
1565
1566         if (!strcasecmp(results->intech, OSP_TECH_SIP)) {
1567                 protocol = OSPC_PROTNAME_SIP;
1568         } else if (!strcasecmp(results->intech, OSP_TECH_H323)) {
1569                 protocol = OSPC_PROTNAME_Q931;
1570         } else if (!strcasecmp(results->intech, OSP_TECH_IAX)) {
1571                 protocol = OSPC_PROTNAME_IAX;
1572         } else if (!strcasecmp(results->intech, OSP_TECH_SKYPE)) {
1573                 protocol = OSPC_PROTNAME_SKYPE;
1574         } else {
1575                 protocol = OSPC_PROTNAME_SIP;
1576         }
1577         OSPPTransactionSetProtocol(results->outhandle, OSPC_PROTTYPE_SOURCE, protocol);
1578
1579         if (!ast_strlen_zero(snetid)) {
1580                 OSPPTransactionSetNetworkIds(results->outhandle, snetid, "");
1581         }
1582
1583         OSPPTransactionSetNumberPortability(results->outhandle, np->rn, np->cic, np->npdi);
1584
1585         for (type = OSPC_OPNAME_START; type < OSPC_OPNAME_NUMBER; type++) {
1586                 OSPPTransactionSetOperatorName(results->outhandle, type, np->opname[type]);
1587         }
1588
1589     OSPPTransactionSetRemotePartyId(results->outhandle, OSPC_NFORMAT_E164, headers->rpiduser);
1590     OSPPTransactionSetAssertedId(results->outhandle, OSPC_NFORMAT_E164, headers->paiuser);
1591         osp_convert_inout(headers->divhost, host, sizeof(host));
1592         OSPPTransactionSetDiversion(results->outhandle, headers->divuser, host);
1593     OSPPTransactionSetChargeInfo(results->outhandle, OSPC_NFORMAT_E164, headers->pciuser);
1594
1595         if (cinfo != NULL) {
1596                 for (i = 0; i < OSP_MAX_CUSTOMINFO; i++) {
1597                         if (!ast_strlen_zero(cinfo[i])) {
1598                                 OSPPTransactionSetCustomInfo(results->outhandle, i, cinfo[i]);
1599                         }
1600                 }
1601         }
1602
1603         ast_copy_string(callednum, called, sizeof(callednum));
1604         if((tmp = strchr(callednum, ';')) != NULL) {
1605                 *tmp = '\0';
1606         }
1607
1608         callidnum = 0;
1609         callids[0] = NULL;
1610         for (i = 0; i < OSP_CALLID_MAXNUM; i++) {
1611                 type = 1 << i;
1612                 if (callidtypes & type) {
1613                         error = osp_create_callid(type, &callid);
1614                         if (error == 1) {
1615                                 callids[callidnum] = OSPPCallIdNew(callid.len, callid.buf);
1616                                 callidnum++;
1617                         }
1618                 }
1619         }
1620
1621         if (provider->workmode == OSP_MODE_INDIRECT) {
1622                 osp_convert_inout(srcdev, src, sizeof(src));
1623                 if (ast_strlen_zero(actualsrc)) {
1624                         osp_convert_inout(srcdev, dev, sizeof(dev));
1625                 } else {
1626                         osp_convert_inout(actualsrc, dev, sizeof(dev));
1627                 }
1628         } else {
1629                 osp_convert_inout(source, src, sizeof(src));
1630                 osp_convert_inout(srcdev, dev, sizeof(dev));
1631         }
1632
1633         if (provider->srvtype == OSP_SRV_NPQUERY) {
1634                 OSPPTransactionSetServiceType(results->outhandle, OSPC_SERVICE_NPQUERY);
1635                 if (!ast_strlen_zero(dest)) {
1636                         preferred[0] = dest;
1637                 }
1638                 results->numdests = 1;
1639         } else {
1640                 OSPPTransactionSetServiceType(results->outhandle, OSPC_SERVICE_VOICE);
1641                 results->numdests = OSP_DEF_MAXDESTS;
1642         }
1643
1644         error = OSPPTransactionRequestAuthorisation(results->outhandle,
1645                 src,
1646                 dev,
1647                 calling ? calling : "",
1648                 OSPC_NFORMAT_E164,
1649                 callednum,
1650                 OSPC_NFORMAT_E164,
1651                 NULL,
1652                 callidnum,
1653                 callids,
1654                 preferred,
1655                 &results->numdests,
1656                 &dummy,
1657                 NULL);
1658
1659         for (i = 0; i < callidnum; i++) {
1660                 OSPPCallIdDelete(&callids[i]);
1661         }
1662
1663         if (error != OSPC_ERR_NO_ERROR) {
1664                 ast_log(LOG_WARNING, "OSP: Unable to request authorization, error '%d'\n", error);
1665                 results->numdests = 0;
1666                 if (results->inhandle != OSP_INVALID_HANDLE) {
1667                         OSPPTransactionRecordFailure(results->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
1668                 }
1669                 return OSP_ERROR;
1670         }
1671
1672         if (!results->numdests) {
1673                 ast_debug(1, "OSP: No more destination\n");
1674                 if (results->inhandle != OSP_INVALID_HANDLE) {
1675                         OSPPTransactionRecordFailure(results->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
1676                 }
1677                 return OSP_FAILED;
1678         }
1679
1680         results->outcallid.len = sizeof(results->outcallid.buf);
1681         tokenlen = sizeof(token);
1682         error = OSPPTransactionGetFirstDestination(results->outhandle,
1683                 0,
1684                 NULL,
1685                 NULL,
1686                 &results->outtimelimit,
1687                 &results->outcallid.len,
1688                 results->outcallid.buf,
1689                 sizeof(callednum),
1690                 callednum,
1691                 sizeof(callingnum),
1692                 callingnum,
1693                 sizeof(destination),
1694                 destination,
1695                 0,
1696                 NULL,
1697                 &tokenlen,
1698                 token);
1699         if (error != OSPC_ERR_NO_ERROR) {
1700                 ast_debug(1, "OSP: Unable to get first route, error '%d'\n", error);
1701                 results->numdests = 0;
1702                 results->outtimelimit = OSP_DEF_TIMELIMIT;
1703                 if (results->inhandle != OSP_INVALID_HANDLE) {
1704                         OSPPTransactionRecordFailure(results->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
1705                 }
1706                 return OSP_ERROR;
1707         }
1708
1709         results->numdests--;
1710         results->outtimelimit = osp_choose_timelimit(results->intimelimit, results->outtimelimit);
1711         ast_debug(1, "OSP: outtimelimit '%d'\n", results->outtimelimit);
1712         ast_debug(1, "OSP: calling '%s'\n", callingnum);
1713         ast_debug(1, "OSP: called '%s'\n", callednum);
1714         ast_debug(1, "OSP: destination '%s'\n", destination);
1715         ast_debug(1, "OSP: token size '%d'\n", tokenlen);
1716
1717         if ((res = osp_check_destination(provider, callingnum, callednum, destination, tokenlen, token, &reason, results)) > 0) {
1718                 return OSP_OK;
1719         }
1720
1721         if (!results->numdests) {
1722                 ast_debug(1, "OSP: No more destination\n");
1723                 results->outtimelimit = OSP_DEF_TIMELIMIT;
1724                 OSPPTransactionRecordFailure(results->outhandle, reason);
1725                 if (results->inhandle != OSP_INVALID_HANDLE) {
1726                         OSPPTransactionRecordFailure(results->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
1727                 }
1728                 return OSP_FAILED;
1729         }
1730
1731         while(results->numdests) {
1732                 results->outcallid.len = sizeof(results->outcallid.buf);
1733                 tokenlen = sizeof(token);
1734                 error = OSPPTransactionGetNextDestination(results->outhandle,
1735                         reason,
1736                         0,
1737                         NULL,
1738                         NULL,
1739                         &results->outtimelimit,
1740                         &results->outcallid.len,
1741                         results->outcallid.buf,
1742                         sizeof(callednum),
1743                         callednum,
1744                         sizeof(callingnum),
1745                         callingnum,
1746                         sizeof(destination),
1747                         destination,
1748                         0,
1749                         NULL,
1750                         &tokenlen,
1751                         token);
1752                 if (error == OSPC_ERR_NO_ERROR) {
1753                         results->numdests--;
1754                         results->outtimelimit = osp_choose_timelimit(results->intimelimit, results->outtimelimit);
1755                         ast_debug(1, "OSP: outtimelimit '%d'\n", results->outtimelimit);
1756                         ast_debug(1, "OSP: calling '%s'\n", callingnum);
1757                         ast_debug(1, "OSP: called '%s'\n", callednum);
1758                         ast_debug(1, "OSP: destination '%s'\n", destination);
1759                         ast_debug(1, "OSP: token size '%d'\n", tokenlen);
1760
1761                         if ((res = osp_check_destination(provider, callingnum, callednum, destination, tokenlen, token, &reason, results)) > 0) {
1762                                 break;
1763                         } else if (!results->numdests) {
1764                                 ast_debug(1, "OSP: No more destination\n");
1765                                 OSPPTransactionRecordFailure(results->outhandle, reason);
1766                                 if (results->inhandle != OSP_INVALID_HANDLE) {
1767                                         OSPPTransactionRecordFailure(results->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
1768                                 }
1769                                 res = OSP_FAILED;
1770                                 break;
1771                         }
1772                 } else {
1773                         ast_debug(1, "OSP: Unable to get route, error '%d'\n", error);
1774                         results->numdests = 0;
1775                         results->outtimelimit = OSP_DEF_TIMELIMIT;
1776                         if (results->inhandle != OSP_INVALID_HANDLE) {
1777                                 OSPPTransactionRecordFailure(results->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
1778                         }
1779                         res = OSP_ERROR;
1780                         break;
1781                 }
1782         }
1783
1784         return res;
1785 }
1786
1787 /*!
1788  * \brief OSP Lookup Next function
1789  * \param name OSP provider name
1790  * \param cause Asterisk hangup cuase
1791  * \param results Lookup results, in/output
1792  * \return OSP_OK Found , OSP_FAILED No route, OSP_ERROR Error
1793  */
1794 static int osp_next(
1795         const char* name,
1796         int cause,
1797         struct osp_results* results)
1798 {
1799         int res;
1800         struct osp_provider* provider = NULL;
1801         char calling[OSP_SIZE_NORSTR];
1802         char called[OSP_SIZE_NORSTR];
1803         char dest[OSP_SIZE_NORSTR];
1804         unsigned int tokenlen;
1805         char token[OSP_SIZE_TOKSTR];
1806         OSPEFAILREASON reason;
1807         OSPE_OPERATOR_NAME type;
1808         int error;
1809
1810         if (results == NULL) {
1811                 ast_log(LOG_ERROR, "Invalid parameters\n");
1812                 res = OSP_ERROR;
1813         }
1814
1815         results->outtech[0] = '\0';
1816         results->dest[0] = '\0';
1817         results->calling[0] = '\0';
1818         results->called[0] = '\0';
1819         results->token[0] = '\0';
1820         results->networkid[0] = '\0';
1821         results->nprn[0] = '\0';
1822         results->npcic[0] = '\0';
1823         results->npdi = 0;
1824         for (type = OSPC_OPNAME_START; type < OSPC_OPNAME_NUMBER; type++) {
1825                 results->opname[type][0] = '\0';
1826         }
1827         results->outtimelimit = OSP_DEF_TIMELIMIT;
1828
1829         if ((res = osp_get_provider(name, &provider)) <= 0) {
1830                 ast_debug(1, "OSP: Unabe to find OSP provider '%s'\n", name);
1831                 return res;
1832         }
1833
1834         if (results->outhandle == OSP_INVALID_HANDLE) {
1835                 ast_debug(1, "OSP: Transaction handle undefined\n");
1836                 results->numdests = 0;
1837                 if (results->inhandle != OSP_INVALID_HANDLE) {
1838                         OSPPTransactionRecordFailure(results->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
1839                 }
1840                 return OSP_ERROR;
1841         }
1842
1843         reason = asterisk2osp(cause);
1844
1845         if (!results->numdests) {
1846                 ast_debug(1, "OSP: No more destination\n");
1847                 OSPPTransactionRecordFailure(results->outhandle, reason);
1848                 if (results->inhandle != OSP_INVALID_HANDLE) {
1849                         OSPPTransactionRecordFailure(results->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
1850                 }
1851                 return OSP_FAILED;
1852         }
1853
1854         while(results->numdests) {
1855                 results->outcallid.len = sizeof(results->outcallid.buf);
1856                 tokenlen = sizeof(token);
1857                 error = OSPPTransactionGetNextDestination(
1858                         results->outhandle,
1859                         reason,
1860                         0,
1861                         NULL,
1862                         NULL,
1863                         &results->outtimelimit,
1864                         &results->outcallid.len,
1865                         results->outcallid.buf,
1866                         sizeof(called),
1867                         called,
1868                         sizeof(calling),
1869                         calling,
1870                         sizeof(dest),
1871                         dest,
1872                         0,
1873                         NULL,
1874                         &tokenlen,
1875                         token);
1876                 if (error == OSPC_ERR_NO_ERROR) {
1877                         results->numdests--;
1878                         results->outtimelimit = osp_choose_timelimit(results->intimelimit, results->outtimelimit);
1879                         ast_debug(1, "OSP: outtimelimit '%d'\n", results->outtimelimit);
1880                         ast_debug(1, "OSP: calling '%s'\n", calling);
1881                         ast_debug(1, "OSP: called '%s'\n", called);
1882                         ast_debug(1, "OSP: destination '%s'\n", dest);
1883                         ast_debug(1, "OSP: token size '%d'\n", tokenlen);
1884
1885                         if ((res = osp_check_destination(provider, calling, called, dest, tokenlen, token, &reason, results)) > 0) {
1886                                 res = OSP_OK;
1887                                 break;
1888                         } else if (!results->numdests) {
1889                                 ast_debug(1, "OSP: No more destination\n");
1890                                 OSPPTransactionRecordFailure(results->outhandle, reason);
1891                                 if (results->inhandle != OSP_INVALID_HANDLE) {
1892                                         OSPPTransactionRecordFailure(results->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
1893                                 }
1894                                 res = OSP_FAILED;
1895                                 break;
1896                         }
1897                 } else {
1898                         ast_debug(1, "OSP: Unable to get route, error '%d'\n", error);
1899                         results->token[0] = '\0';
1900                         results->numdests = 0;
1901                         results->outtimelimit = OSP_DEF_TIMELIMIT;
1902                         if (results->inhandle != OSP_INVALID_HANDLE) {
1903                                 OSPPTransactionRecordFailure(results->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
1904                         }
1905                         res = OSP_ERROR;
1906                         break;
1907                 }
1908         }
1909
1910         return res;
1911 }
1912
1913 /*!
1914  * \brief Get integer from variable string
1915  * \param vstr Variable string
1916  * \return OSP_DEF_INTSTATS Error
1917  */
1918 static int osp_get_varint(
1919         const char* vstr)
1920 {
1921         char* tmp;
1922         int value = OSP_DEF_INTSTATS;
1923
1924         if (!ast_strlen_zero(vstr)) {
1925                 if ((tmp = strchr(vstr, '=')) != NULL) {
1926                         tmp++;
1927                         if (sscanf(tmp, "%30d", &value) != 1) {
1928                                 value = OSP_DEF_INTSTATS;
1929                         }
1930                 }
1931         }
1932
1933         return value;
1934 }
1935
1936 /*!
1937  * \brief Get float from variable string
1938  * \param vstr Variable string
1939  * \return OSP_DEF_FLOATSTATS Error
1940  */
1941 static float osp_get_varfloat(
1942         const char* vstr)
1943 {
1944         char* tmp;
1945         float value = OSP_DEF_FLOATSTATS;
1946
1947         if (!ast_strlen_zero(vstr)) {
1948                 if ((tmp = strchr(vstr, '=')) != NULL) {
1949                         tmp++;
1950                         if (sscanf(tmp, "%30f", &value) != 1) {
1951                                 value = OSP_DEF_FLOATSTATS;
1952                         }
1953                 }
1954         }
1955
1956         return value;
1957 }
1958
1959 /*!
1960  * \brief Report QoS
1961  * \param trans OSP in/outbound transaction handle
1962  * \param leg Inbound/outbound
1963  * \param qos QoS string
1964  * \return OSP_OK Success, OSP_FAILED Failed, OSP_ERROR Error
1965  */
1966 static int osp_report_qos(
1967         int trans,
1968         enum osp_callleg leg,
1969         const char* qos)
1970 {
1971         int res = OSP_FAILED;
1972         enum osp_direction dir;
1973         char buffer[OSP_SIZE_NORSTR];
1974         char* tmp;
1975         char* item;
1976         int totalpackets[OSP_DIR_NUMBER];
1977         struct osp_metrics lost[OSP_DIR_NUMBER];
1978         struct osp_metrics jitter[OSP_DIR_NUMBER];
1979         struct osp_metrics rtt;
1980         int value;
1981
1982         if (!ast_strlen_zero(qos)) {
1983                 for (dir = OSP_DIR_RX; dir < OSP_DIR_NUMBER; dir++) {
1984                         totalpackets[dir] = OSP_DEF_INTSTATS;
1985                 }
1986
1987                 for (dir = OSP_DIR_RX; dir < OSP_DIR_NUMBER; dir++) {
1988                         lost[dir].value = OSP_DEF_INTSTATS;
1989                         lost[dir].min = OSP_DEF_FLOATSTATS;
1990                         lost[dir].max = OSP_DEF_FLOATSTATS;
1991                         lost[dir].avg = OSP_DEF_FLOATSTATS;
1992                         lost[dir].sdev = OSP_DEF_FLOATSTATS;
1993                 }
1994
1995                 for (dir = OSP_DIR_RX; dir < OSP_DIR_NUMBER; dir++) {
1996                         jitter[dir].value = OSP_DEF_INTSTATS;
1997                         jitter[dir].min = OSP_DEF_FLOATSTATS;
1998                         jitter[dir].max = OSP_DEF_FLOATSTATS;
1999                         jitter[dir].avg = OSP_DEF_FLOATSTATS;
2000                         jitter[dir].sdev = OSP_DEF_FLOATSTATS;
2001                 }
2002
2003                 rtt.value = OSP_DEF_INTSTATS;
2004                 rtt.min = OSP_DEF_FLOATSTATS;
2005                 rtt.max = OSP_DEF_FLOATSTATS;
2006                 rtt.avg = OSP_DEF_FLOATSTATS;
2007                 rtt.sdev = OSP_DEF_FLOATSTATS;
2008
2009                 ast_copy_string(buffer, qos, sizeof(buffer));
2010                 for (item = strtok_r(buffer, ";", &tmp); item; item = strtok_r(NULL, ";", &tmp)) {
2011                         if (!strncasecmp(item, "rxcount", strlen("rxcount"))) {
2012                                 totalpackets[OSP_DIR_RX] = osp_get_varint(item);
2013                         } else if (!strncasecmp(item, "txcount", strlen("txcount"))) {
2014                                 totalpackets[OSP_DIR_TX] = osp_get_varint(item);
2015                         } else if (!strncasecmp(item, "lp", strlen("lp"))) {
2016                                 lost[OSP_DIR_RX].value = osp_get_varint(item);
2017                         } else if (!strncasecmp(item, "minrxlost", strlen("minrxlost"))) {
2018                                 lost[OSP_DIR_RX].min = osp_get_varfloat(item);
2019                         } else if (!strncasecmp(item, "maxrxlost", strlen("maxrxlost"))) {
2020                                 lost[OSP_DIR_RX].max = osp_get_varfloat(item);
2021                         } else if (!strncasecmp(item, "avgrxlost", strlen("avgrxlost"))) {
2022                                 lost[OSP_DIR_RX].avg = osp_get_varfloat(item);
2023                         } else if (!strncasecmp(item, "stdevrxlost", strlen("stdevrxlost"))) {
2024                                 lost[OSP_DIR_RX].sdev = osp_get_varfloat(item);
2025                         } else if (!strncasecmp(item, "rlp", strlen("rlp"))) {
2026                                 lost[OSP_DIR_TX].value = osp_get_varint(item);
2027                         } else if (!strncasecmp(item, "reported_minlost", strlen("reported_minlost"))) {
2028                                 lost[OSP_DIR_TX].min = osp_get_varfloat(item);
2029                         } else if (!strncasecmp(item, "reported_maxlost", strlen("reported_maxlost"))) {
2030                                 lost[OSP_DIR_TX].max = osp_get_varfloat(item);
2031                         } else if (!strncasecmp(item, "reported_avglost", strlen("reported_avglost"))) {
2032                                 lost[OSP_DIR_TX].avg = osp_get_varfloat(item);
2033                         } else if (!strncasecmp(item, "reported_stdevlost", strlen("reported_stdevlost"))) {
2034                                 lost[OSP_DIR_TX].sdev = osp_get_varfloat(item);
2035                         } else if (!strncasecmp(item, "rxjitter", strlen("rxjitter"))) {
2036                                 jitter[OSP_DIR_RX].value = osp_get_varint(item);
2037                         } else if (!strncasecmp(item, "minrxjitter", strlen("minrxjitter"))) {
2038                                 jitter[OSP_DIR_RX].min = osp_get_varfloat(item);
2039                         } else if (!strncasecmp(item, "maxrxjitter", strlen("maxrxjitter"))) {
2040                                 jitter[OSP_DIR_RX].max = osp_get_varfloat(item);
2041                         } else if (!strncasecmp(item, "avgrxjitter", strlen("avgjitter"))) {
2042                                 jitter[OSP_DIR_RX].avg = osp_get_varfloat(item);
2043                         } else if (!strncasecmp(item, "stdevrxjitter", strlen("stdevjitter"))) {
2044                                 jitter[OSP_DIR_RX].sdev = osp_get_varfloat(item);
2045                         } else if (!strncasecmp(item, "txjitter", strlen("txjitter"))) {
2046                                 jitter[OSP_DIR_TX].value = osp_get_varint(item);
2047                         } else if (!strncasecmp(item, "reported_minjitter", strlen("reported_minjitter"))) {
2048                                 jitter[OSP_DIR_TX].min = osp_get_varfloat(item);
2049                         } else if (!strncasecmp(item, "reported_maxjitter", strlen("reported_maxjitter"))) {
2050                                 jitter[OSP_DIR_TX].max = osp_get_varfloat(item);
2051                         } else if (!strncasecmp(item, "reported_avgjitter", strlen("reported_avgjitter"))) {
2052                                 jitter[OSP_DIR_TX].avg = osp_get_varfloat(item);
2053                         } else if (!strncasecmp(item, "reported_stdevjitter", strlen("reported_stdevjitter"))) {
2054                                 jitter[OSP_DIR_TX].sdev = osp_get_varfloat(item);
2055                         } else if (!strncasecmp(item, "rtt", strlen("rtt"))) {
2056                                 rtt.value = osp_get_varint(item);
2057                         } else if (!strncasecmp(item, "minrtt", strlen("minrtt"))) {
2058                                 rtt.min = osp_get_varfloat(item);
2059                         } else if (!strncasecmp(item, "maxrtt", strlen("maxrtt"))) {
2060                                 rtt.max = osp_get_varfloat(item);
2061                         } else if (!strncasecmp(item, "avgrtt", strlen("avgrtt"))) {
2062                                 rtt.avg = osp_get_varfloat(item);
2063                         } else if (!strncasecmp(item, "stdevrtt", strlen("stdevrtt"))) {
2064                                 rtt.sdev = osp_get_varfloat(item);
2065                         }
2066                 }
2067
2068                 ast_debug(1, "OSP: call leg '%d'\n", leg);
2069                 ast_debug(1, "OSP: rxcount '%d'\n", totalpackets[OSP_DIR_RX]);
2070                 ast_debug(1, "OSP: txcount '%d'\n", totalpackets[OSP_DIR_TX]);
2071                 ast_debug(1, "OSP: lp '%d'\n",lost[OSP_DIR_RX].value);
2072                 ast_debug(1, "OSP: minrxlost '%f'\n", lost[OSP_DIR_RX].min);
2073                 ast_debug(1, "OSP: maxrxlost '%f'\n", lost[OSP_DIR_RX].max);
2074                 ast_debug(1, "OSP: avgrxlost '%f'\n", lost[OSP_DIR_RX].avg);
2075                 ast_debug(1, "OSP: stdevrxlost '%f'\n", lost[OSP_DIR_RX].sdev);
2076                 ast_debug(1, "OSP: rlp '%d'\n", lost[OSP_DIR_TX].value);
2077                 ast_debug(1, "OSP: reported_minlost '%f'\n", lost[OSP_DIR_TX].min);
2078                 ast_debug(1, "OSP: reported_maxlost '%f'\n", lost[OSP_DIR_TX].max);
2079                 ast_debug(1, "OSP: reported_avglost '%f'\n", lost[OSP_DIR_TX].avg);
2080                 ast_debug(1, "OSP: reported_stdevlost '%f'\n", lost[OSP_DIR_TX].sdev);
2081                 ast_debug(1, "OSP: rxjitter '%d'\n", jitter[OSP_DIR_RX].value);
2082                 ast_debug(1, "OSP: minrxjitter '%f'\n", jitter[OSP_DIR_RX].min);
2083                 ast_debug(1, "OSP: maxrxjitter '%f'\n", jitter[OSP_DIR_RX].max);
2084                 ast_debug(1, "OSP: avgrxjitter '%f'\n", jitter[OSP_DIR_RX].avg);
2085                 ast_debug(1, "OSP: stdevrxjitter '%f'\n", jitter[OSP_DIR_RX].sdev);
2086                 ast_debug(1, "OSP: txjitter '%d'\n", jitter[OSP_DIR_TX].value);
2087                 ast_debug(1, "OSP: reported_minjitter '%f'\n", jitter[OSP_DIR_TX].min);
2088                 ast_debug(1, "OSP: reported_maxjitter '%f'\n", jitter[OSP_DIR_TX].max);
2089                 ast_debug(1, "OSP: reported_avgjitter '%f'\n", jitter[OSP_DIR_TX].avg);
2090                 ast_debug(1, "OSP: reported_stdevjitter '%f'\n", jitter[OSP_DIR_TX].sdev);
2091                 ast_debug(1, "OSP: rtt '%d'\n", rtt.value);
2092                 ast_debug(1, "OSP: minrtt '%f'\n", rtt.min);
2093                 ast_debug(1, "OSP: maxrtt '%f'\n", rtt.max);
2094                 ast_debug(1, "OSP: avgrtt '%f'\n", rtt.avg);
2095                 ast_debug(1, "OSP: stdevrtt '%f'\n", rtt.sdev);
2096
2097                 if (leg == OSP_CALL_INBOUND) {
2098                         OSPPTransactionSetPackets(trans, OSPC_SMETRIC_RTP, OSPC_SDIR_SRCREP, totalpackets[OSP_DIR_RX]);
2099                         OSPPTransactionSetPackets(trans, OSPC_SMETRIC_RTCP, OSPC_SDIR_DESTREP, totalpackets[OSP_DIR_TX]);
2100                         if (lost[OSP_DIR_RX].value >= 0) {
2101                                 value = lost[OSP_DIR_RX].value;
2102                         } else {
2103                                 value = (int)lost[OSP_DIR_RX].avg;
2104                         }
2105                         OSPPTransactionSetLost(trans, OSPC_SMETRIC_RTP, OSPC_SDIR_SRCREP, value, OSP_DEF_INTSTATS);
2106                         if (lost[OSP_DIR_TX].value >= 0) {
2107                                 value = lost[OSP_DIR_TX].value;
2108                         } else {
2109                                 value = (int)lost[OSP_DIR_TX].avg;
2110                         }
2111                         OSPPTransactionSetLost(trans, OSPC_SMETRIC_RTCP, OSPC_SDIR_DESTREP, value, OSP_DEF_INTSTATS);
2112                         if (jitter[OSP_DIR_RX].value >= 0) {
2113                                 value = jitter[OSP_DIR_RX].value;
2114                         } else {
2115                                 value = (int)jitter[OSP_DIR_RX].avg;
2116                         }
2117                         OSPPTransactionSetJitter(trans,
2118                                 OSPC_SMETRIC_RTP,
2119                                 OSPC_SDIR_SRCREP,
2120                                 OSP_DEF_INTSTATS,
2121                                 (int)jitter[OSP_DIR_RX].min,
2122                                 (int)jitter[OSP_DIR_RX].max,
2123                                 value, jitter[OSP_DIR_RX].sdev);
2124                         if (jitter[OSP_DIR_TX].value >= 0) {
2125                                 value = jitter[OSP_DIR_TX].value;
2126                         } else {
2127                                 value = (int)jitter[OSP_DIR_TX].avg;
2128                         }
2129                         OSPPTransactionSetJitter(trans, OSPC_SMETRIC_RTCP, OSPC_SDIR_DESTREP,
2130                                 OSP_DEF_INTSTATS, (int)jitter[OSP_DIR_TX].min, (int)jitter[OSP_DIR_TX].max, value, jitter[OSP_DIR_TX].sdev);
2131                 } else {
2132                         OSPPTransactionSetPackets(trans, OSPC_SMETRIC_RTP, OSPC_SDIR_DESTREP, totalpackets[OSP_DIR_RX]);
2133                         OSPPTransactionSetPackets(trans, OSPC_SMETRIC_RTCP, OSPC_SDIR_SRCREP, totalpackets[OSP_DIR_TX]);
2134                         OSPPTransactionSetLost(trans, OSPC_SMETRIC_RTP, OSPC_SDIR_DESTREP, lost[OSP_DIR_RX].value, OSP_DEF_INTSTATS);
2135                         OSPPTransactionSetLost(trans, OSPC_SMETRIC_RTCP, OSPC_SDIR_SRCREP, lost[OSP_DIR_TX].value, OSP_DEF_INTSTATS);
2136                         if (jitter[OSP_DIR_RX].value >= 0) {
2137                                 value = jitter[OSP_DIR_RX].value;
2138                         } else {
2139                                 value = (int)jitter[OSP_DIR_RX].avg;
2140                         }
2141                         OSPPTransactionSetJitter(trans,
2142                                 OSPC_SMETRIC_RTP,
2143                                 OSPC_SDIR_DESTREP,
2144                                 OSP_DEF_INTSTATS,
2145                                 (int)jitter[OSP_DIR_RX].min,
2146                                 (int)jitter[OSP_DIR_RX].max,
2147                                 value,
2148                                 jitter[OSP_DIR_RX].sdev);
2149                         if (jitter[OSP_DIR_TX].value >= 0) {
2150                                 value = jitter[OSP_DIR_TX].value;
2151                         } else {
2152                                 value = (int)jitter[OSP_DIR_TX].avg;
2153                         }
2154                         OSPPTransactionSetJitter(trans,
2155                                 OSPC_SMETRIC_RTCP,
2156                                 OSPC_SDIR_SRCREP,
2157                                 OSP_DEF_INTSTATS,
2158                                 (int)jitter[OSP_DIR_TX].min,
2159                                 (int)jitter[OSP_DIR_TX].max,
2160                                 value,
2161                                 jitter[OSP_DIR_TX].sdev);
2162                 }
2163
2164                 res = OSP_OK;
2165         }
2166
2167         return res;
2168 }
2169
2170 /*!
2171  * \brief OSP Finish function
2172  * \param trans OSP in/outbound transaction handle
2173  * \param recorded If failure reason has been recorded
2174  * \param cause Asterisk hangup cause
2175  * \param start Call start time
2176  * \param connect Call connect time
2177  * \param end Call end time
2178  * \param release Who release first, 0 source, 1 destination
2179  * \param inqos Inbound QoS string
2180  * \param outqos Outbound QoS string
2181  * \return OSP_OK Success, OSP_FAILED Failed, OSP_ERROR Error
2182  */
2183 static int osp_finish(
2184         int trans,
2185         int recorded,
2186         int cause,
2187         time_t start,
2188         time_t connect,
2189         time_t end,
2190         unsigned int release,
2191         const char* inqos,
2192         const char* outqos)
2193 {
2194         int res;
2195         OSPEFAILREASON reason;
2196         time_t alert = 0;
2197         unsigned isPddInfoPresent = 0;
2198         unsigned pdd = 0;
2199         unsigned int dummy = 0;
2200         int error;
2201
2202         if (trans == OSP_INVALID_HANDLE) {
2203                 return OSP_FAILED;
2204         }
2205
2206         OSPPTransactionSetRoleInfo(trans, OSPC_RSTATE_STOP, OSPC_RFORMAT_OSP, OSPC_RVENDOR_ASTERISK);
2207
2208         if (!recorded) {
2209                 reason = asterisk2osp(cause);
2210                 OSPPTransactionRecordFailure(trans, reason);
2211         }
2212
2213         osp_report_qos(trans, OSP_CALL_INBOUND, inqos);
2214         osp_report_qos(trans, OSP_CALL_OUTBOUND, outqos);
2215
2216         error = OSPPTransactionReportUsage(trans,
2217                 difftime(end, connect),
2218                 start,
2219                 end,
2220                 alert,
2221                 connect,
2222                 isPddInfoPresent,
2223                 pdd,
2224                 release,
2225                 NULL,
2226                 OSP_DEF_INTSTATS,
2227                 OSP_DEF_INTSTATS,
2228                 OSP_DEF_INTSTATS,
2229                 OSP_DEF_INTSTATS,
2230                 &dummy,
2231                 NULL);
2232         if (error == OSPC_ERR_NO_ERROR) {
2233                 ast_debug(1, "OSP: Usage reported\n");
2234                 res = OSP_OK;
2235         } else {
2236                 ast_debug(1, "OSP: Unable to report usage, error '%d'\n", error);
2237                 res = OSP_ERROR;
2238         }
2239         OSPPTransactionDelete(trans);
2240
2241         return res;
2242 }
2243
2244 /* OSP Application APIs */
2245
2246 /*!
2247  * \brief OSP Application OSPAuth
2248  * \param chan Channel
2249  * \param data Parameter
2250  * \return OSP_AST_OK Success, OSP_AST_ERROR Error
2251  */
2252 static int ospauth_exec(
2253         struct ast_channel *chan,
2254         const char *data)
2255 {
2256         int res;
2257         const char* provider = OSP_DEF_PROVIDER;
2258         struct varshead* headp;
2259         struct ast_var_t* current;
2260         const char* source = "";
2261         const char* token = "";
2262         int handle;
2263         unsigned int timelimit;
2264         char buffer[OSP_SIZE_INTSTR];
2265         const char* status;
2266         char* tmp;
2267
2268         AST_DECLARE_APP_ARGS(args,
2269                 AST_APP_ARG(provider);
2270                 AST_APP_ARG(options);
2271         );
2272
2273         if (!(tmp = ast_strdupa(data))) {
2274                 ast_log(LOG_ERROR, "Out of memory\n");
2275                 return OSP_AST_ERROR;
2276         }
2277
2278         AST_STANDARD_APP_ARGS(args, tmp);
2279
2280         if (!ast_strlen_zero(args.provider)) {
2281                 provider = args.provider;
2282         }
2283         ast_debug(1, "OSPAuth: provider '%s'\n", provider);
2284
2285         headp = &chan->varshead;
2286         AST_LIST_TRAVERSE(headp, current, entries) {
2287                 if (!strcasecmp(ast_var_name(current), "OSPINPEERIP")) {
2288                         source = ast_var_value(current);
2289                 } else if (!strcasecmp(ast_var_name(current), "OSPINTOKEN")) {
2290                         token = ast_var_value(current);
2291                 }
2292         }
2293
2294         ast_debug(1, "OSPAuth: source '%s'\n", source);
2295         ast_debug(1, "OSPAuth: token size '%zd'\n", strlen(token));
2296
2297         res = osp_auth(provider, &handle, source,
2298                 S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL),
2299                 chan->exten, token, &timelimit);
2300         if (res > 0) {
2301                 status = AST_OSP_SUCCESS;
2302         } else {
2303                 timelimit = OSP_DEF_TIMELIMIT;
2304                 if (!res) {
2305                         status = AST_OSP_FAILED;
2306                 } else {
2307                         status = AST_OSP_ERROR;
2308                 }
2309         }
2310
2311         snprintf(buffer, sizeof(buffer), "%d", handle);
2312         pbx_builtin_setvar_helper(chan, "OSPINHANDLE", buffer);
2313         ast_debug(1, "OSPAuth: OSPINHANDLE '%s'\n", buffer);
2314         snprintf(buffer, sizeof(buffer), "%d", timelimit);
2315         pbx_builtin_setvar_helper(chan, "OSPINTIMELIMIT", buffer);
2316         ast_debug(1, "OSPAuth: OSPINTIMELIMIT '%s'\n", buffer);
2317         pbx_builtin_setvar_helper(chan, "OSPAUTHSTATUS", status);
2318         ast_debug(1, "OSPAuth: %s\n", status);
2319
2320         if(res != OSP_OK) {
2321                 res = OSP_AST_ERROR;
2322         } else {
2323                 res = OSP_AST_OK;
2324         }
2325
2326         return res;
2327 }
2328
2329 /*!
2330  * \brief OSP Application OSPLookup
2331  * \param chan Channel
2332  * \param data Parameter
2333  * \return OSP_AST_OK Success, OSP_AST_ERROR Error
2334  */
2335 static int osplookup_exec(
2336         struct ast_channel* chan,
2337         const char * data)
2338 {
2339         int res, cres;
2340         const char* provider = OSP_DEF_PROVIDER;
2341         unsigned int callidtypes = OSP_CALLID_UNDEF;
2342         struct varshead* headp;
2343         struct ast_var_t* current;
2344         const char* actualsrc = "";
2345         const char* srcdev = "";
2346         const char* snetid = "";
2347         struct osp_npdata np;
2348         OSPE_OPERATOR_NAME type;
2349         struct osp_headers headers;
2350         unsigned int i;
2351         const char* cinfo[OSP_MAX_CUSTOMINFO] = { NULL };
2352         char buffer[OSP_SIZE_TOKSTR];
2353         struct osp_results results;
2354         const char* status;
2355         char* tmp;
2356
2357         AST_DECLARE_APP_ARGS(args,
2358                 AST_APP_ARG(exten);
2359                 AST_APP_ARG(provider);
2360                 AST_APP_ARG(options);
2361         );
2362
2363         if (ast_strlen_zero(data)) {
2364                 ast_log(LOG_WARNING, "OSPLookup: Arg required, OSPLookup(exten[,provider[,options]])\n");
2365                 return OSP_AST_ERROR;
2366         }
2367
2368         if (!(tmp = ast_strdupa(data))) {
2369                 ast_log(LOG_ERROR, "Out of memory\n");
2370                 return OSP_AST_ERROR;
2371         }
2372
2373         AST_STANDARD_APP_ARGS(args, tmp);
2374
2375         ast_debug(1, "OSPLookup: exten '%s'\n", args.exten);
2376
2377         if (!ast_strlen_zero(args.provider)) {
2378                 provider = args.provider;
2379         }
2380         ast_debug(1, "OSPlookup: provider '%s'\n", provider);
2381
2382         if (args.options) {
2383                 if (strchr(args.options, 'h')) {
2384                         callidtypes |= OSP_CALLID_H323;
2385                 }
2386                 if (strchr(args.options, 's')) {
2387                         callidtypes |= OSP_CALLID_SIP;
2388                 }
2389                 if (strchr(args.options, 'i')) {
2390                         callidtypes |= OSP_CALLID_IAX;
2391                 }
2392         }
2393         ast_debug(1, "OSPLookup: call id types '%d'\n", callidtypes);
2394
2395         results.inhandle = OSP_INVALID_HANDLE;
2396         results.intimelimit = OSP_DEF_TIMELIMIT;
2397         results.dest[0] = '\0';
2398
2399         np.rn = "";
2400         np.cic = "";
2401         np.npdi = 0;
2402         for (type = OSPC_OPNAME_START; type < OSPC_OPNAME_NUMBER; type++) {
2403                 np.opname[type] = "";
2404         }
2405
2406         headers.rpiduser = "";
2407         headers.paiuser = "";
2408         headers.divuser = "";
2409         headers.divhost = "";
2410         headers.pciuser = "";
2411
2412         headp = &chan->varshead;
2413         AST_LIST_TRAVERSE(headp, current, entries) {
2414                 if (!strcasecmp(ast_var_name(current), "OSPINACTUALSRC")) {
2415                         actualsrc = ast_var_value(current);
2416                 } else if (!strcasecmp(ast_var_name(current), "OSPINPEERIP")) {
2417                         srcdev = ast_var_value(current);
2418                 } else if (!strcasecmp(ast_var_name(current), "OSPINTECH")) {
2419                         ast_copy_string(results.intech, ast_var_value(current), sizeof(results.intech));
2420                 } else if (!strcasecmp(ast_var_name(current), "OSPINHANDLE")) {
2421                         if (sscanf(ast_var_value(current), "%30d", &results.inhandle) != 1) {
2422                                 results.inhandle = OSP_INVALID_HANDLE;
2423                         }
2424                 } else if (!strcasecmp(ast_var_name(current), "OSPINTIMELIMIT")) {
2425                         if (sscanf(ast_var_value(current), "%30d", &results.intimelimit) != 1) {
2426                                 results.intimelimit = OSP_DEF_TIMELIMIT;
2427                         }
2428                 } else if (!strcasecmp(ast_var_name(current), "OSPINNETWORKID")) {
2429                         snetid = ast_var_value(current);
2430                 } else if (!strcasecmp(ast_var_name(current), "OSPINNPRN")) {
2431                         np.rn = ast_var_value(current);
2432                 } else if (!strcasecmp(ast_var_name(current), "OSPINNPCIC")) {
2433                         np.cic = ast_var_value(current);
2434                 } else if (!strcasecmp(ast_var_name(current), "OSPINNPDI")) {
2435                         if (ast_true(ast_var_value(current))) {
2436                                 np.npdi = 1;
2437                         }
2438                 } else if (!strcasecmp(ast_var_name(current), "OSPINSPID")) {
2439                         np.opname[OSPC_OPNAME_SPID] = ast_var_value(current);
2440                 } else if (!strcasecmp(ast_var_name(current), "OSPINOCN")) {
2441                         np.opname[OSPC_OPNAME_OCN] = ast_var_value(current);
2442                 } else if (!strcasecmp(ast_var_name(current), "OSPINSPN")) {
2443                         np.opname[OSPC_OPNAME_SPN] = ast_var_value(current);
2444                 } else if (!strcasecmp(ast_var_name(current), "OSPINALTSPN")) {
2445                         np.opname[OSPC_OPNAME_ALTSPN] = ast_var_value(current);
2446                 } else if (!strcasecmp(ast_var_name(current), "OSPINMCC")) {
2447                         np.opname[OSPC_OPNAME_MCC] = ast_var_value(current);
2448                 } else if (!strcasecmp(ast_var_name(current), "OSPINMNC")) {
2449                         np.opname[OSPC_OPNAME_MNC] = ast_var_value(current);
2450                 } else if (!strcasecmp(ast_var_name(current), "OSPINTOHOST")) {
2451                         ast_copy_string(results.dest, ast_var_value(current), sizeof(results.dest));
2452                 } else if (!strcasecmp(ast_var_name(current), "OSPINRPIDUSER")) {
2453                         headers.rpiduser = ast_var_value(current);
2454                 } else if (!strcasecmp(ast_var_name(current), "OSPINPAIUSER")) {
2455                         headers.paiuser = ast_var_value(current);
2456                 } else if (!strcasecmp(ast_var_name(current), "OSPINDIVUSER")) {
2457                         headers.divuser = ast_var_value(current);
2458                 } else if (!strcasecmp(ast_var_name(current), "OSPINDIVHOST")) {
2459                         headers.divhost = ast_var_value(current);
2460                 } else if (!strcasecmp(ast_var_name(current), "OSPINPCIUSER")) {
2461                         headers.pciuser = ast_var_value(current);
2462                 } else if (!strcasecmp(ast_var_name(current), "OSPINCUSTOMINFO1")) {
2463                         cinfo[0] = ast_var_value(current);
2464                 } else if (!strcasecmp(ast_var_name(current), "OSPINCUSTOMINFO2")) {
2465                         cinfo[1] = ast_var_value(current);
2466                 } else if (!strcasecmp(ast_var_name(current), "OSPINCUSTOMINFO3")) {
2467                         cinfo[2] = ast_var_value(current);
2468                 } else if (!strcasecmp(ast_var_name(current), "OSPINCUSTOMINFO4")) {
2469                         cinfo[3] = ast_var_value(current);
2470                 } else if (!strcasecmp(ast_var_name(current), "OSPINCUSTOMINFO5")) {
2471                         cinfo[4] = ast_var_value(current);
2472                 } else if (!strcasecmp(ast_var_name(current), "OSPINCUSTOMINFO6")) {
2473                         cinfo[5] = ast_var_value(current);
2474                 } else if (!strcasecmp(ast_var_name(current), "OSPINCUSTOMINFO7")) {
2475                         cinfo[6] = ast_var_value(current);
2476                 } else if (!strcasecmp(ast_var_name(current), "OSPINCUSTOMINFO8")) {
2477                         cinfo[7] = ast_var_value(current);
2478                 }
2479         }
2480         ast_debug(1, "OSPLookup: actual source device '%s'\n", actualsrc);
2481         ast_debug(1, "OSPLookup: source device '%s'\n", srcdev);
2482         ast_debug(1, "OSPLookup: OSPINTECH '%s'\n", results.intech);
2483         ast_debug(1, "OSPLookup: OSPINHANDLE '%d'\n", results.inhandle);
2484         ast_debug(1, "OSPLookup: OSPINTIMELIMIT '%d'\n", results.intimelimit);
2485         ast_debug(1, "OSPLookup: OSPINNETWORKID '%s'\n", snetid);
2486         ast_debug(1, "OSPLookup: OSPINNPRN '%s'\n", np.rn);
2487         ast_debug(1, "OSPLookup: OSPINNPCIC '%s'\n", np.cic);
2488         ast_debug(1, "OSPLookup: OSPINNPDI '%d'\n", np.npdi);
2489         ast_debug(1, "OSPLookup: OSPINSPID '%s'\n", np.opname[OSPC_OPNAME_SPID]);
2490         ast_debug(1, "OSPLookup: OSPINOCN '%s'\n", np.opname[OSPC_OPNAME_OCN]);
2491         ast_debug(1, "OSPLookup: OSPINSPN '%s'\n", np.opname[OSPC_OPNAME_SPN]);
2492         ast_debug(1, "OSPLookup: OSPINALTSPN '%s'\n", np.opname[OSPC_OPNAME_ALTSPN]);
2493         ast_debug(1, "OSPLookup: OSPINMCC '%s'\n", np.opname[OSPC_OPNAME_MCC]);
2494         ast_debug(1, "OSPLookup: OSPINMNC '%s'\n", np.opname[OSPC_OPNAME_MNC]);
2495         ast_debug(1, "OSPLookup: OSPINTOHOST '%s'\n", results.dest);
2496         ast_debug(1, "OSPLookup: OSPINRPIDUSER '%s'\n", headers.rpiduser);
2497         ast_debug(1, "OSPLookup: OSPINPAIUSER '%s'\n", headers.paiuser);
2498         ast_debug(1, "OSPLookup: OSPINDIVUSER '%s'\n", headers.divuser);
2499         ast_debug(1, "OSPLookup: OSPINDIVHOST'%s'\n", headers.divhost);
2500         ast_debug(1, "OSPLookup: OSPINPCIUSER '%s'\n", headers.pciuser);
2501         for (i = 0; i < OSP_MAX_CUSTOMINFO; i++) {
2502                 if (!ast_strlen_zero(cinfo[i])) {
2503                         ast_debug(1, "OSPLookup: OSPINCUSTOMINFO%d '%s'\n", i, cinfo[i]);
2504                 }
2505         }
2506
2507         if ((cres = ast_autoservice_start(chan)) < 0) {
2508                 return OSP_AST_ERROR;
2509         }
2510
2511         res = osp_lookup(provider, callidtypes, actualsrc, srcdev,
2512                 S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL),
2513                 args.exten, snetid, &np, &headers, cinfo, &results);
2514         if (res > 0) {
2515                 status = AST_OSP_SUCCESS;
2516         } else {
2517                 results.outtech[0] = '\0';
2518                 results.dest[0] = '\0';
2519                 results.calling[0] = '\0';
2520                 results.called[0] = '\0';
2521                 results.token[0] = '\0';
2522                 results.networkid[0] = '\0';
2523                 results.nprn[0] = '\0';
2524                 results.npcic[0] = '\0';
2525                 results.npdi = 0;
2526                 for (type = OSPC_OPNAME_START; type < OSPC_OPNAME_NUMBER; type++) {
2527                         results.opname[type][0] = '\0';
2528                 }
2529                 results.numdests = 0;
2530                 results.outtimelimit = OSP_DEF_TIMELIMIT;
2531                 results.outcallid.buf[0] = '\0';
2532                 results.outcallid.len = 0;
2533                 if (!res) {
2534                         status = AST_OSP_FAILED;
2535                 } else {
2536                         status = AST_OSP_ERROR;
2537                 }
2538         }
2539
2540         snprintf(buffer, sizeof(buffer), "%d", results.outhandle);
2541         pbx_builtin_setvar_helper(chan, "OSPOUTHANDLE", buffer);
2542         ast_debug(1, "OSPLookup: OSPOUTHANDLE '%s'\n", buffer);
2543         pbx_builtin_setvar_helper(chan, "OSPOUTTECH", results.outtech);
2544         ast_debug(1, "OSPLookup: OSPOUTTECH '%s'\n", results.outtech);
2545         pbx_builtin_setvar_helper(chan, "OSPDESTINATION", results.dest);
2546         ast_debug(1, "OSPLookup: OSPDESTINATION '%s'\n", results.dest);
2547         pbx_builtin_setvar_helper(chan, "OSPOUTCALLING", results.calling);
2548         ast_debug(1, "OSPLookup: OSPOUTCALLING '%s'\n", results.calling);
2549         pbx_builtin_setvar_helper(chan, "OSPOUTCALLED", results.called);
2550         ast_debug(1, "OSPLookup: OSPOUTCALLED '%s'\n", results.called);
2551         pbx_builtin_setvar_helper(chan, "OSPOUTNETWORKID", results.networkid);
2552         ast_debug(1, "OSPLookup: OSPOUTNETWORKID '%s'\n", results.networkid);
2553         pbx_builtin_setvar_helper(chan, "OSPOUTNPRN", results.nprn);
2554         ast_debug(1, "OSPLookup: OSPOUTNPRN '%s'\n", results.nprn);
2555         pbx_builtin_setvar_helper(chan, "OSPOUTNPCIC", results.npcic);
2556         ast_debug(1, "OSPLookup: OSPOUTNPCIC '%s'\n", results.npcic);
2557         snprintf(buffer, sizeof(buffer), "%d", results.npdi);
2558         pbx_builtin_setvar_helper(chan, "OSPOUTNPDI", buffer);
2559         ast_debug(1, "OSPLookup: OSPOUTNPDI'%s'\n", buffer);
2560         pbx_builtin_setvar_helper(chan, "OSPOUTSPID", results.opname[OSPC_OPNAME_SPID]);
2561         ast_debug(1, "OSPLookup: OSPOUTSPID '%s'\n", results.opname[OSPC_OPNAME_SPID]);
2562         pbx_builtin_setvar_helper(chan, "OSPOUTOCN", results.opname[OSPC_OPNAME_OCN]);
2563         ast_debug(1, "OSPLookup: OSPOUTOCN '%s'\n", results.opname[OSPC_OPNAME_OCN]);
2564         pbx_builtin_setvar_helper(chan, "OSPOUTSPN", results.opname[OSPC_OPNAME_SPN]);
2565         ast_debug(1, "OSPLookup: OSPOUTSPN '%s'\n", results.opname[OSPC_OPNAME_SPN]);
2566         pbx_builtin_setvar_helper(chan, "OSPOUTALTSPN", results.opname[OSPC_OPNAME_ALTSPN]);
2567         ast_debug(1, "OSPLookup: OSPOUTALTSPN '%s'\n", results.opname[OSPC_OPNAME_ALTSPN]);
2568         pbx_builtin_setvar_helper(chan, "OSPOUTMCC", results.opname[OSPC_OPNAME_MCC]);
2569         ast_debug(1, "OSPLookup: OSPOUTMCC '%s'\n", results.opname[OSPC_OPNAME_MCC]);
2570         pbx_builtin_setvar_helper(chan, "OSPOUTMNC", results.opname[OSPC_OPNAME_MNC]);
2571         ast_debug(1, "OSPLookup: OSPOUTMNC '%s'\n", results.opname[OSPC_OPNAME_MNC]);
2572         pbx_builtin_setvar_helper(chan, "OSPOUTTOKEN", results.token);
2573         ast_debug(1, "OSPLookup: OSPOUTTOKEN size '%zd'\n", strlen(results.token));
2574         snprintf(buffer, sizeof(buffer), "%d", results.numdests);
2575         pbx_builtin_setvar_helper(chan, "OSPDESTREMAILS", buffer);
2576         ast_debug(1, "OSPLookup: OSPDESTREMAILS '%s'\n", buffer);
2577         snprintf(buffer, sizeof(buffer), "%d", results.outtimelimit);
2578         pbx_builtin_setvar_helper(chan, "OSPOUTTIMELIMIT", buffer);
2579         ast_debug(1, "OSPLookup: OSPOUTTIMELIMIT '%s'\n", buffer);
2580         snprintf(buffer, sizeof(buffer), "%d", callidtypes);
2581         pbx_builtin_setvar_helper(chan, "OSPOUTCALLIDTYPES", buffer);
2582         ast_debug(1, "OSPLookup: OSPOUTCALLIDTYPES '%s'\n", buffer);
2583         pbx_builtin_setvar_helper(chan, "OSPLOOKUPSTATUS", status);
2584         ast_debug(1, "OSPLookup: %s\n", status);
2585
2586         if (!strcasecmp(results.outtech, OSP_TECH_SIP)) {
2587                 snprintf(buffer, sizeof(buffer), "%s/%s@%s", results.outtech, results.called, results.dest);
2588                 pbx_builtin_setvar_helper(chan, "OSPDIALSTR", buffer);
2589                 if (!ast_strlen_zero(results.token)) {
2590                         snprintf(buffer, sizeof(buffer), "%s: %s", OSP_SIP_HEADER, results.token);
2591                         pbx_builtin_setvar_helper(chan, "_SIPADDHEADER", buffer);
2592                         ast_debug(1, "OSPLookup: SIPADDHEADER size '%zd'\n", strlen(buffer));
2593                 }
2594         } else if (!strcasecmp(results.outtech, OSP_TECH_H323)) {
2595                 if ((callidtypes & OSP_CALLID_H323) && (results.outcallid.len != 0)) {
2596                         osp_uuid2str(results.outcallid.buf, buffer, sizeof(buffer));
2597                 } else {
2598                         buffer[0] = '\0';
2599                 }
2600                 pbx_builtin_setvar_helper(chan, "OSPOUTCALLID", buffer);
2601                 snprintf(buffer, sizeof(buffer), "%s/%s@%s", results.outtech, results.called, results.dest);
2602                 pbx_builtin_setvar_helper(chan, "OSPDIALSTR", buffer);
2603         } else if (!strcasecmp(results.outtech, OSP_TECH_IAX)) {
2604                 snprintf(buffer, sizeof(buffer), "%s/%s/%s", results.outtech, results.dest, results.called);
2605                 pbx_builtin_setvar_helper(chan, "OSPDIALSTR", buffer);
2606         } else if (!strcasecmp(results.outtech, OSP_TECH_SKYPE)) {
2607                 snprintf(buffer, sizeof(buffer), "%s/%s", results.outtech, results.called);
2608                 pbx_builtin_setvar_helper(chan, "OSPDIALSTR", buffer);
2609         }
2610
2611         if ((cres = ast_autoservice_stop(chan)) < 0) {
2612                 return OSP_AST_ERROR;
2613         }
2614
2615         if(res != OSP_OK) {
2616                 res = OSP_AST_ERROR;
2617         } else {
2618                 res = OSP_AST_OK;
2619         }
2620
2621         return res;
2622 }
2623
2624 /*!
2625  * \brief OSP Application OSPNext
2626  * \param chan Channel
2627  * \param data Parameter
2628  * \return OSP_AST_OK Success, OSP_AST_ERROR Error
2629  */
2630 static int ospnext_exec(
2631         struct ast_channel* chan,
2632         const char * data)
2633 {
2634         int res;
2635         const char* provider = OSP_DEF_PROVIDER;
2636         int cause = 0;
2637         struct varshead* headp;
2638         struct ast_var_t* current;
2639         struct osp_results results;
2640         OSPE_OPERATOR_NAME type;
2641         char buffer[OSP_SIZE_TOKSTR];
2642         unsigned int callidtypes = OSP_CALLID_UNDEF;
2643         const char* status;
2644         char* tmp;
2645
2646         AST_DECLARE_APP_ARGS(args,
2647                 AST_APP_ARG(cause);
2648                 AST_APP_ARG(provider);
2649                 AST_APP_ARG(options);
2650         );
2651
2652         if (ast_strlen_zero(data)) {
2653                 ast_log(LOG_WARNING, "OSPNext: Arg required, OSPNext(cause[,provider[,options]])\n");
2654                 return OSP_AST_ERROR;
2655         }
2656
2657         if (!(tmp = ast_strdupa(data))) {
2658                 ast_log(LOG_ERROR, "Out of memory\n");
2659                 return OSP_AST_ERROR;
2660         }
2661
2662         AST_STANDARD_APP_ARGS(args, tmp);
2663
2664         if (!ast_strlen_zero(args.cause) && sscanf(args.cause, "%30d", &cause) != 1) {
2665                 cause = 0;
2666         }
2667         ast_debug(1, "OSPNext: cause '%d'\n", cause);
2668
2669         if (!ast_strlen_zero(args.provider)) {
2670                 provider = args.provider;
2671         }
2672         ast_debug(1, "OSPlookup: provider '%s'\n", provider);
2673
2674         results.inhandle = OSP_INVALID_HANDLE;
2675         results.outhandle = OSP_INVALID_HANDLE;
2676         results.intimelimit = OSP_DEF_TIMELIMIT;
2677         results.numdests = 0;
2678
2679         headp = &chan->varshead;
2680         AST_LIST_TRAVERSE(headp, current, entries) {
2681                 if (!strcasecmp(ast_var_name(current), "OSPINHANDLE")) {
2682                         if (sscanf(ast_var_value(current), "%30d", &results.inhandle) != 1) {
2683                                 results.inhandle = OSP_INVALID_HANDLE;
2684                         }
2685                 } else if (!strcasecmp(ast_var_name(current), "OSPOUTHANDLE")) {
2686                         if (sscanf(ast_var_value(current), "%30d", &results.outhandle) != 1) {
2687                                 results.outhandle = OSP_INVALID_HANDLE;
2688                         }
2689                 } else if (!strcasecmp(ast_var_name(current), "OSPINTIMELIMIT")) {
2690                         if (sscanf(ast_var_value(current), "%30d", &results.intimelimit) != 1) {
2691                                 results.intimelimit = OSP_DEF_TIMELIMIT;
2692                         }
2693                 } else if (!strcasecmp(ast_var_name(current), "OSPOUTCALLIDTYPES")) {
2694                         if (sscanf(ast_var_value(current), "%30d", &callidtypes) != 1) {
2695                                 callidtypes = OSP_CALLID_UNDEF;
2696                         }
2697                 } else if (!strcasecmp(ast_var_name(current), "OSPDESTREMAILS")) {
2698                         if (sscanf(ast_var_value(current), "%30d", &results.numdests) != 1) {
2699                                 results.numdests = 0;
2700                         }
2701                 }
2702         }
2703         ast_debug(1, "OSPNext: OSPINHANDLE '%d'\n", results.inhandle);
2704         ast_debug(1, "OSPNext: OSPOUTHANDLE '%d'\n", results.outhandle);
2705         ast_debug(1, "OSPNext: OSPINTIMELIMIT '%d'\n", results.intimelimit);
2706         ast_debug(1, "OSPNext: OSPOUTCALLIDTYPES '%d'\n", callidtypes);
2707         ast_debug(1, "OSPNext: OSPDESTREMAILS '%d'\n", results.numdests);
2708
2709         if ((res = osp_next(provider, cause, &results)) > 0) {
2710                 status = AST_OSP_SUCCESS;
2711         } else {
2712                 results.outtech[0] = '\0';
2713                 results.dest[0] = '\0';
2714                 results.calling[0] = '\0';
2715                 results.called[0] = '\0';
2716                 results.token[0] = '\0';
2717                 results.networkid[0] = '\0';
2718                 results.nprn[0] = '\0';
2719                 results.npcic[0] = '\0';
2720                 results.npdi = 0;
2721                 for (type = OSPC_OPNAME_START; type < OSPC_OPNAME_NUMBER; type++) {
2722                         results.opname[type][0] = '\0';
2723                 }
2724                 results.numdests = 0;
2725                 results.outtimelimit = OSP_DEF_TIMELIMIT;
2726                 results.outcallid.buf[0] = '\0';
2727                 results.outcallid.len = 0;
2728                 if (!res) {
2729                         status = AST_OSP_FAILED;
2730                 } else {
2731                         status = AST_OSP_ERROR;
2732                 }
2733         }
2734
2735         pbx_builtin_setvar_helper(chan, "OSPOUTTECH", results.outtech);
2736         ast_debug(1, "OSPNext: OSPOUTTECH '%s'\n", results.outtech);
2737         pbx_builtin_setvar_helper(chan, "OSPDESTINATION", results.dest);
2738         ast_debug(1, "OSPNext: OSPDESTINATION '%s'\n", results.dest);
2739         pbx_builtin_setvar_helper(chan, "OSPOUTCALLING", results.calling);
2740         ast_debug(1, "OSPNext: OSPOUTCALLING '%s'\n", results.calling);
2741         pbx_builtin_setvar_helper(chan, "OSPOUTCALLED", results.called);
2742         ast_debug(1, "OSPNext: OSPOUTCALLED'%s'\n", results.called);
2743         pbx_builtin_setvar_helper(chan, "OSPOUTNETWORKID", results.networkid);
2744         ast_debug(1, "OSPLookup: OSPOUTNETWORKID '%s'\n", results.networkid);
2745         pbx_builtin_setvar_helper(chan, "OSPOUTNPRN", results.nprn);
2746         ast_debug(1, "OSPLookup: OSPOUTNPRN '%s'\n", results.nprn);
2747         pbx_builtin_setvar_helper(chan, "OSPOUTNPCIC", results.npcic);
2748         ast_debug(1, "OSPLookup: OSPOUTNPCIC '%s'\n", results.npcic);
2749         snprintf(buffer, sizeof(buffer), "%d", results.npdi);
2750         pbx_builtin_setvar_helper(chan, "OSPOUTNPDI", buffer);
2751         ast_debug(1, "OSPLookup: OSPOUTNPDI'%s'\n", buffer);
2752         pbx_builtin_setvar_helper(chan, "OSPOUTSPID", results.opname[OSPC_OPNAME_SPID]);
2753         ast_debug(1, "OSPLookup: OSPOUTSPID '%s'\n", results.opname[OSPC_OPNAME_SPID]);
2754         pbx_builtin_setvar_helper(chan, "OSPOUTOCN", results.opname[OSPC_OPNAME_OCN]);
2755         ast_debug(1, "OSPLookup: OSPOUTOCN '%s'\n", results.opname[OSPC_OPNAME_OCN]);
2756         pbx_builtin_setvar_helper(chan, "OSPOUTSPN", results.opname[OSPC_OPNAME_SPN]);
2757         ast_debug(1, "OSPLookup: OSPOUTSPN '%s'\n", results.opname[OSPC_OPNAME_SPN]);
2758         pbx_builtin_setvar_helper(chan, "OSPOUTALTSPN", results.opname[OSPC_OPNAME_ALTSPN]);
2759         ast_debug(1, "OSPLookup: OSPOUTALTSPN '%s'\n", results.opname[OSPC_OPNAME_ALTSPN]);
2760         pbx_builtin_setvar_helper(chan, "OSPOUTMCC", results.opname[OSPC_OPNAME_MCC]);
2761         ast_debug(1, "OSPLookup: OSPOUTMCC '%s'\n", results.opname[OSPC_OPNAME_MCC]);
2762         pbx_builtin_setvar_helper(chan, "OSPOUTMNC", results.opname[OSPC_OPNAME_MNC]);
2763         ast_debug(1, "OSPLookup: OSPOUTMNC '%s'\n", results.opname[OSPC_OPNAME_MNC]);
2764         pbx_builtin_setvar_helper(chan, "OSPOUTTOKEN", results.token);
2765         ast_debug(1, "OSPNext: OSPOUTTOKEN size '%zd'\n", strlen(results.token));
2766         snprintf(buffer, sizeof(buffer), "%d", results.numdests);
2767         pbx_builtin_setvar_helper(chan, "OSPDESTREMAILS", buffer);
2768         ast_debug(1, "OSPNext: OSPDESTREMAILS '%s'\n", buffer);
2769         snprintf(buffer, sizeof(buffer), "%d", results.outtimelimit);
2770         pbx_builtin_setvar_helper(chan, "OSPOUTTIMELIMIT", buffer);
2771         ast_debug(1, "OSPNext: OSPOUTTIMELIMIT '%s'\n", buffer);
2772         pbx_builtin_setvar_helper(chan, "OSPNEXTSTATUS", status);
2773         ast_debug(1, "OSPNext: %s\n", status);
2774
2775         if (!strcasecmp(results.outtech, OSP_TECH_SIP)) {
2776                 snprintf(buffer, sizeof(buffer), "%s/%s@%s", results.outtech, results.called, results.dest);
2777                 pbx_builtin_setvar_helper(chan, "OSPDIALSTR", buffer);
2778                 if (!ast_strlen_zero(results.token)) {
2779                         snprintf(buffer, sizeof(buffer), "%s: %s", OSP_SIP_HEADER, results.token);
2780                         pbx_builtin_setvar_helper(chan, "_SIPADDHEADER", buffer);
2781                         ast_debug(1, "OSPLookup: SIPADDHEADER size '%zd'\n", strlen(buffer));
2782                 }
2783         } else if (!strcasecmp(results.outtech, OSP_TECH_H323)) {
2784                 if ((callidtypes & OSP_CALLID_H323) && (results.outcallid.len != 0)) {
2785                         osp_uuid2str(results.outcallid.buf, buffer, sizeof(buffer));
2786                 } else {
2787                         buffer[0] = '\0';
2788                 }
2789                 pbx_builtin_setvar_helper(chan, "OSPOUTCALLID", buffer);
2790                 snprintf(buffer, sizeof(buffer), "%s/%s@%s", results.outtech, results.called, results.dest);
2791                 pbx_builtin_setvar_helper(chan, "OSPDIALSTR", buffer);
2792         } else if (!strcasecmp(results.outtech, OSP_TECH_IAX)) {
2793                 snprintf(buffer, sizeof(buffer), "%s/%s/%s", results.outtech, results.dest, results.called);
2794                 pbx_builtin_setvar_helper(chan, "OSPDIALSTR", buffer);
2795         } else if (!strcasecmp(results.outtech, OSP_TECH_SKYPE)) {
2796                 snprintf(buffer, sizeof(buffer), "%s/%s", results.outtech, results.called);
2797                 pbx_builtin_setvar_helper(chan, "OSPDIALSTR", buffer);
2798         }
2799
2800         if(res != OSP_OK) {
2801                 res = OSP_AST_ERROR;
2802         } else {
2803                 res = OSP_AST_OK;
2804         }
2805
2806         return res;
2807 }
2808
2809 /*!
2810  * \brief OSP Application OSPFinish
2811  * \param chan Channel
2812  * \param data Parameter
2813  * \return OSP_AST_OK Success, OSP_AST_ERROR Error
2814  */
2815 static int ospfinished_exec(
2816         struct ast_channel* chan,
2817         const char * data)
2818 {
2819         int res = OSP_OK;
2820         int cause = 0;
2821         struct varshead* headp;
2822         struct ast_var_t* current;
2823         int inhandle = OSP_INVALID_HANDLE;
2824         int outhandle = OSP_INVALID_HANDLE;
2825         int recorded = 0;
2826         time_t start, connect, end;
2827         unsigned int release;