Updates from transnexus to osplookup, removes res_osp
authorMatt O'Gorman <mogorman@digium.com>
Fri, 30 Jun 2006 15:12:35 +0000 (15:12 +0000)
committerMatt O'Gorman <mogorman@digium.com>
Fri, 30 Jun 2006 15:12:35 +0000 (15:12 +0000)
and puts all logic into the app, documentation provided now
in osp.txt.

git-svn-id: https://origsvn.digium.com/svn/asterisk/trunk@36406 65c4cc65-6c06-0410-ace0-fbb531ad65f3

apps/app_osplookup.c
doc/osp.txt [new file with mode: 0644]
include/asterisk/astosp.h
res/res_osp.c [deleted file]

index f857164..c2f6424 100644 (file)
@@ -18,7 +18,7 @@
 
 /*!
  * \file
- * \brief Open Settlement Protocol Applications
+ * \brief Open Settlement Protocol (OSP) Applications
  *
  * \author Mark Spencer <markster@digium.com>
  * 
 
 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 
+#include <sys/types.h>
 #include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
 #include <string.h>
-#include <ctype.h>
+#include <unistd.h>
+#include <errno.h>
+#include <osp/osp.h>
+#include <osp/osputils.h>
 
 #include "asterisk/lock.h"
-#include "asterisk/file.h"
-#include "asterisk/logger.h"
-#include "asterisk/channel.h"
-#include "asterisk/pbx.h"
-#include "asterisk/options.h"
 #include "asterisk/config.h"
-#include "asterisk/module.h"
 #include "asterisk/utils.h"
 #include "asterisk/causes.h"
-#include "asterisk/astosp.h"
+#include "asterisk/channel.h"
 #include "asterisk/app.h"
+#include "asterisk/module.h"
+#include "asterisk/pbx.h"
 #include "asterisk/options.h"
+#include "asterisk/cli.h"
+#include "asterisk/logger.h"
+#include "asterisk/astosp.h"
 
-static char *app1= "OSPAuth";
-static char *synopsis1 = "OSP authentication";
-static char *descrip1 = 
-"  OSPAuth([provider[|options]]):  Authenticate a SIP INVITE by OSP and sets\n"
-"the variables:\n"
-" ${OSPINHANDLE}:  The in_bound call transaction handle\n"
-" ${OSPINTIMELIMIT}:  The in_bound call duration limit in seconds\n"
-"\n"
-"The option string may contain the following character:\n"
-"      'j' -- jump to n+101 priority if the authentication was NOT successful\n"
-"This application sets the following channel variable upon completion:\n"
-"      OSPAUTHSTATUS   The status of the OSP Auth attempt as a text string, one of\n"
-"              SUCCESS | FAILED | ERROR\n";
+/* OSP Buffer Sizes */
+#define OSP_INTSTR_SIZE                        ((unsigned int)16)                      /* OSP signed/unsigned int string buffer size */
+#define OSP_NORSTR_SIZE                        ((unsigned int)256)                     /* OSP normal string buffer size */
+#define OSP_TOKSTR_SIZE                        ((unsigned int)4096)            /* OSP token string buffer size */
+
+/* OSP Constants */
+#define OSP_INVALID_HANDLE             ((int)-1)                                       /* Invalid OSP handle, provider, transaction etc. */
+#define OSP_CONFIG_FILE                        ((const char*)"osp.conf")       /* OSP configuration file name */
+#define OSP_GENERAL_CAT                        ((const char*)"general")        /* OSP global configuration context name */
+#define OSP_DEF_PROVIDER               ((const char*)"default")        /* OSP default provider context name */
+#define OSP_MAX_CERTS                  ((unsigned int)10)                      /* OSP max number of cacerts */
+#define OSP_MAX_SRVS                   ((unsigned int)10)                      /* OSP max number of service points */
+#define OSP_DEF_MAXCONNECTIONS ((unsigned int)20)                      /* OSP default max_connections */
+#define OSP_MIN_MAXCONNECTIONS ((unsigned int)1)                       /* OSP min max_connections */
+#define OSP_MAX_MAXCONNECTIONS ((unsigned int)1000)            /* OSP max max_connections */
+#define OSP_DEF_RETRYDELAY             ((unsigned int)0)                       /* OSP default retry delay */
+#define OSP_MIN_RETRYDELAY             ((unsigned int)0)                       /* OSP min retry delay */
+#define OSP_MAX_RETRYDELAY             ((unsigned int)10)                      /* OSP max retry delay */
+#define OSP_DEF_RETRYLIMIT             ((unsigned int)2)                       /* OSP default retry times */
+#define OSP_MIN_RETRYLIMIT             ((unsigned int)0)                       /* OSP min retry times */
+#define OSP_MAX_RETRYLIMIT             ((unsigned int)100)                     /* OSP max retry times */
+#define OSP_DEF_TIMEOUT                        ((unsigned int)500)                     /* OSP default timeout in ms */
+#define OSP_MIN_TIMEOUT                        ((unsigned int)200)                     /* OSP min timeout in ms */
+#define OSP_MAX_TIMEOUT                        ((unsigned int)10000)           /* OSP max timeout in ms */
+#define OSP_DEF_AUTHPOLICY             ((enum osp_authpolicy)OSP_AUTH_YES)
+#define OSP_AUDIT_URL                  ((const char*)"localhost")      /* OSP default Audit URL */
+#define OSP_LOCAL_VALIDATION   ((int)1)                                        /* Validate OSP token locally */
+#define OSP_SSL_LIFETIME               ((unsigned int)300)                     /* SSL life time, in seconds */
+#define OSP_HTTP_PERSISTENCE   ((int)1)                                        /* In seconds */
+#define OSP_CUSTOMER_ID                        ((const char*)"")                       /* OSP customer ID */
+#define OSP_DEVICE_ID                  ((const char*)"")                       /* OSP device ID */
+#define OSP_DEF_DESTINATIONS   ((unsigned int)5)                       /* OSP default max number of destinations */
+#define OSP_DEF_TIMELIMIT              ((unsigned int)0)                       /* OSP default duration limit, no limit */
+
+/* OSP Authentication Policy */
+enum osp_authpolicy {
+       OSP_AUTH_NO,            /* Accept any call */
+       OSP_AUTH_YES,           /* Accept call with valid OSP token or without OSP token */
+       OSP_AUTH_EXCLUSIVE      /* Only accept call with valid OSP token */
+};
+
+/* OSP Provider */
+struct osp_provider {
+       char name[OSP_NORSTR_SIZE];                                             /* OSP provider context name */
+       char privatekey[OSP_NORSTR_SIZE];                               /* OSP private key file name */
+       char localcert[OSP_NORSTR_SIZE];                                /* OSP local cert file name */
+       unsigned int cacount;                                                   /* Number of cacerts */
+       char cacerts[OSP_MAX_CERTS][OSP_NORSTR_SIZE];   /* Cacert file names */
+       unsigned int spcount;                                                   /* Number of service points */
+       char srvpoints[OSP_MAX_SRVS][OSP_NORSTR_SIZE];  /* Service point URLs */
+       int maxconnections;                                                             /* Max number of connections */
+       int retrydelay;                                                                 /* Retry delay */
+       int retrylimit;                                                                 /* Retry limit */
+       int timeout;                                                                    /* Timeout in ms */
+       char source[OSP_NORSTR_SIZE];                                   /* IP of self */
+       enum osp_authpolicy authpolicy;                                 /* OSP authentication policy */
+       OSPTPROVHANDLE handle;                                                  /* OSP provider handle */
+       struct osp_provider* next;                                              /* Pointer to next OSP provider */
+};
+
+/* OSP Application In/Output Results */
+struct osp_result {
+       int inhandle;                                   /* Inbound transaction handle */
+       int outhandle;                                  /* Outbound transaction handle */
+       unsigned int intimelimit;               /* Inbound duration limit */
+       unsigned int outtimelimit;              /* Outbound duration limit */
+       char tech[20];                                  /* Asterisk TECH string */
+       char dest[OSP_NORSTR_SIZE];             /* Destination in called@IP format */
+       char calling[OSP_NORSTR_SIZE];  /* Calling number, may be translated */
+       char token[OSP_TOKSTR_SIZE];    /* Outbound OSP token */
+       int numresults;                                 /* Number of remain destinations */
+};
+
+/* OSP Module Global Variables */
+AST_MUTEX_DEFINE_STATIC(osplock);                                                      /* Lock of OSP provider list */
+static int osp_initialized = 0;                                                                /* Init flag */
+static int osp_hardware = 0;                                                           /* Hardware accelleration flag */
+static struct osp_provider* ospproviders = NULL;                       /* OSP provider list */
+static unsigned int osp_tokenformat = TOKEN_ALGO_SIGNED;       /* Token format supported */
+
+/* OSP Client Wrapper APIs */
 
-static char *app2= "OSPLookup";
-static char *synopsis2 = "Lookup destination by OSP";
-static char *descrip2 = 
-"  OSPLookup(exten[|provider[|options]]):  Looks up an extension via OSP and sets\n"
-"the variables, where 'n' is the number of the result beginning with 1:\n"
-" ${OSPOUTHANDLE}:  The OSP Handle for anything remaining\n"
-" ${OSPTECH}:  The technology to use for the call\n"
-" ${OSPDEST}:  The destination to use for the call\n"
-" ${OSPCALLING}:  The calling number to use for the call\n"
-" ${OSPOUTTOKEN}:  The actual OSP token as a string\n"
-" ${OSPOUTTIMELIMIT}:  The out_bound call duration limit in seconds\n"
-" ${OSPRESULTS}:  The number of OSP results total remaining\n"
-"\n"
-"The option string may contain the following character:\n"
-"      'j' -- jump to n+101 priority if the lookup was NOT successful\n"
-"This application sets the following channel variable upon completion:\n"
-"      OSPLOOKUPSTATUS The status of the OSP Lookup attempt as a text string, one of\n"
-"              SUCCESS | FAILED | ERROR\n";
+/*!
+ * \brief Create OSP provider handle according to configuration
+ * \param cfg OSP configuration
+ * \param provider OSP provider context name
+ * \return 1 Success, 0 Failed, -1 Error
+ */
+static int osp_create_provider(
+       struct ast_config* cfg,         /* OSP configuration */
+       const char* provider)           /* OSP provider context name */
+{
+       int res;
+       unsigned int t, i, j;
+       struct osp_provider* p;
+       struct ast_variable* v;
+       OSPTPRIVATEKEY privatekey;
+       OSPTCERT localcert;
+       const char* psrvpoints[OSP_MAX_SRVS];
+       OSPTCERT cacerts[OSP_MAX_CERTS];
+       const OSPTCERT* pcacerts[OSP_MAX_CERTS];
+       int error = OSPC_ERR_NO_ERROR;
+
+       if (!(p = ast_calloc(1, sizeof(*p)))) {
+               ast_log(LOG_ERROR, "Out of memory\n");
+               return -1;
+       }
 
-static char *app3 = "OSPNext";
-static char *synopsis3 = "Lookup next destination by OSP";
-static char *descrip3 = 
-"  OSPNext(cause[|options]):  Looks up the next OSP Destination for ${OSPOUTHANDLE}\n"
-"See OSPLookup for more information\n"
-"\n"
-"The option string may contain the following character:\n"
-"      'j' -- jump to n+101 priority if the lookup was NOT successful\n"
-"This application sets the following channel variable upon completion:\n"
-"      OSPNEXTSTATUS   The status of the OSP Next attempt as a text string, one of\n"
-"              SUCCESS | FAILED |ERROR\n";
+       ast_copy_string(p->name, provider, sizeof(p->name));
+       snprintf(p->privatekey, sizeof(p->privatekey), "%s/%s-privatekey.pem", ast_config_AST_KEY_DIR, provider);
+       snprintf(p->localcert, sizeof(p->localcert), "%s/%s-localcert.pem", ast_config_AST_KEY_DIR, provider);
+       p->maxconnections = OSP_DEF_MAXCONNECTIONS;
+       p->retrydelay = OSP_DEF_RETRYDELAY;
+       p->retrylimit = OSP_DEF_RETRYLIMIT;
+       p->timeout = OSP_DEF_TIMEOUT;
+       p->authpolicy = OSP_DEF_AUTHPOLICY;
+       p->handle = OSP_INVALID_HANDLE;
+
+       v = ast_variable_browse(cfg, provider);
+       while(v) {
+               if (!strcasecmp(v->name, "privatekey")) {
+                       if (v->value[0] == '/') {
+                               ast_copy_string(p->privatekey, v->value, sizeof(p->privatekey));
+                       } else {
+                               snprintf(p->privatekey, sizeof(p->privatekey), "%s/%s", ast_config_AST_KEY_DIR, v->value);
+                       }
+                       ast_log(LOG_DEBUG, "OSP: privatekey '%s'\n", p->privatekey);
+               } else if (!strcasecmp(v->name, "localcert")) {
+                       if (v->value[0] == '/') {
+                               ast_copy_string(p->localcert, v->value, sizeof(p->localcert));
+                       } else {
+                               snprintf(p->localcert, sizeof(p->localcert), "%s/%s", ast_config_AST_KEY_DIR, v->value);
+                       }
+                       ast_log(LOG_DEBUG, "OSP: localcert '%s'\n", p->localcert);
+               } else if (!strcasecmp(v->name, "cacert")) {
+                       if (p->cacount < OSP_MAX_CERTS) {
+                               if (v->value[0] == '/') {
+                                       ast_copy_string(p->cacerts[p->cacount], v->value, sizeof(p->cacerts[0]));
+                               } else {
+                                       snprintf(p->cacerts[p->cacount], sizeof(p->cacerts[0]), "%s/%s", ast_config_AST_KEY_DIR, v->value);
+                               }
+                               ast_log(LOG_DEBUG, "OSP: cacert[%d]: '%s'\n", p->cacount, p->cacerts[p->cacount]);
+                               p->cacount++;
+                       } else {
+                               ast_log(LOG_WARNING, "OSP: Too many CA Certificates at line %d\n", v->lineno);
+                       }
+               } else if (!strcasecmp(v->name, "servicepoint")) {
+                       if (p->spcount < OSP_MAX_SRVS) {
+                               ast_copy_string(p->srvpoints[p->spcount], v->value, sizeof(p->srvpoints[0]));
+                               ast_log(LOG_DEBUG, "OSP: servicepoint[%d]: '%s'\n", p->spcount, p->srvpoints[p->spcount]);
+                               p->spcount++;
+                       } else {
+                               ast_log(LOG_WARNING, "OSP: Too many Service Points at line %d\n", v->lineno);
+                       }
+               } else if (!strcasecmp(v->name, "maxconnections")) {
+                       if ((sscanf(v->value, "%d", &t) == 1) && (t >= OSP_MIN_MAXCONNECTIONS) && (t <= OSP_MAX_MAXCONNECTIONS)) {
+                               p->maxconnections = t;
+                               ast_log(LOG_DEBUG, "OSP: maxconnections '%d'\n", t);
+                       } else {
+                               ast_log(LOG_WARNING, "OSP: maxconnections should be an integer from %d to %d, not '%s' at line %d\n", 
+                                       OSP_MIN_MAXCONNECTIONS, OSP_MAX_MAXCONNECTIONS, v->value, v->lineno);
+                       }
+               } else if (!strcasecmp(v->name, "retrydelay")) {
+                       if ((sscanf(v->value, "%d", &t) == 1) && (t >= OSP_MIN_RETRYDELAY) && (t <= OSP_MAX_RETRYDELAY)) {
+                               p->retrydelay = t;
+                               ast_log(LOG_DEBUG, "OSP: retrydelay '%d'\n", t);
+                       } else {
+                               ast_log(LOG_WARNING, "OSP: retrydelay should be an integer from %d to %d, not '%s' at line %d\n", 
+                                       OSP_MIN_RETRYDELAY, OSP_MAX_RETRYDELAY, v->value, v->lineno);
+                       }
+               } else if (!strcasecmp(v->name, "retrylimit")) {
+                       if ((sscanf(v->value, "%d", &t) == 1) && (t >= OSP_MIN_RETRYLIMIT) && (t <= OSP_MAX_RETRYLIMIT)) {
+                               p->retrylimit = t;
+                               ast_log(LOG_DEBUG, "OSP: retrylimit '%d'\n", t);
+                       } else {
+                               ast_log(LOG_WARNING, "OSP: retrylimit should be an integer from %d to %d, not '%s' at line %d\n", 
+                                       OSP_MIN_RETRYLIMIT, OSP_MAX_RETRYLIMIT, v->value, v->lineno);
+                       }
+               } else if (!strcasecmp(v->name, "timeout")) {
+                       if ((sscanf(v->value, "%d", &t) == 1) && (t >= OSP_MIN_TIMEOUT) && (t <= OSP_MAX_TIMEOUT)) {
+                               p->timeout = t;
+                               ast_log(LOG_DEBUG, "OSP: timeout '%d'\n", t);
+                       } else {
+                               ast_log(LOG_WARNING, "OSP: timeout should be an integer from %d to %d, not '%s' at line %d\n", 
+                                       OSP_MIN_TIMEOUT, OSP_MAX_TIMEOUT, v->value, v->lineno);
+                       }
+               } else if (!strcasecmp(v->name, "source")) {
+                       ast_copy_string(p->source, v->value, sizeof(p->source));
+                       ast_log(LOG_DEBUG, "OSP: source '%s'\n", p->source);
+               } else if (!strcasecmp(v->name, "authpolicy")) {
+                       if ((sscanf(v->value, "%d", &t) == 1) && ((t == OSP_AUTH_NO) || (t == OSP_AUTH_YES) || (t == OSP_AUTH_EXCLUSIVE))) {
+                               p->authpolicy = t;
+                               ast_log(LOG_DEBUG, "OSP: authpolicy '%d'\n", t);
+                       } else {
+                               ast_log(LOG_WARNING, "OSP: authpolicy should be %d, %d or %d, not '%s' at line %d\n", 
+                                       OSP_AUTH_NO, OSP_AUTH_YES, OSP_AUTH_EXCLUSIVE, v->value, v->lineno);
+                       }
+               }
+               v = v->next;
+       }
 
-static char *app4 = "OSPFinish";
-static char *synopsis4 = "Record OSP entry";
-static char *descrip4 = 
-"  OSPFinish([status[|options]]):  Records call state for ${OSPINHANDLE}, according to\n"
-"status, which should be one of BUSY, CONGESTION, ANSWER, NOANSWER, or CHANUNAVAIL\n"
-"or coincidentally, just what the Dial application stores in its ${DIALSTATUS}.\n"
-"\n"
-"The option string may contain the following character:\n"
-"      'j' -- jump to n+101 priority if the finish attempt was NOT successful\n"
-"This application sets the following channel variable upon completion:\n"
-"      OSPFINISHSTATUS The status of the OSP Finish attempt as a text string, one of\n"
-"              SUCCESS | FAILED |ERROR \n";
+       error = OSPPUtilLoadPEMPrivateKey(p->privatekey, &privatekey);
+       if (error != OSPC_ERR_NO_ERROR) {
+               ast_log(LOG_WARNING, "OSP: Unable to load privatekey '%s', error '%d'\n", p->privatekey, error);
+               free(p);
+               return 0;
+       }
 
-LOCAL_USER_DECL;
+       error = OSPPUtilLoadPEMCert(p->localcert, &localcert);
+       if (error != OSPC_ERR_NO_ERROR) {
+               ast_log(LOG_WARNING, "OSP: Unable to load localcert '%s', error '%d'\n", p->localcert, error);
+               if (privatekey.PrivateKeyData) {
+                       free(privatekey.PrivateKeyData);
+               }
+               free(p);
+               return 0;
+       }
+
+       if (p->cacount < 1) {
+               snprintf(p->cacerts[p->cacount], sizeof(p->cacerts[0]), "%s/%s-cacert.pem", ast_config_AST_KEY_DIR, provider);
+               ast_log(LOG_DEBUG, "OSP: cacert[%d]: '%s'\n", p->cacount, p->cacerts[p->cacount]);
+               p->cacount++;
+       }
+       for (i = 0; i < p->cacount; i++) {
+               error = OSPPUtilLoadPEMCert(p->cacerts[i], &cacerts[i]);
+               if (error != OSPC_ERR_NO_ERROR) {
+                       ast_log(LOG_WARNING, "OSP: Unable to load cacert '%s', error '%d'\n", p->cacerts[i], error);
+                       for (j = 0; j < i; j++) {
+                               if (cacerts[j].CertData) {
+                                       free(cacerts[j].CertData);
+                               }
+                       }
+                       if (localcert.CertData) {
+                               free(localcert.CertData);
+                       }
+                       if (privatekey.PrivateKeyData) {
+                               free(privatekey.PrivateKeyData);
+                       }
+                       free(p);
+                       return 0;
+               }
+               pcacerts[i] = &cacerts[i];
+       }
+       
+       for (i = 0; i < p->spcount; i++) {
+               psrvpoints[i] = p->srvpoints[i];
+       }
+
+       error = OSPPProviderNew(
+               p->spcount, psrvpoints,
+               NULL,
+               OSP_AUDIT_URL,
+               &privatekey,
+               &localcert,
+               p->cacount, pcacerts,
+               OSP_LOCAL_VALIDATION,
+               OSP_SSL_LIFETIME,
+               p->maxconnections,
+               OSP_HTTP_PERSISTENCE,
+               p->retrydelay,
+               p->retrylimit,
+               p->timeout,
+               OSP_CUSTOMER_ID,
+               OSP_DEVICE_ID,
+               &p->handle);
+       if (error != OSPC_ERR_NO_ERROR) {
+               ast_log(LOG_WARNING, "OSP: Unable to create provider '%s', error '%d'\n", provider, error);
+               free(p);
+               res = -1;
+       } else {
+               ast_log(LOG_DEBUG, "OSP: provider '%s'\n", provider);
+               ast_mutex_lock(&osplock);
+               p->next = ospproviders;
+               ospproviders = p;
+               ast_mutex_unlock(&osplock);     
+               res = 1;
+       }
+
+       for (i = 0; i < p->cacount; i++) {
+               if (cacerts[i].CertData) {
+                       free(cacerts[i].CertData);
+               }
+       }
+       if (localcert.CertData) {
+               free(localcert.CertData);
+       }
+       if (privatekey.PrivateKeyData) {
+               free(privatekey.PrivateKeyData);
+       }
+
+       return res;
+}
+
+/*!
+ * \brief Get OSP authenticiation policy of provider
+ * \param provider OSP provider context name
+ * \param policy OSP authentication policy, output
+ * \return 1 Success, 0 Failed, -1 Error
+ */
+static int osp_get_policy(
+       const char* provider,           /* OSP provider context name */
+       int* policy)                            /* OSP authentication policy, output */
+{
+       int res = 0;
+       struct osp_provider* p;
+
+       ast_mutex_lock(&osplock);
+       p = ospproviders;
+       while(p) {
+               if (!strcasecmp(p->name, provider)) {
+                       *policy = p->authpolicy;
+                       ast_log(LOG_DEBUG, "OSP: authpolicy '%d'\n", *policy);
+                       res = 1;
+                       break;
+               }
+               p = p->next;
+       }
+       ast_mutex_unlock(&osplock);
+
+       return res;
+}
 
-static int ospauth_exec(struct ast_channel *chan, void *data)
+/*!
+ * \brief Create OSP transaction handle
+ * \param provider OSP provider context name
+ * \param transaction OSP transaction handle, output
+ * \param sourcesize Size of source buffer, in/output
+ * \param source Source of provider, output
+ * \return 1 Success, 0 Failed, -1 Error
+ */
+static int osp_create_transaction(
+       const char* provider,           /* OSP provider context name */
+       int* transaction,                       /* OSP transaction handle, output */
+       unsigned int sourcesize,        /* Size of source buffer, in/output */
+       char* source)                           /* Source of provider context, output */
 {
        int res = 0;
+       struct osp_provider* p;
+       int error;
+
+       ast_mutex_lock(&osplock);
+       p = ospproviders;
+       while(p) {
+               if (!strcasecmp(p->name, provider)) {
+                       error = OSPPTransactionNew(p->handle, transaction);
+                       if (error == OSPC_ERR_NO_ERROR) {
+                               ast_log(LOG_DEBUG, "OSP: transaction '%d'\n", *transaction);
+                               ast_copy_string(source, p->source, sourcesize);
+                               ast_log(LOG_DEBUG, "OSP: source '%s'\n", source);
+                               res = 1;
+                       } else {
+                               *transaction = OSP_INVALID_HANDLE;
+                               ast_log(LOG_DEBUG, "OSP: Unable to create transaction handle, error '%d'\n", error);
+                               res = -1;
+                       }
+                       break;
+               }
+               p = p->next;
+       }
+       ast_mutex_unlock(&osplock);
+
+       return res;
+}
+
+/*!
+ * \brief Validate OSP token of inbound call
+ * \param transaction OSP transaction handle
+ * \param source Source of inbound call
+ * \param dest Destination of inbound call
+ * \param calling Calling number
+ * \param called Called number
+ * \param token OSP token, may be empty
+ * \param timelimit Call duration limit, output
+ * \return 1 Success, 0 Failed, -1 Error
+ */
+static int osp_validate_token(
+       int transaction,                        /* OSP transaction handle */
+       const char* source,                     /* Source of inbound call */
+       const char* dest,                       /* Destination of inbound call */
+       const char* calling,            /* Calling number */
+       const char* called,                     /* Called number */
+       const char* token,                      /* OSP token, may be empty */
+       unsigned int* timelimit)        /* Call duration limit, output */
+{
+       int res;
+       int tokenlen;
+       char tokenstr[OSP_TOKSTR_SIZE];
+       unsigned int authorised;
+       unsigned int dummy = 0;
+       int error;
+
+       tokenlen = ast_base64decode(tokenstr, token, strlen(token));
+       error = OSPPTransactionValidateAuthorisation(
+               transaction, 
+               source, dest, NULL, NULL,
+               calling ? calling : "", OSPC_E164, 
+               called, OSPC_E164, 
+               0, NULL,
+               tokenlen, tokenstr, 
+               &authorised, 
+               timelimit, 
+               &dummy, NULL, 
+               osp_tokenformat); 
+       if (error != OSPC_ERR_NO_ERROR) {
+               ast_log(LOG_DEBUG, "OSP: Unable to validate inbound token\n");
+               res = -1;
+       } else if (authorised) {
+               ast_log(LOG_DEBUG, "OSP: Authorised\n");
+               res = 1;
+       } else {
+               ast_log(LOG_DEBUG, "OSP: Unauthorised\n");
+               res = 0;
+       }
+       
+       return res;
+}
+
+/*!
+ * \brief Choose min duration limit
+ * \param in Inbound duration limit
+ * \param out Outbound duration limit
+ * \return min duration limit
+ */
+static unsigned int osp_choose_timelimit(
+       unsigned int in,                        /* Inbound duration timelimit */
+       unsigned int out)                       /* Outbound duration timelimit */
+{
+       if (in == OSP_DEF_TIMELIMIT) {
+               return out;
+       } else if (out == OSP_DEF_TIMELIMIT) {
+               return in;
+       } else {
+               return in < out ? in : out;
+       }
+}
+
+/*!
+ * \brief Choose min duration limit
+ * \param called Called number
+ * \param calling Calling number
+ * \param destination Destination IP in '[x.x.x.x]' format
+ * \param tokenlen OSP token length
+ * \param token OSP token
+ * \param reason Failure reason, output
+ * \param result OSP lookup results, in/output
+ * \return 1 Success, 0 Failed, -1 Error
+ */
+static int osp_check_destination(
+       const char* called,                             /* Called number */
+       const char* calling,                    /* Calling number */
+       char* destination,                              /* Destination IP in '[x.x.x.x]' format */
+       unsigned int tokenlen,                  /* OSP token length */
+       const char* token,                              /* OSP token */
+       enum OSPEFAILREASON* reason,    /* Failure reason, output */
+       struct osp_result* result)              /* OSP lookup results, in/output */
+{
+       int res;
+       OSPE_DEST_OSP_ENABLED enabled;
+       OSPE_DEST_PROT protocol;
+       int error;
+
+       if (strlen(destination) <= 2) {
+               ast_log(LOG_DEBUG, "OSP: Wrong destination format '%s'\n", destination);
+               *reason = OSPC_FAIL_NORMAL_UNSPECIFIED;
+               return -1;
+       } 
+
+       if ((error = OSPPTransactionIsDestOSPEnabled(result->outhandle, &enabled)) != OSPC_ERR_NO_ERROR) {
+               ast_log(LOG_DEBUG, "OSP: Unable to get destination OSP version, error '%d'\n", error);
+               *reason = OSPC_FAIL_NORMAL_UNSPECIFIED;
+               return -1;
+       }
+
+       if (enabled == OSPE_OSP_FALSE) {
+               result->token[0] = '\0';
+       } else {
+               ast_base64encode(result->token, token, tokenlen, sizeof(result->token) - 1);
+       }
+
+       if ((error = OSPPTransactionGetDestProtocol(result->outhandle, &protocol)) != OSPC_ERR_NO_ERROR) {
+               ast_log(LOG_DEBUG, "OSP: Unable to get destination protocol, error '%d'\n", error);
+               *reason = OSPC_FAIL_NORMAL_UNSPECIFIED; 
+               result->token[0] = '\0';
+               return -1;
+       } 
+
+       res = 1;
+       /* Strip leading and trailing brackets */
+       destination[strlen(destination) - 1] = '\0';
+       switch(protocol) {
+               case OSPE_DEST_PROT_H323_SETUP:
+                       ast_log(LOG_DEBUG, "OSP: protocol '%d'\n", protocol);
+                       ast_copy_string(result->tech, "H323", sizeof(result->tech));
+                       snprintf(result->dest, sizeof(result->dest), "%s@%s", called, destination + 1);
+                       ast_copy_string(result->calling, calling, sizeof(result->calling));
+                       break;
+               case OSPE_DEST_PROT_SIP:
+                       ast_log(LOG_DEBUG, "OSP: protocol '%d'\n", protocol);
+                       ast_copy_string(result->tech, "SIP", sizeof(result->tech));
+                       snprintf(result->dest, sizeof(result->dest), "%s@%s", called, destination + 1);
+                       ast_copy_string(result->calling, calling, sizeof(result->calling));
+                       break;
+               case OSPE_DEST_PROT_IAX:
+                       ast_log(LOG_DEBUG, "OSP: protocol '%d'\n", protocol);
+                       ast_copy_string(result->tech, "IAX", sizeof(result->tech));
+                       snprintf(result->dest, sizeof(result->dest), "%s@%s", called, destination + 1);
+                       ast_copy_string(result->calling, calling, sizeof(result->calling));
+                       break;
+               default:
+                       ast_log(LOG_DEBUG, "OSP: Unknown protocol '%d'\n", protocol);
+                       *reason = OSPC_FAIL_PROTOCOL_ERROR; 
+                       result->token[0] = '\0';
+                       res = 0;
+       }
+
+       return res;
+}
+
+/*!
+ * \brief Convert Asterisk status to TC code
+ * \param cause Asterisk hangup cause
+ * \return OSP TC code
+ */
+static enum OSPEFAILREASON asterisk2osp(
+       int cause)                                              /* Asterisk hangup cause */
+{
+       return (enum OSPEFAILREASON)cause;
+}
+
+/*!
+ * \brief OSP Authentication function
+ * \param provider OSP provider context name
+ * \param transaction OSP transaction handle, output
+ * \param source Source of inbound call
+ * \param calling Calling number
+ * \param called Called number
+ * \param token OSP token, may be empty
+ * \param timelimit Call duration limit, output
+ * \return 1 Authenricated, 0 Unauthenticated, -1 Error
+ */
+static int osp_auth(
+       const char* provider,           /* OSP provider context name */
+       int* transaction,                       /* OSP transaction handle, output */
+       const char* source,                     /* Source of inbound call */
+       const char* calling,            /* Calling number */
+       const char* called,                     /* Called number */
+       const char* token,                      /* OSP token, may be empty */
+       unsigned int* timelimit)        /* Call duration limit, output */
+{
+       int res;
+       int policy;
+       char dest[OSP_NORSTR_SIZE];
+
+       *transaction = OSP_INVALID_HANDLE;
+       *timelimit = OSP_DEF_TIMELIMIT;
+
+       if ((res = osp_get_policy(provider, &policy)) <= 0) {
+               ast_log(LOG_DEBUG, "OSP: Unabe to find OSP authentication policy\n");
+               return res;
+       }
+
+       switch (policy) {
+               case OSP_AUTH_NO:
+                       res = 1;
+                       break;
+               case OSP_AUTH_EXCLUSIVE:
+                       if (ast_strlen_zero(token)) {
+                               res = 0;
+                       } else if ((res = osp_create_transaction(provider, transaction, sizeof(dest), dest)) <= 0) {
+                               ast_log(LOG_DEBUG, "OSP: Unable to generate transaction handle\n");
+                               *transaction = OSP_INVALID_HANDLE;
+                               res = 0;
+                       } else if((res = osp_validate_token(*transaction, source, dest, calling, called, token, timelimit)) <= 0) {
+                               OSPPTransactionRecordFailure(*transaction, OSPC_FAIL_CALL_REJECTED);
+                       }
+                       break;
+               case OSP_AUTH_YES:
+               default:
+                       if (ast_strlen_zero(token)) {
+                               res = 1;
+                       } else if ((res = osp_create_transaction(provider, transaction, sizeof(dest), dest)) <= 0) {
+                               ast_log(LOG_DEBUG, "OSP: Unable to generate transaction handle\n");
+                               *transaction = OSP_INVALID_HANDLE;
+                               res = 0;
+                       } else if((res = osp_validate_token(*transaction, source, dest, calling, called, token, timelimit)) <= 0) {
+                               OSPPTransactionRecordFailure(*transaction, OSPC_FAIL_CALL_REJECTED);
+                       }
+                       break;
+       }
+
+       return res;
+}
+
+/*!
+ * \brief OSP Lookup function
+ * \param provider OSP provider context name
+ * \param srcdev Source device of outbound call
+ * \param calling Calling number
+ * \param called Called number
+ * \param result Lookup results
+ * \return 1 Found , 0 No route, -1 Error
+ */
+static int osp_lookup(
+       const char* provider,           /* OSP provider conttext name */
+       const char* srcdev,                     /* Source device of outbound call */
+       const char* calling,            /* Calling number */
+       const char* called,                     /* Called number */
+       struct osp_result* result)      /* OSP lookup results, in/output */
+{
+       int res;
+       char source[OSP_NORSTR_SIZE];
+       unsigned int callidlen;
+       char callid[OSPC_CALLID_MAXSIZE];
+       char callingnum[OSP_NORSTR_SIZE];
+       char callednum[OSP_NORSTR_SIZE];
+       char destination[OSP_NORSTR_SIZE];
+       unsigned int tokenlen;
+       char token[OSP_TOKSTR_SIZE];
+       unsigned int dummy = 0;
+       enum OSPEFAILREASON reason;
+       int error;
+
+       result->outhandle = OSP_INVALID_HANDLE;
+       result->tech[0] = '\0';
+       result->dest[0] = '\0';
+       result->calling[0] = '\0';
+       result->token[0] = '\0';
+       result->numresults = 0;
+       result->outtimelimit = OSP_DEF_TIMELIMIT;
+
+       if ((res = osp_create_transaction(provider, &result->outhandle, sizeof(source), source)) <= 0) {
+               ast_log(LOG_DEBUG, "OSP: Unable to generate transaction handle\n");
+               result->outhandle = OSP_INVALID_HANDLE;
+               if (result->inhandle != OSP_INVALID_HANDLE) {
+                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
+               }
+               return -1;
+       }
+
+       result->numresults = OSP_DEF_DESTINATIONS;
+       error = OSPPTransactionRequestAuthorisation(
+               result->outhandle, 
+               source, srcdev,
+               calling ? calling : "", OSPC_E164, 
+               called, OSPC_E164, 
+               NULL, 
+               0, NULL, 
+               NULL, 
+               &result->numresults, 
+               &dummy, NULL);
+       if (error != OSPC_ERR_NO_ERROR) {
+               ast_log(LOG_DEBUG, "OSP: Unable to request authorization\n");
+               result->numresults = 0;
+               if (result->inhandle != OSP_INVALID_HANDLE) {
+                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
+               }
+               return -1;
+       }
+
+       if (!result->numresults) {
+               ast_log(LOG_DEBUG, "OSP: No more destination\n");
+               if (result->inhandle != OSP_INVALID_HANDLE) {
+                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
+               }
+               return 0;
+       }
+
+       callidlen = sizeof(callid);
+       tokenlen = sizeof(token);
+       error = OSPPTransactionGetFirstDestination(
+               result->outhandle, 
+               0, NULL, NULL, 
+               &result->outtimelimit, 
+               &callidlen, callid,
+               sizeof(callednum), callednum, 
+               sizeof(callingnum), callingnum, 
+               sizeof(destination), destination, 
+               0, NULL, 
+               &tokenlen, token);
+       if (error != OSPC_ERR_NO_ERROR) {
+               ast_log(LOG_DEBUG, "OSP: Unable to get first route\n");
+               result->numresults = 0;
+               result->outtimelimit = OSP_DEF_TIMELIMIT;
+               if (result->inhandle != OSP_INVALID_HANDLE) {
+                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
+               }
+               return -1;
+       }
+
+       result->numresults--;
+       result->outtimelimit = osp_choose_timelimit(result->intimelimit, result->outtimelimit);
+       ast_log(LOG_DEBUG, "OSP: outtimelimit '%d'\n", result->outtimelimit);
+       ast_log(LOG_DEBUG, "OSP: called '%s'\n", callednum);
+       ast_log(LOG_DEBUG, "OSP: calling '%s'\n", callingnum);
+       ast_log(LOG_DEBUG, "OSP: destination '%s'\n", destination);
+       ast_log(LOG_DEBUG, "OSP: token size '%d'\n", tokenlen);
+
+       if ((res = osp_check_destination(callednum, callingnum, destination, tokenlen, token, &reason, result)) > 0) {
+               return 1;
+       }
+
+       if (!result->numresults) {
+               ast_log(LOG_DEBUG, "OSP: No more destination\n");
+               result->outtimelimit = OSP_DEF_TIMELIMIT;
+               OSPPTransactionRecordFailure(result->outhandle, reason);
+               if (result->inhandle != OSP_INVALID_HANDLE) {
+                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
+               }
+               return 0;
+       }
+
+       while(result->numresults) {
+               callidlen = sizeof(callid);
+               tokenlen = sizeof(token);
+               error = OSPPTransactionGetNextDestination(
+                       result->outhandle, 
+                       reason, 
+                       0, NULL, NULL, 
+                       &result->outtimelimit, 
+                       &callidlen, callid,
+                       sizeof(callednum), callednum, 
+                       sizeof(callingnum), callingnum, 
+                       sizeof(destination), destination, 
+                       0, NULL, 
+                       &tokenlen, token);
+               if (error == OSPC_ERR_NO_ERROR) {
+                       result->numresults--;
+                       result->outtimelimit = osp_choose_timelimit(result->intimelimit, result->outtimelimit);
+                       ast_log(LOG_DEBUG, "OSP: outtimelimit '%d'\n", result->outtimelimit);
+                       ast_log(LOG_DEBUG, "OSP: called '%s'\n", callednum);
+                       ast_log(LOG_DEBUG, "OSP: calling '%s'\n", callingnum);
+                       ast_log(LOG_DEBUG, "OSP: destination '%s'\n", destination);
+                       ast_log(LOG_DEBUG, "OSP: token size '%d'\n", tokenlen);
+                       if ((res = osp_check_destination(callednum, callingnum, destination, tokenlen, token, &reason, result)) > 0) {
+                               break;
+                       } else if (!result->numresults) {
+                               ast_log(LOG_DEBUG, "OSP: No more destination\n");
+                               OSPPTransactionRecordFailure(result->outhandle, reason);
+                               if (result->inhandle != OSP_INVALID_HANDLE) {
+                                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
+                               }
+                               res = 0;
+                               break;
+                       }
+               } else {
+                       ast_log(LOG_DEBUG, "OSP: Unable to get route, error '%d'\n", error);
+                       result->numresults = 0;
+                       result->outtimelimit = OSP_DEF_TIMELIMIT;
+                       if (result->inhandle != OSP_INVALID_HANDLE) {
+                               OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
+                       }
+                       res = -1;
+                       break;
+               }
+       }
+       return res;
+}
+
+/*!
+ * \brief OSP Lookup Next function
+ * \param cause Asterisk hangup cuase
+ * \param result Lookup results, in/output
+ * \return 1 Found , 0 No route, -1 Error
+ */
+static int osp_next(
+       int cause,                                      /* Asterisk hangup cuase */
+       struct osp_result* result)      /* OSP lookup results, in/output */
+{
+       int res;
+       unsigned int callidlen;
+       char callid[OSPC_CALLID_MAXSIZE];
+       char callingnum[OSP_NORSTR_SIZE];
+       char callednum[OSP_NORSTR_SIZE];
+       char destination[OSP_NORSTR_SIZE];
+       unsigned int tokenlen;
+       char token[OSP_TOKSTR_SIZE];
+       enum OSPEFAILREASON reason;
+       int error;
+
+       result->tech[0] = '\0';
+       result->dest[0] = '\0';
+       result->calling[0] = '\0';
+       result->token[0] = '\0';
+       result->outtimelimit = OSP_DEF_TIMELIMIT;
+
+       if (result->outhandle == OSP_INVALID_HANDLE) {
+               ast_log(LOG_DEBUG, "OSP: Transaction handle undefined\n");
+               result->numresults = 0;
+               if (result->inhandle != OSP_INVALID_HANDLE) {
+                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
+               }
+               return -1;
+       }
+
+       reason = asterisk2osp(cause);
+
+       if (!result->numresults) {
+               ast_log(LOG_DEBUG, "OSP: No more destination\n");
+               OSPPTransactionRecordFailure(result->outhandle, reason);
+               if (result->inhandle != OSP_INVALID_HANDLE) {
+                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
+               }
+               return 0;
+       }
+
+       while(result->numresults) {
+               callidlen = sizeof(callid);
+               tokenlen = sizeof(token);
+               error = OSPPTransactionGetNextDestination(
+                       result->outhandle, 
+                       reason, 
+                       0, NULL, NULL, 
+                       &result->outtimelimit, 
+                       &callidlen, callid,
+                       sizeof(callednum), callednum, 
+                       sizeof(callingnum), callingnum, 
+                       sizeof(destination), destination, 
+                       0, NULL, 
+                       &tokenlen, token);
+               if (error == OSPC_ERR_NO_ERROR) {
+                       result->numresults--;
+                       result->outtimelimit = osp_choose_timelimit(result->intimelimit, result->outtimelimit);
+                       ast_log(LOG_DEBUG, "OSP: outtimelimit '%d'\n", result->outtimelimit);
+                       ast_log(LOG_DEBUG, "OSP: called '%s'\n", callednum);
+                       ast_log(LOG_DEBUG, "OSP: calling '%s'\n", callingnum);
+                       ast_log(LOG_DEBUG, "OSP: destination '%s'\n", destination);
+                       ast_log(LOG_DEBUG, "OSP: token size '%d'\n", tokenlen);
+                       if ((res = osp_check_destination(callednum, callingnum, destination, tokenlen, token, &reason, result)) > 0) {
+                               res = 1;
+                               break;
+                       } else if (!result->numresults) {
+                               ast_log(LOG_DEBUG, "OSP: No more destination\n");
+                               OSPPTransactionRecordFailure(result->outhandle, reason);
+                               if (result->inhandle != OSP_INVALID_HANDLE) {
+                                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
+                               }
+                               res = 0;
+                               break;
+                       }
+               } else {
+                       ast_log(LOG_DEBUG, "OSP: Unable to get route, error '%d'\n", error);
+                       result->token[0] = '\0';
+                       result->numresults = 0;
+                       result->outtimelimit = OSP_DEF_TIMELIMIT;
+                       if (result->inhandle != OSP_INVALID_HANDLE) {
+                               OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
+                       }
+                       res = -1;
+                       break;
+               }
+       }
+
+       return res;
+}
+
+/*!
+ * \brief OSP Finish function
+ * \param handle OSP in/outbound transaction handle
+ * \param recorded If failure reason has been recorded
+ * \param cause Asterisk hangup cause
+ * \param start Call start time
+ * \param connect Call connect time
+ * \param end Call end time
+ * \param release Who release first, 0 source, 1 destination
+ * \return 1 Success, 0 Failed, -1 Error
+ */
+static int osp_finish(
+       int handle,                             /* OSP in/outbound transaction handle */
+       int recorded,                   /* If failure reason has been recorded */
+       int cause,                              /* Asterisk hangup cause */
+       time_t start,                   /* Call start time */
+       time_t connect,                 /* Call connect time */
+       time_t end,                             /* Call end time */
+       unsigned int release)   /* Who release first, 0 source, 1 destination */
+{
+       int res;
+       enum OSPEFAILREASON reason;
+       time_t alert = 0;
+       unsigned isPddInfoPresent = 0;
+       unsigned pdd = 0;
+       unsigned char* confId = "";
+       unsigned int dummy = 0;
+       int error;
+       
+       if (handle == OSP_INVALID_HANDLE) {
+               return 0;
+       }
+
+       if (!recorded) {
+               reason = asterisk2osp(cause);
+               OSPPTransactionRecordFailure(handle, reason);
+       }
+
+       error = OSPPTransactionReportUsage(
+               handle, 
+               difftime(end, connect), start, end, alert, connect, 
+               isPddInfoPresent, pdd, 
+               release, 
+               confId,
+               0, 0, 0, 0,
+               &dummy, NULL);
+       if (error == OSPC_ERR_NO_ERROR) {
+               ast_log(LOG_DEBUG, "OSP: Usage reported\n");
+               res = 1;
+       } else {
+               ast_log(LOG_DEBUG, "OSP: Unable to report usage, error '%d'\n", error);
+               res = -1;
+       }
+       OSPPTransactionDelete(handle);
+
+       return res;
+}
+
+/* OSP Application APIs */
+
+/*!
+ * \brief OSP Application OSPAuth
+ * \param chan Channel
+ * \param data Parameter
+ * \return 0 Success, -1 Failed
+ */
+static int ospauth_exec(struct ast_channel* chan, void* data)
+{
+       int res;
        struct localuser* u;
-       char* provider = OSP_DEF_PROVIDER;
+       const char* provider = OSP_DEF_PROVIDER;
        int priority_jump = 0;
        struct varshead* headp;
        struct ast_var_t* current;
@@ -126,9 +988,9 @@ static int ospauth_exec(struct ast_channel *chan, void *data)
        const char* token = "";
        int handle;
        unsigned int timelimit;
-       char* tmp;
        char buffer[OSP_INTSTR_SIZE];
-       char* status;
+       const char* status;
+       char* tmp;
 
        AST_DECLARE_APP_ARGS(args,
                AST_APP_ARG(provider);
@@ -137,7 +999,11 @@ static int ospauth_exec(struct ast_channel *chan, void *data)
 
        LOCAL_USER_ADD(u);
 
-       tmp = ast_strdupa(data);
+       if (!(tmp = ast_strdupa(data))) {
+               ast_log(LOG_ERROR, "Out of memory\n");
+               LOCAL_USER_REMOVE(u);
+               return -1;
+       }
 
        AST_STANDARD_APP_ARGS(args, tmp);
 
@@ -146,10 +1012,8 @@ static int ospauth_exec(struct ast_channel *chan, void *data)
        }
        ast_log(LOG_DEBUG, "OSPAuth: provider '%s'\n", provider);
 
-       if (args.options) {
-               if (strchr(args.options, 'j')) {
-                       priority_jump = 1;
-               }
+       if ((args.options) && (strchr(args.options, 'j'))) {
+               priority_jump = 1;
        }
        ast_log(LOG_DEBUG, "OSPAuth: priority jump '%d'\n", priority_jump);
 
@@ -164,16 +1028,15 @@ static int ospauth_exec(struct ast_channel *chan, void *data)
        ast_log(LOG_DEBUG, "OSPAuth: source '%s'\n", source);
        ast_log(LOG_DEBUG, "OSPAuth: token size '%zd'\n", strlen(token));
 
-       res = ast_osp_auth(provider, &handle, source, chan->cid.cid_num, chan->exten, token, &timelimit);
-       if (res > 0) {
-               status = OSP_APP_SUCCESS;
+       
+       if ((res = osp_auth(provider, &handle, source, chan->cid.cid_num, chan->exten, token, &timelimit)) > 0) {
+               status = AST_OSP_SUCCESS;
        } else {
                timelimit = OSP_DEF_TIMELIMIT;
                if (!res) {
-                       status = OSP_APP_FAILED;
+                       status = AST_OSP_FAILED;
                } else {
-                       handle = OSP_INVALID_HANDLE;
-                       status = OSP_APP_ERROR;
+                       status = AST_OSP_ERROR;
                }
        }
 
@@ -186,34 +1049,41 @@ static int ospauth_exec(struct ast_channel *chan, void *data)
        pbx_builtin_setvar_helper(chan, "OSPAUTHSTATUS", status);
        ast_log(LOG_DEBUG, "OSPAuth: %s\n", status);
 
-       if(!res) {
+       if(res <= 0) {
                if (priority_jump || ast_opt_priority_jumping) {
                        ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101);
+                       res = 0;
                } else {
                        res = -1;
                }
-       } else if (res > 0) {
+       } else {
                res = 0;
        }
 
        LOCAL_USER_REMOVE(u);
 
-       return(res);
+       return res;
 }
 
-static int osplookup_exec(struct ast_channel *chan, void *data)
+/*!
+ * \brief OSP Application OSPLookup
+ * \param chan Channel
+ * \param data Parameter
+ * \return 0 Success, -1 Failed
+ */
+static int osplookup_exec(struct ast_channel* chan, void* data)
 {
-       int res = 0;
+       int res, cres;
        struct localuser* u;
-       char* provider = OSP_DEF_PROVIDER;
+       const char* provider = OSP_DEF_PROVIDER;
        int priority_jump = 0;
        struct varshead* headp;
        struct ast_var_t* current;
        const char* srcdev = "";
-       char* tmp;
        char buffer[OSP_TOKSTR_SIZE];
-       struct ast_osp_result result;
-       char* status;
+       struct osp_result result;
+       const char* status;
+       char* tmp;
 
        AST_DECLARE_APP_ARGS(args,
                AST_APP_ARG(exten);
@@ -223,12 +1093,16 @@ static int osplookup_exec(struct ast_channel *chan, void *data)
        
        if (ast_strlen_zero(data)) {
                ast_log(LOG_WARNING, "OSPLookup: Arg required, OSPLookup(exten[|provider[|options]])\n");
-               return(-1);
+               return -1;
        }
 
        LOCAL_USER_ADD(u);
 
-       tmp = ast_strdupa(data);
+       if (!(tmp = ast_strdupa(data))) {
+               ast_log(LOG_ERROR, "Out of memory\n");
+               LOCAL_USER_REMOVE(u);
+               return -1;
+       }
 
        AST_STANDARD_APP_ARGS(args, tmp);
 
@@ -239,14 +1113,13 @@ static int osplookup_exec(struct ast_channel *chan, void *data)
        }
        ast_log(LOG_DEBUG, "OSPlookup: provider '%s'\n", provider);
 
-       if (args.options) {
-               if (strchr(args.options, 'j')) {
-                       priority_jump = 1;
-               }
+       if ((args.options) && (strchr(args.options, 'j'))) {
+               priority_jump = 1;
        }
        ast_log(LOG_DEBUG, "OSPLookup: priority jump '%d'\n", priority_jump);
 
        result.inhandle = OSP_INVALID_HANDLE;
+       result.intimelimit = OSP_DEF_TIMELIMIT;
 
        headp = &chan->varshead;
        AST_LIST_TRAVERSE(headp, current, entries) {
@@ -265,10 +1138,14 @@ static int osplookup_exec(struct ast_channel *chan, void *data)
        ast_log(LOG_DEBUG, "OSPLookup: OSPINHANDLE '%d'\n", result.inhandle);
        ast_log(LOG_DEBUG, "OSPLookup: OSPINTIMELIMIT '%d'\n", result.intimelimit);
        ast_log(LOG_DEBUG, "OSPLookup: source device '%s'\n", srcdev);
+       
+       if ((cres = ast_autoservice_start(chan)) < 0) {
+               LOCAL_USER_REMOVE(u);
+               return -1;
+       }
 
-       res = ast_osp_lookup(provider, srcdev, chan->cid.cid_num, args.exten, &result);
-       if (res > 0) {
-               status = OSP_APP_SUCCESS;
+       if ((res = osp_lookup(provider, srcdev, chan->cid.cid_num, args.exten, &result)) > 0) {
+               status = AST_OSP_SUCCESS;
        } else {
                result.tech[0] = '\0';
                result.dest[0] = '\0';
@@ -277,10 +1154,9 @@ static int osplookup_exec(struct ast_channel *chan, void *data)
                result.numresults = 0;
                result.outtimelimit = OSP_DEF_TIMELIMIT;
                if (!res) {
-                       status = OSP_APP_FAILED;
+                       status = AST_OSP_FAILED;
                } else {
-                       result.outhandle = OSP_INVALID_HANDLE;
-                       status = OSP_APP_ERROR;
+                       status = AST_OSP_ERROR;
                }
        }
 
@@ -295,11 +1171,6 @@ static int osplookup_exec(struct ast_channel *chan, void *data)
        ast_log(LOG_DEBUG, "OSPLookup: OSPCALLING '%s'\n", result.calling);
        pbx_builtin_setvar_helper(chan, "OSPOUTTOKEN", result.token);
        ast_log(LOG_DEBUG, "OSPLookup: OSPOUTTOKEN size '%zd'\n", strlen(result.token));
-       if (!ast_strlen_zero(result.token)) {
-               snprintf(buffer, sizeof(buffer), "P-OSP-Auth-Token: %s", result.token);
-               pbx_builtin_setvar_helper(chan, "_SIPADDHEADER", buffer);
-               ast_log(LOG_DEBUG, "OSPLookup: SIPADDHEADER size '%zd'\n", strlen(buffer));
-       }
        snprintf(buffer, sizeof(buffer), "%d", result.numresults);
        pbx_builtin_setvar_helper(chan, "OSPRESULTS", buffer);
        ast_log(LOG_DEBUG, "OSPLookup: OSPRESULTS '%s'\n", buffer);
@@ -309,58 +1180,55 @@ static int osplookup_exec(struct ast_channel *chan, void *data)
        pbx_builtin_setvar_helper(chan, "OSPLOOKUPSTATUS", status);
        ast_log(LOG_DEBUG, "OSPLookup: %s\n", status);
 
-       if(!res) {
+       if (!strcasecmp(result.tech, "SIP")) {
+               if (!ast_strlen_zero(result.token)) {
+                       snprintf(buffer, sizeof(buffer), "P-OSP-Auth-Token: %s", result.token);
+                       pbx_builtin_setvar_helper(chan, "_SIPADDHEADER", buffer);
+                       ast_log(LOG_DEBUG, "OSPLookup: SIPADDHEADER size '%zd'\n", strlen(buffer));
+               }
+       } else if (!strcasecmp(result.tech, "H323")) {
+       } else if (!strcasecmp(result.tech, "IAX")) {
+       }
+
+       if ((cres = ast_autoservice_stop(chan)) < 0) {
+               LOCAL_USER_REMOVE(u);
+               return -1;
+       }
+
+       if(res <= 0) {
                if (priority_jump || ast_opt_priority_jumping) {
                        ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101);
+                       res = 0;
                } else {
                        res = -1;
                }
-       } else if (res > 0) {
+       } else {
                res = 0;
        }
 
        LOCAL_USER_REMOVE(u);
 
-       return(res);
-}
-
-static int str2cause(char *str)
-{
-       int cause = AST_CAUSE_NORMAL;
-
-       if (ast_strlen_zero(str)) {
-               cause = AST_CAUSE_NOTDEFINED;
-       } else if (!strcasecmp(str, "BUSY")) {
-               cause = AST_CAUSE_BUSY;
-       } else if (!strcasecmp(str, "CONGESTION")) {
-               cause = AST_CAUSE_CONGESTION;
-       } else if (!strcasecmp(str, "ANSWER")) {
-               cause = AST_CAUSE_NORMAL;
-       } else if (!strcasecmp(str, "CANCEL")) {
-               cause = AST_CAUSE_NORMAL;
-       } else if (!strcasecmp(str, "NOANSWER")) {
-               cause = AST_CAUSE_NOANSWER;
-       } else if (!strcasecmp(str, "NOCHANAVAIL")) {
-               cause = AST_CAUSE_CONGESTION;
-       } else {
-               ast_log(LOG_WARNING, "OSP: Unknown cause '%s', using NORMAL\n", str);
-       }
-
-       return(cause);
+       return res;
 }
 
-static int ospnext_exec(struct ast_channel *chan, void *data)
+/*!
+ * \brief OSP Application OSPNext
+ * \param chan Channel
+ * \param data Parameter
+ * \return 0 Success, -1 Failed
+ */
+static int ospnext_exec(struct ast_channel* chan, void* data)
 {
-       int res=0;
-       struct localuser *u;
+       int res;
+       struct localuser* u;
        int priority_jump = 0;
-       int cause;
+       int cause = 0;
        struct varshead* headp;
        struct ast_var_t* current;
-       struct ast_osp_result result;
-       char *tmp;
+       struct osp_result result;
        char buffer[OSP_TOKSTR_SIZE];
-       char* status;
+       const char* status;
+       char* tmp;
 
        AST_DECLARE_APP_ARGS(args,
                AST_APP_ARG(cause);
@@ -369,26 +1237,32 @@ static int ospnext_exec(struct ast_channel *chan, void *data)
        
        if (ast_strlen_zero(data)) {
                ast_log(LOG_WARNING, "OSPNext: Arg required, OSPNext(cause[|options])\n");
-               return(-1);
+               return -1;
        }
 
        LOCAL_USER_ADD(u);
 
-       tmp = ast_strdupa(data);
+       if (!(tmp = ast_strdupa(data))) {
+               ast_log(LOG_ERROR, "Out of memory\n");
+               LOCAL_USER_REMOVE(u);
+               return -1;
+       }
 
        AST_STANDARD_APP_ARGS(args, tmp);
 
-       cause = str2cause(args.cause);
+       if (!ast_strlen_zero(args.cause) && sscanf(args.cause, "%d", &cause) != 1) {
+               cause = 0;
+       }
        ast_log(LOG_DEBUG, "OSPNext: cause '%d'\n", cause);
 
-       if (args.options) {
-               if (strchr(args.options, 'j'))
-                       priority_jump = 1;
+       if ((args.options) && (strchr(args.options, 'j'))) {
+               priority_jump = 1;
        }
        ast_log(LOG_DEBUG, "OSPNext: priority jump '%d'\n", priority_jump);
 
        result.inhandle = OSP_INVALID_HANDLE;
        result.outhandle = OSP_INVALID_HANDLE;
+       result.intimelimit = OSP_DEF_TIMELIMIT;
        result.numresults = 0;
 
        headp = &chan->varshead;
@@ -401,7 +1275,7 @@ static int ospnext_exec(struct ast_channel *chan, void *data)
                        if (sscanf(ast_var_value(current), "%d", &result.outhandle) != 1) {
                                result.outhandle = OSP_INVALID_HANDLE;
                        }
-               } else if (!strcasecmp(ast_var_name(current), "OSPINTIMEOUT")) {
+               } else if (!strcasecmp(ast_var_name(current), "OSPINTIMELIMIT")) {
                        if (sscanf(ast_var_value(current), "%d", &result.intimelimit) != 1) {
                                result.intimelimit = OSP_DEF_TIMELIMIT;
                        }
@@ -416,8 +1290,8 @@ static int ospnext_exec(struct ast_channel *chan, void *data)
        ast_log(LOG_DEBUG, "OSPNext: OSPINTIMELIMIT '%d'\n", result.intimelimit);
        ast_log(LOG_DEBUG, "OSPNext: OSPRESULTS '%d'\n", result.numresults);
 
-       if ((res = ast_osp_next(cause, &result)) > 0) {
-               status = OSP_APP_SUCCESS;
+       if ((res = osp_next(cause, &result)) > 0) {
+               status = AST_OSP_SUCCESS;
        } else {
                result.tech[0] = '\0';
                result.dest[0] = '\0';
@@ -426,10 +1300,9 @@ static int ospnext_exec(struct ast_channel *chan, void *data)
                result.numresults = 0;
                result.outtimelimit = OSP_DEF_TIMELIMIT;
                if (!res) {
-                       status = OSP_APP_FAILED;
+                       status = AST_OSP_FAILED;
                } else {
-                       result.outhandle = OSP_INVALID_HANDLE;
-                       status = OSP_APP_ERROR;
+                       status = AST_OSP_ERROR;
                }
        }
 
@@ -441,11 +1314,6 @@ static int ospnext_exec(struct ast_channel *chan, void *data)
        ast_log(LOG_DEBUG, "OSPNext: OSPCALLING '%s'\n", result.calling);
        pbx_builtin_setvar_helper(chan, "OSPOUTTOKEN", result.token);
        ast_log(LOG_DEBUG, "OSPNext: OSPOUTTOKEN size '%zd'\n", strlen(result.token));
-       if (!ast_strlen_zero(result.token)) {
-               snprintf(buffer, sizeof(buffer), "P-OSP-Auth-Token: %s", result.token);
-               pbx_builtin_setvar_helper(chan, "_SIPADDHEADER", buffer);
-               ast_log(LOG_DEBUG, "OSPNext: SIPADDHEADER size '%zd'\n", strlen(buffer));
-       }
        snprintf(buffer, sizeof(buffer), "%d", result.numresults);
        pbx_builtin_setvar_helper(chan, "OSPRESULTS", buffer);
        ast_log(LOG_DEBUG, "OSPNext: OSPRESULTS '%s'\n", buffer);
@@ -455,52 +1323,72 @@ static int ospnext_exec(struct ast_channel *chan, void *data)
        pbx_builtin_setvar_helper(chan, "OSPNEXTSTATUS", status);
        ast_log(LOG_DEBUG, "OSPNext: %s\n", status);
 
-       if(!res) {
+       if (!strcasecmp(result.tech, "SIP")) {
+               if (!ast_strlen_zero(result.token)) {
+                       snprintf(buffer, sizeof(buffer), "P-OSP-Auth-Token: %s", result.token);
+                       pbx_builtin_setvar_helper(chan, "_SIPADDHEADER", buffer);
+                       ast_log(LOG_DEBUG, "OSPLookup: SIPADDHEADER size '%zd'\n", strlen(buffer));
+               }
+       } else if (!strcasecmp(result.tech, "H323")) {
+       } else if (!strcasecmp(result.tech, "IAX")) {
+       }
+
+       if(res <= 0) {
                if (priority_jump || ast_opt_priority_jumping) {
                        ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101);
+                       res = 0;
                } else {
                        res = -1;
                }
-       } else if (res > 0) {
+       } else {
                res = 0;
        }
 
        LOCAL_USER_REMOVE(u);
 
-       return(res);
+       return res;
 }
 
-static int ospfinished_exec(struct ast_channel *chan, void *data)
+/*!
+ * \brief OSP Application OSPFinish
+ * \param chan Channel
+ * \param data Parameter
+ * \return 0 Success, -1 Failed
+ */
+static int ospfinished_exec(struct ast_channel* chan, void* data)
 {
        int res = 1;
        struct localuser* u;
        int priority_jump = 0;
-       int cause;
+       int cause = 0;
        struct varshead* headp;
        struct ast_var_t* current;
        int inhandle = OSP_INVALID_HANDLE;
        int outhandle = OSP_INVALID_HANDLE;
        int recorded = 0;
        time_t start, connect, end;
-       char* tmp;
-       char* str = "";
+       unsigned int release;
        char buffer[OSP_INTSTR_SIZE];
-       char* status;
+       const char* status;
+       char* tmp;
 
        AST_DECLARE_APP_ARGS(args,
-               AST_APP_ARG(status);
+               AST_APP_ARG(cause);
                AST_APP_ARG(options);
        );
        
        LOCAL_USER_ADD(u);
 
-       tmp = ast_strdupa(data);
+       if (!(tmp = ast_strdupa(data))) {
+               ast_log(LOG_ERROR, "Out of memory\n");
+               LOCAL_USER_REMOVE(u);
+               return -1;
+       }
 
        AST_STANDARD_APP_ARGS(args, tmp);
 
-       if (args.options) {
-               if (strchr(args.options, 'j'))
-                       priority_jump = 1;
+       if ((args.options) && (strchr(args.options, 'j'))) {
+               priority_jump = 1;
        }
        ast_log(LOG_DEBUG, "OSPFinish: priority jump '%d'\n", priority_jump);
 
@@ -519,7 +1407,7 @@ static int ospfinished_exec(struct ast_channel *chan, void *data)
                        !strcasecmp(ast_var_name(current), "OSPLOOKUPSTATUS") || 
                        !strcasecmp(ast_var_name(current), "OSPNEXTSTATUS"))) 
                {
-                       if (strcasecmp(ast_var_value(current), OSP_APP_SUCCESS)) {
+                       if (strcasecmp(ast_var_value(current), AST_OSP_SUCCESS)) {
                                recorded = 1;
                        }
                }
@@ -528,10 +1416,9 @@ static int ospfinished_exec(struct ast_channel *chan, void *data)
        ast_log(LOG_DEBUG, "OSPFinish: OSPOUTHANDLE '%d'\n", outhandle);
        ast_log(LOG_DEBUG, "OSPFinish: recorded '%d'\n", recorded);
 
-       if (!recorded) {
-               str = args.status;
+       if (!ast_strlen_zero(args.cause) && sscanf(args.cause, "%d", &cause) != 1) {
+               cause = 0;
        }
-       cause = str2cause(str);
        ast_log(LOG_DEBUG, "OSPFinish: cause '%d'\n", cause);
 
        if (chan->cdr) {
@@ -551,55 +1438,288 @@ static int ospfinished_exec(struct ast_channel *chan, void *data)
        ast_log(LOG_DEBUG, "OSPFinish: connect '%ld'\n", connect);
        ast_log(LOG_DEBUG, "OSPFinish: end '%ld'\n", end);
 
-       if (ast_osp_finish(outhandle, cause, start, connect, end) <= 0) {
-               ast_log(LOG_DEBUG, "OSPFinish: Unable to report usage for out_bound call\n");
+       release = chan->_softhangup ? 0 : 1;
+
+       if (osp_finish(outhandle, recorded, cause, start, connect, end, release) <= 0) {
+               ast_log(LOG_DEBUG, "OSPFinish: Unable to report usage for outbound call\n");
+       }
+       switch (cause) {
+               case AST_CAUSE_NORMAL_CLEARING:
+                       break;
+               default:
+                       cause = AST_CAUSE_NO_ROUTE_DESTINATION;
+                       break;
        }
-       if (ast_osp_finish(inhandle, cause, start, connect, end) <= 0) {
-               ast_log(LOG_DEBUG, "OSPFinish: Unable to report usage for in_bound call\n");
+       if (osp_finish(inhandle, recorded, cause, start, connect, end, release) <= 0) {
+               ast_log(LOG_DEBUG, "OSPFinish: Unable to report usage for inbound call\n");
        }
        snprintf(buffer, sizeof(buffer), "%d", OSP_INVALID_HANDLE);
        pbx_builtin_setvar_helper(chan, "OSPOUTHANDLE", buffer);
        pbx_builtin_setvar_helper(chan, "OSPINHANDLE", buffer);
 
        if (res > 0) {
-               status = OSP_APP_SUCCESS;
+               status = AST_OSP_SUCCESS;
        } else if (!res) {
-               status = OSP_APP_FAILED;
+               status = AST_OSP_FAILED;
        } else {
-               status = OSP_APP_ERROR;
+               status = AST_OSP_ERROR;
        }
        pbx_builtin_setvar_helper(chan, "OSPFINISHSTATUS", status);
 
        if(!res) {
                if (priority_jump || ast_opt_priority_jumping) {
                        ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101);
+                       res = 0;
                } else {
                        res = -1;
                }
-       } else if (res > 0) {
+       } else {
                res = 0;
        }
 
        LOCAL_USER_REMOVE(u);
 
-       return(res);
+       return res;
+}
+
+/* OSP Module APIs */
+
+static int osp_load(void)
+{
+       char* t;
+       unsigned int v;
+       struct ast_config* cfg;
+       int error = OSPC_ERR_NO_ERROR;
+
+       cfg = ast_config_load(OSP_CONFIG_FILE);
+       if (cfg) {
+               t = ast_variable_retrieve(cfg, OSP_GENERAL_CAT, "accelerate");
+               if (t && ast_true(t)) {
+                       if ((error = OSPPInit(1)) != OSPC_ERR_NO_ERROR) {
+                               ast_log(LOG_WARNING, "OSP: Unable to enable hardware accelleration\n");
+                               OSPPInit(0);
+                       } else {
+                               osp_hardware = 1;
+                       }
+               } else {
+                       OSPPInit(0);
+               }
+               ast_log(LOG_DEBUG, "OSP: osp_hardware '%d'\n", osp_hardware);
+
+               t = ast_variable_retrieve(cfg, OSP_GENERAL_CAT, "tokenformat");
+               if (t) {
+                       if ((sscanf(t, "%d", &v) == 1) && 
+                               ((v == TOKEN_ALGO_SIGNED) || (v == TOKEN_ALGO_UNSIGNED) || (v == TOKEN_ALGO_BOTH))) 
+                       {
+                               osp_tokenformat = v;
+                       } else {
+                               ast_log(LOG_WARNING, "tokenformat should be an integer from %d, %d or %d, not '%s'\n", 
+                                       TOKEN_ALGO_SIGNED, TOKEN_ALGO_UNSIGNED, TOKEN_ALGO_BOTH, t);
+                       }
+               }
+               ast_log(LOG_DEBUG, "OSP: osp_tokenformat '%d'\n", osp_tokenformat);
+
+               t = ast_category_browse(cfg, NULL);
+               while(t) {
+                       if (strcasecmp(t, OSP_GENERAL_CAT)) {
+                               osp_create_provider(cfg, t);
+                       }
+                       t = ast_category_browse(cfg, t);
+               }
+
+               osp_initialized = 1;
+
+               ast_config_destroy(cfg);
+       } else {
+               ast_log(LOG_WARNING, "OSP: Unable to find configuration. OSP support disabled\n");
+       }
+       ast_log(LOG_DEBUG, "OSP: osp_initialized '%d'\n", osp_initialized);
+
+       return 0;
 }
 
-static int load_module(void *mod)
+static int osp_unload(void)
+{
+       struct osp_provider* p;
+       struct osp_provider* next;
+
+       if (osp_initialized) {
+               ast_mutex_lock(&osplock);
+               p = ospproviders;
+               while(p) {
+                       next = p->next;
+                       OSPPProviderDelete(p->handle, 0);
+                       free(p);
+                       p = next;
+               }
+               ospproviders = NULL;
+               ast_mutex_unlock(&osplock);
+
+               OSPPCleanup();
+
+               osp_tokenformat = TOKEN_ALGO_SIGNED;
+               osp_hardware = 0;
+               osp_initialized = 0;
+       }
+       return 0;
+}
+
+static int osp_show(int fd, int argc, char* argv[])
+{
+       int i;
+       int found = 0;
+       struct osp_provider* p;
+       const char* provider = NULL;
+       const char* tokenalgo;
+
+       if ((argc < 2) || (argc > 3)) {
+               return RESULT_SHOWUSAGE;
+       }
+       if (argc > 2) {
+               provider = argv[2];
+       }
+       if (!provider) {
+               switch (osp_tokenformat) {
+                       case TOKEN_ALGO_BOTH:
+                               tokenalgo = "Both";
+                               break;
+                       case TOKEN_ALGO_UNSIGNED:
+                               tokenalgo = "Unsigned";
+                               break;
+                       case TOKEN_ALGO_SIGNED:
+                       default:
+                               tokenalgo = "Signed";
+                               break;
+               }
+               ast_cli(fd, "OSP: %s %s %s\n", 
+                       osp_initialized ? "Initialized" : "Uninitialized", osp_hardware ? "Accelerated" : "Normal", tokenalgo);
+       }
+
+       ast_mutex_lock(&osplock);
+       p = ospproviders;
+       while(p) {
+               if (!provider || !strcasecmp(p->name, provider)) {
+                       if (found) {
+                               ast_cli(fd, "\n");
+                       }
+                       ast_cli(fd, " == OSP Provider '%s' == \n", p->name);
+                       ast_cli(fd, "Local Private Key: %s\n", p->privatekey);
+                       ast_cli(fd, "Local Certificate: %s\n", p->localcert);
+                       for (i = 0; i < p->cacount; i++) {
+                               ast_cli(fd, "CA Certificate %d:  %s\n", i + 1, p->cacerts[i]);
+                       }
+                       for (i = 0; i < p->spcount; i++) {
+                               ast_cli(fd, "Service Point %d:   %s\n", i + 1, p->srvpoints[i]);
+                       }
+                       ast_cli(fd, "Max Connections:   %d\n", p->maxconnections);
+                       ast_cli(fd, "Retry Delay:       %d seconds\n", p->retrydelay);
+                       ast_cli(fd, "Retry Limit:       %d\n", p->retrylimit);
+                       ast_cli(fd, "Timeout:           %d milliseconds\n", p->timeout);
+                       ast_cli(fd, "Source:            %s\n", strlen(p->source) ? p->source : "<unspecified>");
+                       ast_cli(fd, "Auth Policy        %d\n", p->authpolicy);
+                       ast_cli(fd, "OSP Handle:        %d\n", p->handle);
+                       found++;
+               }
+               p = p->next;
+       }
+       ast_mutex_unlock(&osplock);
+
+       if (!found) {
+               if (provider) {
+                       ast_cli(fd, "Unable to find OSP provider '%s'\n", provider);
+               } else {
+                       ast_cli(fd, "No OSP providers configured\n");
+               }
+       }
+       return RESULT_SUCCESS;
+}
+
+static const char* app1= "OSPAuth";
+static const char* synopsis1 = "OSP authentication";
+static const char* descrip1 = 
+"  OSPAuth([provider[|options]]):  Authenticate a SIP INVITE by OSP and sets\n"
+"the variables:\n"
+" ${OSPINHANDLE}:  The inbound call transaction handle\n"
+" ${OSPINTIMELIMIT}:  The inbound call duration limit in seconds\n"
+"\n"
+"The option string may contain the following character:\n"
+"      'j' -- jump to n+101 priority if the authentication was NOT successful\n"
+"This application sets the following channel variable upon completion:\n"
+"      OSPAUTHSTATUS   The status of the OSP Auth attempt as a text string, one of\n"
+"              SUCCESS | FAILED | ERROR\n";
+
+static const char* app2= "OSPLookup";
+static const char* synopsis2 = "Lookup destination by OSP";
+static const char* descrip2 = 
+"  OSPLookup(exten[|provider[|options]]):  Looks up an extension via OSP and sets\n"
+"the variables, where 'n' is the number of the result beginning with 1:\n"
+" ${OSPOUTHANDLE}:  The OSP Handle for anything remaining\n"
+" ${OSPTECH}:  The technology to use for the call\n"
+" ${OSPDEST}:  The destination to use for the call\n"
+" ${OSPCALLING}:  The calling number to use for the call\n"
+" ${OSPOUTTOKEN}:  The actual OSP token as a string\n"
+" ${OSPOUTTIMELIMIT}:  The outbound call duration limit in seconds\n"
+" ${OSPRESULTS}:  The number of OSP results total remaining\n"
+"\n"
+"The option string may contain the following character:\n"
+"      'j' -- jump to n+101 priority if the lookup was NOT successful\n"
+"This application sets the following channel variable upon completion:\n"
+"      OSPLOOKUPSTATUS The status of the OSP Lookup attempt as a text string, one of\n"
+"              SUCCESS | FAILED | ERROR\n";
+
+static const char* app3 = "OSPNext";
+static const char* synopsis3 = "Lookup next destination by OSP";
+static const char* descrip3 = 
+"  OSPNext(cause[|options]):  Looks up the next OSP Destination for ${OSPOUTHANDLE}\n"
+"See OSPLookup for more information\n"
+"\n"
+"The option string may contain the following character:\n"
+"      'j' -- jump to n+101 priority if the lookup was NOT successful\n"
+"This application sets the following channel variable upon completion:\n"
+"      OSPNEXTSTATUS   The status of the OSP Next attempt as a text string, one of\n"
+"              SUCCESS | FAILED |ERROR\n";
+
+static const char* app4 = "OSPFinish";
+static const char* synopsis4 = "Record OSP entry";
+static const char* descrip4 = 
+"  OSPFinish([status[|options]]):  Records call state for ${OSPINHANDLE}, according to\n"
+"status, which should be one of BUSY, CONGESTION, ANSWER, NOANSWER, or CHANUNAVAIL\n"
+"or coincidentally, just what the Dial application stores in its ${DIALSTATUS}.\n"
+"\n"
+"The option string may contain the following character:\n"
+"      'j' -- jump to n+101 priority if the finish attempt was NOT successful\n"
+"This application sets the following channel variable upon completion:\n"
+"      OSPFINISHSTATUS The status of the OSP Finish attempt as a text string, one of\n"
+"              SUCCESS | FAILED |ERROR \n";
+
+static const char osp_usage[] =
+"Usage: osp show\n"
+"       Displays information on Open Settlement Protocol support\n";
+
+static struct ast_cli_entry osp_cli = {
+       {"osp", "show", NULL}, 
+       osp_show, 
+       "Displays OSP information", 
+       osp_usage 
+};
+
+LOCAL_USER_DECL;
+
+static int load_module(void* mod)
 {
        int res;
        
-       ast_osp_adduse();
-
-       res = ast_register_application(app1, ospauth_exec, synopsis1, descrip1);
+       osp_load();
+       res = ast_cli_register(&osp_cli);
+       res |= ast_register_application(app1, ospauth_exec, synopsis1, descrip1);
        res |= ast_register_application(app2, osplookup_exec, synopsis2, descrip2);
        res |= ast_register_application(app3, ospnext_exec, synopsis3, descrip3);
        res |= ast_register_application(app4, ospfinished_exec, synopsis4, descrip4);
 
-       return(res);
+       return res;
 }
 
-static int unload_module(void *mod)
+static int unload_module(void* mod)
 {
        int res;
        
@@ -607,24 +1727,29 @@ static int unload_module(void *mod)
        res |= ast_unregister_application(app3);
        res |= ast_unregister_application(app2);
        res |= ast_unregister_application(app1);
+       res |= ast_cli_unregister(&osp_cli);
+       osp_unload();
 
        STANDARD_HANGUP_LOCALUSERS;
 
-       ast_osp_deluse();
+       return res;
+}
 
-       return(res);
+static int reload(void* mod)
+{
+       osp_unload();
+       osp_load();
+       return 0;
 }
 
-static const char *description(void)
+static const char* description(void)
 {
        return "Open Settlement Protocol Applications";
 }
 
-static const char *key(void)
+static const char* key(void)
 {
-       return(ASTERISK_GPL_KEY);
+       return ASTERISK_GPL_KEY;
 }
 
-STD_MOD1;
-
-
+STD_MOD(MOD_1, reload, NULL, NULL);
diff --git a/doc/osp.txt b/doc/osp.txt
new file mode 100644 (file)
index 0000000..465fcf1
--- /dev/null
@@ -0,0 +1,463 @@
+Asterisk OSP Module User Guide
+
+June 16, 2006
+
+Table of Contents
+1        Introduction
+2        OSP Toolkit
+2.1      Build OSP Toolkit
+2.1.1    Unpacking the Toolkit
+2.1.2    Preparing to build the OSP Toolkit
+2.1.3    Building the OSP Toolkit
+2.1.4    Installing the OSP Toolkit
+2.1.5    Building the Enrollment Utility
+2.2      Obtain Crypto Files
+3        Asterisk
+3.1      OSP Support Implementation
+3.1.1    OSPAuth
+3.1.2    OSPLookup
+3.1.3    OSPNext
+3.1.4    OSPFinish
+3.2      Build with OSP Support
+3.3      Configure with OSP Support
+3.3.1    osp.conf
+3.3.2    zapata/sip/iax.conf
+3.3.3    extensions.conf
+
+Asterisk is a trademark of Digium, Inc.
+TransNexus and OSP Secured are trademarks of TransNexus, Inc.
+
+1 Introduction
+  This document provides instructions on how to build and configure Asterisk 
+  V1.4 with the OSP Toolkit to enable secure, multi-lateral peering. The OSP 
+  Toolkit is an open source implementation of the OSP peering protocol and is 
+  freely available from www.sipfoundry.org.  The OSP standard defined by the 
+  European Telecommunications Standards Institute (ETSI TS 101 321) 
+  www.esti.org.  If you have questions or need help, building Asterisk with the
+  OSP Toolkit, please post your question on the OSP mailing list at 
+  https://list.sipfoundry.org/mailman/listinfo/osp. 
+
+2 OSP Toolkit
+  Please reference the OSP Toolkit document "How to Build and Test the OSP 
+  Toolkit" available from www.sipfoundry.org/OSP/OSPclient .  
+
+2.1 Build OSP Toolkit
+  The software listed below is required ti build and use the OSP Toolkit:
+  * OpenSSL (required for building) - Open Source SSL protocol and 
+  Cryptographic Algorithms (version 0.9.7g recommended) from www.openssl.org. 
+  Pre-compiled OpenSSL binary packages are not recommended because of the 
+  binary compatibility issue. 
+  * Perl (required for building) - A programming language used by OpenSSL for 
+  compilation. Any version of Perl should work. One version of Perl is 
+  available from www.activestate.com/ActivePerl. If pre-compiled OpenSSL 
+  packages are used, Perl package is not required.
+  * C compiler (required for building) - Any C compiler should work.  The GNU 
+  Compiler Collection from www.gnu.org is routinely used for building the OSP 
+  Toolkit for testing.
+  * OSP Server (required for testing) - Access to any OSP server should work.  
+  Open source OSP servers are available from www.sipfoundry.org/osp, a free 
+  commercial OSP server may be downloaded from www.transnexus.com and an OSP 
+  server osptestserver.transnexus.com is freely available on the internet for 
+  testing for testing. Please contact support@transnexus.com for testing access
+  to osptestserver.transnexus.com.
+
+2.1.1 Unpacking the Toolkit
+  After downloading the OSP Toolkit (version 3.3.4 or later release) from 
+  www.sipfoundry.org, perform the following steps in order:
+  1) Copy the OSP Toolkit distribution into the directory where it will reside,
+  say /usr/src. 
+  2) Un-package the distribution file by executing the following command: 
+    gunzip -c OSPToolkit-###.tar.gz | tar xvf -
+    Where ### is the version number separated by underlines. For example, if 
+    the version is 3.3.4, then the above command would be: 
+    gunzip -c OSPToolkit-3_3_4.tar.gz | tar xvf -
+  A new directory (TK-3_3_4-20051103) will be created within the same directory
+  as the tar file.
+  3) Go to the TK-3_3_4-20051103 directory by running this command:
+    cd TK-3_3_4-20051103
+  Within this directory, you will find directories and files similar to what is
+  listed below if the command "ls -F" is executed):
+    ls -F
+    enroll/
+    RelNotes.txt        lib/
+    README.txt          license.txt
+    bin/                src/
+    crypto/             test/
+    include/
+
+2.1.2 Preparing to build the OSP Toolkit
+  4) Compile OpenSSL according to the instructions provided with the OpenSSL 
+  distribution (You would need to do this only if you don't have openssl 
+  already).
+  5) Copy the OpenSSL header files (the *.h files) into the crypto/openssl 
+  directory within the osptoolkit directory. The OpenSSL header files are 
+  located under the openssl/include/openssl directory.
+  6) Copy the OpenSSL library files (libcrypto.a and libssl.a) into the lib 
+  directory within the osptoolkit directory. The OpenSSL library files are 
+  located under the openssl directory.
+  Note: Since the Asterisk requires the OpenSSL package. If the OpenSSL package
+  has been installed, 4~6 are not necessary.
+
+2.1.3 Building the OSP Toolkit
+  7) Optionally, change the install directory of the OSP Toolkit. Open the 
+  Makefile in the /usr/src/TK-3_3_4-20051103/src directory, look for the 
+  install path variable - INSTALL_PATH, and edit it to be anywhere you want 
+  (defaults /usr/local). 
+  Note: Please change the install path variable only if you are familiar with 
+  both the OSP Toolkit and the Asterisk. Otherwise, it may case that the 
+  Asterisk does not support the OSP protocol.
+  8) From within the OSP Toolkit directory (/usr/src/TK-3_3_4-20051103), start 
+  the compilation script by executing the following commands:
+    cd src
+    make clean; make build
+
+2.1.4 Installing the OSP Toolkit
+  The header files and the library of the OSP Toolkit should be installed. 
+  Otherwise, you must specify the OSP Toolkit path for the Asterisk.
+  9) Use the same script to install the Toolkit.
+    make install
+  The make script is also used to install the OSP Toolkit header files and the 
+  library into the INSTALL_PATH specified in the Makefile. 
+  Note: Please make sure you have the rights to access the INSTALL_PATH 
+  directory. For example, in order to access /usr/local directory, normally, 
+  you should be root.
+  By default, the OSP Toolkit is compiled in the production mode. The following
+  table identifies which default features are activated with each compile 
+  option:
+    Default Feature                Production    Development
+    Debug Information Displayed    No            Yes
+  The "Development" option is recommended for a first time build. The CFLAGS 
+  definition in the Makefile must be modified to build in development mode.  
+
+2.1.5 Building the Enrollment Utility
+  Device enrollment is the process of establishing a trusted cryptographic 
+  relationship between the VoIP device and the OSP Server. The Enroll program 
+  is a utility application for establishing a trusted relationship between and 
+  OSP client and an OSP server. Please see the document "Device Enrollment" at 
+  www.sipfoundry.org/OSP/OSPclient for more information about the enroll 
+  application.
+  10) From within the OSP Toolkit directory (/usr/src/TK-3_3_4-20051103), 
+  execute the following commands at the command prompt:
+    cd enroll
+    make clean; make linux
+  Compilation is successful if there are no errors anywhere in the compiler 
+  output. The enroll program is now located in the 
+  /usr/src/TK-3_3_4-20051103/bin directory. By this point, a fully functioning 
+  OSP Toolkit should have been successfully built.
+
+2.2 Obtain Crypto Files
+  The OSP module in Asterisk requires three crypto files containing local 
+  certificate (localcert.pem), private key (pkey.pem), and CA certificate 
+  (cacert_0.pem).  Asterisk will try to load the files from the Asterisk 
+  public/private key directory - /var/lib/asterisk/key.  If the files are not 
+  present, the OSP module will not start and the Asterisk will not support the 
+  OSP protocol.  Use the enroll.sh script from the toolkit distribution to 
+  enroll the Asterisk OSP module with an OSP server to obtain the crypto files.
+  Documentation explaining how to use the enroll.sh script (Device Enrollment) 
+  to enroll with an OSP server is available at 
+  www.sipfoundry.org/OSP/ospclient.  Copy the files file generated by the 
+  enrollment process to the Asterisk configuration directory.  
+  Note: The osptestserver.transnexus.com is configured only for sending and 
+  receiving non-SSL messages, and issuing signed tokens. If you need help, post
+  a message on the OSP mailing list of www.sipfoundry.org or send an e-mail to 
+  support@transnexus.com.
+  The enroll.sh script takes the domain name or IP addresses of the OSP servers
+  that the OSP Toolkit needs to enroll with as arguments, and then generates 
+  pem files - cacert_#.pem, certreq.pem, localcert.pem, and pkey.pem. The '#'
+  in the cacert file name is used to differentiate the ca certificate file 
+  names for the various SP's (OSP servers). If only one address is provided at 
+  the command line, cacert_0.pem will be generated. If 2 addresses are provided
+  at the command line, 2 files will be generated - cacert_0.pem and 
+  cacert_1.pem, one for each SP. The example below shows the usage when the 
+  client is registering with osptestserver.transnexus.com. If all goes well, 
+  the following text will be displayed. The gray boxes indicate required input.
+    ./enroll.sh osptestserver.transnexus.com
+    Generating a 512 bit RSA private key
+    ........................++++++++++++
+    .........++++++++++++
+    writing new private key to 'pkey.pem'
+    -----
+    You are about to be asked to enter information that will be incorporated
+    into your certificate request.
+    What you are about to enter is what is called a Distinguished Name or a DN.
+    There are quite a few fields but you can leave some blank
+    For some fields there will be a default value,
+    If you enter '.', the field will be left blank.
+    -----
+    Country Name (2 letter code) [AU]: _______
+    State or Province Name (full name) [Some-State]: _______
+    Locality Name (eg, city) []:_______
+    Organization Name (eg, company) [Internet Widgits Pty Ltd]: _______
+    Organizational Unit Name (eg, section) []:_______
+    Common Name (eg, YOUR name) []:_______
+    Email Address []:_______
+
+    Please enter the following 'extra' attributes
+    to be sent with your certificate request
+    A challenge password []:_______
+    An optional company name []:_______
+
+    Error Code returned from openssl command : 0
+
+    CA certificate received
+    [SP: osptestserver.transnexus.com]Error Code returned from getcacert command : 0
+
+    output buffer after operation: operation=request
+    output buffer after nonce: operation=request&nonce=1655976791184458
+    X509 CertInfo context is null pointer
+    Unable to get Local Certificate
+    depth=0 /CN=osptestserver.transnexus.com/O=OSPServer
+    verify error:num=18:self signed certificate
+    verify return:1
+    depth=0 /CN=osptestserver.transnexus.com/O=OSPServer
+    verify return:1
+    The certificate request was successful.
+    Error Code returned from localcert command : 0
+  The files generated should be copied to the /var/lib/asterisk/key 
+  directory. 
+  Note: The script enroll.sh requires AT&T korn shell (ksh) or any of its 
+  compatible variants. The /usr/src/TK-3_3_4-20051103/bin directory should be 
+  in the PATH variable. Otherwise, enroll.sh cannot find the enroll file.
+
+3 Asterisk
+
+3.1 OSP Support Implementation
+  In Asterisk, all OSP support is implemented as dial plan functions.
+
+3.1.1 OSPAuth 
+  OSP token validation function.
+  Input:
+  * OSPPEERIP: last hop IP address
+  * OSPINTOKEN: inbound OSP token
+  * provider: OSP service provider configured in osp.conf. If it is empty, 
+  default provider is used.
+  * priority jump
+  Output:
+  * OSPINHANDLE: inbound OSP transaction handle
+  * OSPINTIMELIMIT: inbound call duration limit
+  * OSPAUTHSTATUS: OSPAuth return value. SUCCESS/FAILED/ERROR
+
+3.1.2 OSPLookup
+  OSP lookup function.
+  Input:
+  * OSPPEERIP: last hop IP address
+  * OSPINHANDLE: inbound OSP transaction handle
+  * OSPINTIMELIMIT: inbound call duration limit 
+  * exten: called number
+  * provider: OSP service provider configured in osp.conf. If it is empty, 
+  default provider is used.
+  * priority jump
+  Output:
+  * OSPOUTHANDLE: outbound transaction handle
+  * OSPTECH: outbound protocol
+  * OSPDEST: outbound destination
+  * OSPCALLING: outbound calling number
+  * OSPOUTTOKEN: outbound OSP token
+  * OSPRESULTS: number of remain destinations
+  * OSPOUTTIMELIMIT: outbound call duration limit
+  * OSPLOOKUPSTATUS: OSPLookup return value. SUCCESS/FAILED/ERROR
+
+3.1.3 OSPNext
+  OSP lookup next function.
+  Input:
+  * OSPINHANDLE: inbound transaction handle
+  * OSPOUTHANDLE: outbound transaction handle
+  * OSPINTIMELIMIT: inbound call duration limit 
+  * OSPRESULTS: number of remain destinations
+  * cause: last destination disconnect cause
+  * priority jump
+  Output:
+  * OSPTECH: outbound protocol
+  * OSPDEST: outbound destination
+  * OSPCALLING: outbound calling number
+  * OSPOUTTOKEN: outbound OSP token
+  * OSPRESULTS: number of remain destinations
+  * OSPOUTTIMELIMIT: outbound call duration limit
+  * OSPNEXTSTATUS: OSPLookup return value. SUCCESS/FAILED/ERROR
+
+3.1.4 OSPFinish
+  OSP report usage function.
+  Input:
+  * OSPINHANDLE: inbound transaction handle
+  * OSPOUTHANDLE: outbound transaction handle
+  * OSPAUTHSTATUS: OSPAuth return value
+  * OSPLOOKUPTSTATUS: OSPLookup return value
+  * OSPNEXTSTATUS: OSPNext return value
+  * cause: last destination disconnect cause
+  * priority jump
+  Output:
+  * OSPFINISHSTATUS: OSPLookup return value. SUCCESS/FAILED/ERROR
+
+3.2 Build with OSP Support
+  If the OSP Toolkit is installed in the default install directory, /usr/local,
+  no additional configuration is required. If the OSP Toolkit is installed in 
+  another directory, say /myosp, Asterisk must be configured with the location 
+  of the OSP Toolkit.
+    --with-osptk=/myosp
+  Note: Please change the install path only if you familiar with both the OSP 
+  Toolkit and the Asterisk. Otherwise, the change may results Asterisk not 
+  supporting the OSP protocol.
+  Now, you can compile Asterisk according to the instructions provided with the
+  Asterisk distribution.
+
+3.3 Configure with OSP Support
+
+3.3.1 osp.conf
+  ;
+  ; Open Settlement Protocol Sample Configuration File
+  ;
+  ; This file contains configuration of providers that
+  ; are used by the OSP subsystem of Asterisk.  The section
+  ; "general" is reserved for global options.  Each other 
+  ; section declares an OSP Provider.  The provider "default"
+  ; is used when no provider is otherwise specified.
+  ;
+  [general]
+  ;
+  ; Should hardware accelleration be enabled?  May not be changed
+  ; on a reload.
+  ;
+  accelerate=no
+  ;
+  ; Defines the token format that Asterisk can validate. 
+  ; 0 - signed tokens only 
+  ; 1 - unsigned tokens only 
+  ; 2 - both signed and unsigned
+  ; The defaults to 0, i.e. the Asterisk can validate signed tokens only.
+  ;
+  tokenformat=0
+  ;
+  [default]
+  ;
+  ; All paths are presumed to be under /var/lib/asterisk/keys unless
+  ; the path begins with '/'
+  ;
+  ; Specify the private keyfile.  If unspecified, defaults to the name
+  ; of the section followed by "-privatekey.pem" (e.g. default-privatekey.pem)
+  ;
+  privatekey=pkey.pem
+  ;
+  ; Specify the local certificate file.  If unspecified, defaults to
+  ; the name of the section followed by "-localcert.pem"
+  ;
+  localcert=localcert.pem
+  ;
+  ; Specify one or more Certificate Authority keys.  If none are listed,
+  ; a single one is added with the name "-cacert.pem"
+  ;
+  cacert=cacert_0.pem
+  ;
+  ; Specific parameters can be tuned as well:
+  ;
+  ; maxconnections: Max number of simultaneous connections to the provider (default=20)
+  ; retrydelay:     Extra delay between retries (default=0)
+  ; retrylimit:     Max number of retries before giving up (default=2)
+  ; timeout:        Timeout for response in milliseconds (default=500)
+  ;
+  maxconnections=20
+  retrydelay=0
+  retrylimit=2
+  timeout=500
+  ;
+  ; List all service points for this provider
+  ;
+  ;servicepoint=http://osptestserver.transnexus.com:1080/osp
+  servicepoint=http://OSP server IP:1080/osp
+  ;
+  ; Set the "source" for requesting authorization
+  ;
+  ;source=foo
+  source=[host IP]
+  ;
+  ; Set the authentication policy.  
+  ; 0 - NO 
+  ; 1 - YES
+  ; 2 - EXCLUSIVE
+  ; Default is 1, validate token but allow no token.
+  ;
+  authpolicy=1
+
+3.3.2 zapata/sip/iax.conf
+  There is no configuration required for OSP.
+
+3.3.3 extensions.conf
+  An Asterisk box can be configured as OSP source/destination gateway or OSP proxy.
+
+3.3.3.1 OSP Source Gateway
+  [PhoneSrcGW]
+  ; Set calling number if necessary
+  exten => _XXXX.,1,Set(CALLERID(numner)=CallingNumber)
+  ; OSP lookup using default provider, if fail/error jump to 2+101
+  exten => _XXXX.,2,OSPLookup(${EXTEN}||j)
+  ; Set calling number which may be translated 
+  exten => _XXXX.,3,Set(CALLERID(number)=${OSPCALLING})
+  ; Dial to destination, 60 timeout, with call duration limit
+  exten => _XXXX.,4,Dial(${OSPTECH}/${OSPDEST},60,oL($[${OSPOUTTIMELIMIT}*1000]))
+  ; Wait 3 seconds
+  exten => _XXXX.,5,Wait,3
+  ; Hangup
+  exten => _XXXX.,6,Hangup
+  ; Deal with OSPLookup fail/error
+  exten => _XXXX.,2+101,Hangup
+  ; OSP report usage
+  exten => h,1,OSPFinish(${HANGUPCAUSE})
+  3.3.3.2 OSP Destination Gateway
+  [PhoneDstGW]
+  ; Get peer IP
+  exten => _XXXX.,1,Set(OSPPEERIP=${SIPCHANINFO(peerip)})
+  ; Get OSP token
+  exten => _XXXX.,2,Set(OSPINTOKEN=${SIP_HEADER(P-OSP-Auth-Token)})
+  ; Validate token using default provider, if fail/error jump to 3+101
+  exten => _XXXX.,3,OSPAuth(|j)
+  ; Ringing
+  exten => _XXXX.,4,Ringing
+  ; Wait 1 second
+  exten => _XXXX.,5,Wait,1
+  ; Dial phone, timeout 15 seconds, with call duration limit
+  exten => _XXXX.,6,Dial(${DIALOUTANALOG}/${EXTEN:1},15,oL($[${OSPINTIMELIMIT}*1000]))
+  ; Wait 3 seconds
+  exten => _XXXX.,7,Wait,3
+  ; Hangup
+  exten => _XXXX.,8,Hangup
+  ; Deal with OSPAuth fail/error
+  exten => _XXXX.,3+101,Hangup
+  ; OSP report usage
+  exten => h,1,OSPFinish(${HANGUPCAUSE})
+  3.3.3.3 Proxy
+  [GeneralProxy]
+  ; Get peer IP
+  exten => _XXXX.,1,Set(OSPPEERIP=${SIPCHANINFO(peerip)})
+  ; Get OSP token
+  exten => _XXXX.,2,Set(OSPINTOKEN=${SIP_HEADER(P-OSP-Auth-Token)})
+  ; Validate token using default provider, if fail/error jump to 3+101
+  exten => _XXXX.,3,OSPAuth(|j)
+  ; OSP lookup using default provider, if fail/error jump to 4+101
+  exten => _XXXX.,4,OSPLookup(${EXTEN}||j)
+  ; Set calling number which may be translated 
+  exten => _XXXX.,5,Set(CALLERID(number)=${OSPCALLING})
+  ; Dial to 1st destination, 60 timeout, with call duration limit
+  exten => _XXXX.,6,Dial(${OSPTECH}/${OSPDEST},24,oL($[${OSPOUTTIMELIMIT}*1000]))
+  ; OSP lookup next, if fail/error jump to 7+101
+  exten => _XXXX.,7,OSPNext(${HANGUPCAUSE}||j)
+  ; Set calling number which may be translated 
+  exten => _XXXX.,8,Set(CALLERID(number)=${OSPCALLING})
+  ; Dial to 2nd destination, 60 timeout, with call duration limit
+  exten => _XXXX.,9,Dial(${OSPTECH}/${OSPDEST},25,oL($[${OSPOUTTIMELIMIT}*1000]))
+  ; OSP lookup next, if fail/error jump to 10+101
+  exten => _XXXX.,10,OSPNext(${HANGUPCAUSE}||j)
+  ; Set calling number which may be translated 
+  exten => _XXXX.,11,Set(CALLERID(number)=${OSPCALLING})
+  ; Dial to 3rd destination, 60 timeout, with call duration limit
+  exten => _XXXX.,12,Dial(${OSPTECH}/${OSPDEST},26,oL($[${OSPOUTTIMELIMIT}*1000]))
+  ; Hangup
+  exten => _XXXX.,13,Hangup
+  ; Deal with OSPAuth fail/error
+  exten => _XXXX.,3+101,Hangup
+  ; Deal with OSPLookup fail/error
+  exten => _XXXX.,4+101,Hangup
+  ; Deal with 1st OSPNext fail/error
+  exten => _XXXX.,7+101,Hangup
+  ; Deal with 2nd OSPNext fail/error
+  exten => _XXXX.,10+101,Hangup
+  ; OSP report usage
+  exten => h,1,OSPFinish(${HANGUPCAUSE})
index 6861dca..75ee76f 100644 (file)
 
 /*! 
  * \file
- * \brief OSP support (Open Settlement Protocol)
+ * \brief Open Settlement Protocol (OSP)
  */
 
 #ifndef _ASTERISK_OSP_H
 #define _ASTERISK_OSP_H
 
-#include <time.h>
-#include <netinet/in.h>
-
-#include "asterisk/channel.h"
-
-#define OSP_DEF_PROVIDER       ((char*)"default")              /* Default provider context name */
-#define OSP_INVALID_HANDLE     ((int)-1)                               /* Invalid OSP handle, provider, transaction etc. */
-#define OSP_DEF_TIMELIMIT      ((unsigned int)0)               /* Default duration limit, no limit */
-
-#define OSP_INTSTR_SIZE                ((unsigned int)16)              /* Signed/unsigned int string buffer size */
-#define OSP_NORSTR_SIZE                ((unsigned int)256)             /* Normal string buffer size */
-#define OSP_TOKSTR_SIZE                ((unsigned int)4096)    /* Token string buffer size */
-
-#define OSP_APP_SUCCESS                ((char*)"SUCCESS")              /* Return status, success */
-#define OSP_APP_FAILED         ((char*)"FAILED")               /* Return status, failed */
-#define OSP_APP_ERROR          ((char*)"ERROR")                /* Return status, error */
-
-struct ast_osp_result {
-       int inhandle;
-       int outhandle;
-       unsigned int intimelimit;
-       unsigned int outtimelimit;
-       char tech[20];
-       char dest[OSP_NORSTR_SIZE];
-       char calling[OSP_NORSTR_SIZE];
-       char token[OSP_TOKSTR_SIZE];
-       int numresults;
-};
-
-/*!
- * \brief OSP Increase Use Count function
- */
-void ast_osp_adduse(void);
-/*!
- * \brief OSP Decrease Use Count function
- */
-void ast_osp_deluse(void);
-/*!
- * \brief OSP Authentication function
- * \param provider OSP provider context name
- * \param transaction OSP transaction handle, output
- * \param source Source of in_bound call
- * \param calling Calling number
- * \param called Called number
- * \param token OSP token, may be empty
- * \param timelimit Call duration limit, output
- * \return 1 Authenricated, 0 Unauthenticated, -1 Error
- */
-int ast_osp_auth(
-       const char* provider,           /* OSP provider context name */
-       int* transaction,                       /* OSP transaction handle, output */
-       const char* source,                     /* Source of in_bound call */
-       const char* calling,            /* Calling number */
-       const char* called,                     /* Called number */
-       const char* token,                      /* OSP token, may be empty */
-       unsigned int* timelimit         /* Call duration limit, output */
-);
-/*!
- * \brief OSP Lookup function
- * \param provider OSP provider context name
- * \param srcdev Source device of out_bound call
- * \param calling Calling number
- * \param called Called number
- * \param result Lookup results
- * \return 1 Found , 0 No route, -1 Error
- */
-int ast_osp_lookup(
-       const char* provider,                   /* OSP provider conttext name */
-       const char* srcdev,                             /* Source device of out_bound call */
-       const char* calling,                    /* Calling number */
-       const char* called,                             /* Called number */
-       struct ast_osp_result* result   /* OSP lookup results, in/output */
-);
-/*!
- * \brief OSP Next function
- * \param reason Last destination failure reason
- * \param result Lookup results, in/output
- * \return 1 Found , 0 No route, -1 Error
- */
-int ast_osp_next(
-       int reason,                                             /* Last destination failure reason */
-       struct ast_osp_result *result   /* OSP lookup results, in/output */
-);
-/*!
- * \brief OSP Finish function
- * \param handle OSP in/out_bound transaction handle
- * \param reason Last destination failure reason
- * \param start Call start time
- * \param connect Call connect time
- * \param end Call end time
- * \return 1 Success, 0 Failed, -1 Error
- */
-int ast_osp_finish(
-       int handle,                                             /* OSP in/out_bound transaction handle */
-       int reason,                                             /* Last destination failure reason */
-       time_t start,                                   /* Call start time */
-       time_t connect,                                 /* Call connect time */
-       time_t end                                              /* Call end time */
-);
+#define AST_OSP_SUCCESS                ((char*)"SUCCESS")              /* Return status, success */
+#define AST_OSP_FAILED         ((char*)"FAILED")               /* Return status, failed */
+#define AST_OSP_ERROR          ((char*)"ERROR")                /* Return status, error */
 
 #endif /* _ASTERISK_OSP_H */
diff --git a/res/res_osp.c b/res/res_osp.c
deleted file mode 100644 (file)
index 62115db..0000000
+++ /dev/null
@@ -1,1114 +0,0 @@
-/*
- * Asterisk -- An open source telephony toolkit.
- *
- * Copyright (C) 1999 - 2006, Digium, Inc.
- *
- * Mark Spencer <markster@digium.com>
- *
- * See http://www.asterisk.org for more information about
- * the Asterisk project. Please do not directly contact
- * any of the maintainers of this project for assistance;
- * the project provides a web site, mailing lists and IRC
- * channels for your use.
- *
- * This program is free software, distributed under the terms of
- * the GNU General Public License Version 2. See the LICENSE file
- * at the top of the source tree.
- */
-
-/*! 
- * \file
- * \brief Provide Open Settlement Protocol capability
- *
- * \author Mark Spencer <markster@digium.com>
- *
- * \arg See also: \ref app_osplookup.c
- */
-
-/*** MODULEINFO
-       <depend>libosptk</depend>
-       <depend>ssl</depend>
- ***/
-
-#include "asterisk.h"
-
-ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
-
-#include <sys/types.h>
-#include <osp/osp.h>
-#include <osp/osputils.h>
-#include <openssl/err.h>
-#include <stdio.h>
-#include <dirent.h>
-#include <string.h>
-#include <errno.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <openssl/bio.h>
-#include <openssl/pem.h>
-#include <openssl/evp.h>
-
-#include "asterisk/file.h"
-#include "asterisk/channel.h"
-#include "asterisk/logger.h"
-#include "asterisk/say.h"
-#include "asterisk/module.h"
-#include "asterisk/options.h"
-#include "asterisk/crypto.h"
-#include "asterisk/md5.h"
-#include "asterisk/cli.h"
-#include "asterisk/io.h"
-#include "asterisk/lock.h"
-#include "asterisk/astosp.h"
-#include "asterisk/config.h"
-#include "asterisk/utils.h"
-#include "asterisk/lock.h"
-#include "asterisk/causes.h"
-#include "asterisk/callerid.h"
-#include "asterisk/pbx.h"
-
-/* OSP Authentication Policy */
-enum osp_authpolicy {
-       OSP_AUTH_NO,
-       OSP_AUTH_YES,
-       OSP_AUTH_EXCLUSIVE
-};
-
-#define OSP_CONFIG_FILE                        ((char*)"osp.conf")
-#define OSP_GENERAL_CAT                        ((char*)"general")
-#define OSP_MAX_CERTS                  ((unsigned int)10)
-#define OSP_MAX_SRVS                   ((unsigned int)10)
-#define OSP_DEF_MAXCONNECTIONS ((unsigned int)20)
-#define OSP_MIN_MAXCONNECTIONS ((unsigned int)1)
-#define OSP_MAX_MAXCONNECTIONS ((unsigned int)1000)
-#define OSP_DEF_RETRYDELAY             ((unsigned int)0)
-#define OSP_MIN_RETRYDELAY             ((unsigned int)0)
-#define OSP_MAX_RETRYDELAY             ((unsigned int)10)
-#define OSP_DEF_RETRYLIMIT             ((unsigned int)2)
-#define OSP_MIN_RETRYLIMIT             ((unsigned int)0)
-#define OSP_MAX_RETRYLIMIT             ((unsigned int)100)
-#define OSP_DEF_TIMEOUT                        ((unsigned int)500)
-#define OSP_MIN_TIMEOUT                        ((unsigned int)200)
-#define OSP_MAX_TIMEOUT                        ((unsigned int)10000)
-#define OSP_DEF_AUTHPOLICY             ((enum osp_authpolicy)OSP_AUTH_YES)
-#define OSP_AUDIT_URL                  ((char*)"localhost")
-#define OSP_LOCAL_VALIDATION   ((int)1)
-#define OSP_SSL_LIFETIME               ((unsigned int)300)
-#define OSP_HTTP_PERSISTENCE   ((int)1)
-#define OSP_CUSTOMER_ID                        ((char*)"")
-#define OSP_DEVICE_ID                  ((char*)"")
-#define OSP_DEF_DESTINATIONS   ((unsigned int)5)
-
-struct osp_provider {
-       char name[OSP_NORSTR_SIZE];
-       char privatekey[OSP_NORSTR_SIZE];
-       char localcert[OSP_NORSTR_SIZE];
-       unsigned int cacount;
-       char cacerts[OSP_MAX_CERTS][OSP_NORSTR_SIZE]; 
-       unsigned int spcount;
-       char srvpoints[OSP_MAX_SRVS][OSP_NORSTR_SIZE];
-       int maxconnections;
-       int retrydelay;
-       int retrylimit;
-       int timeout;
-       char source[OSP_NORSTR_SIZE];
-       enum osp_authpolicy authpolicy;
-       OSPTPROVHANDLE handle;
-       struct osp_provider *next;
-};
-
-AST_MUTEX_DEFINE_STATIC(osplock);
-static unsigned int osp_usecount = 0;
-static int osp_initialized = 0;
-static int osp_hardware = 0;
-static struct osp_provider* ospproviders = NULL;
-static unsigned int osp_tokenformat = TOKEN_ALGO_SIGNED;
-
-static int osp_buildProvider(
-       struct ast_config* cfg,         /* OSP configuration */
-       char* provider);                        /* OSP provider context name */
-static int osp_getPolicy(
-       const char* provider,           /* OSP provider context name */
-       int* policy);                           /* OSP authentication policy, output */
-static int osp_genTransaction(
-       const char* provider,           /* OSP provider context name */
-       int* transaction,                       /* OSP transaction handle, output */
-       unsigned int sourcesize,        /* Size of source buffer, in/output */
-       char* source);                          /* Source of provider context, output */
-static int osp_valToken(
-       int transaction,                        /* OSP transaction handle */
-       const char* source,                     /* Source of in_bound call */
-       const char* dest,                       /* Destination of in_bound call */
-       const char* calling,            /* Calling number */
-       const char* called,                     /* Called number */
-       const char* token,                      /* OSP token, may be empty */
-       unsigned int* timelimit);       /* Call duration limit, output */
-static unsigned int osp_choTimelimit(
-       unsigned int in,                        /* In_bound OSP timelimit */
-       unsigned int out);                      /* Out_bound OSP timelimit */
-static enum OSPEFAILREASON reason2cause(
-       int reason);                            /* Last call failure reason */
-static int osp_chkDest(
-       const char* callednum,                  /* Called number */
-       const char* callingnum,                 /* Calling number */
-       char* destination,                              /* Destination IP in OSP format */
-       unsigned int tokenlen,                  /* OSP token length */
-       const char* token,                              /* OSP token */
-       enum OSPEFAILREASON* cause,             /* Failure cause, output */
-       struct ast_osp_result* result); /* OSP lookup results, in/output */
-
-static int osp_load(void);
-static int osp_unload(void);
-static int osp_show(int fd, int argc, char *argv[]);
-
-static int osp_buildProvider(
-       struct ast_config *cfg,         /* OSP configuration */
-       char* provider)                         /* OSP provider context name */
-{
-       int res;
-       unsigned int t, i, j;
-       struct osp_provider* p;
-       struct ast_variable* v;
-       OSPTPRIVATEKEY privatekey;
-       OSPTCERT localcert;
-       const char* psrvpoints[OSP_MAX_SRVS];
-       OSPTCERT cacerts[OSP_MAX_CERTS];
-       const OSPTCERT* pcacerts[OSP_MAX_CERTS];
-       int error = OSPC_ERR_NO_ERROR;
-
-       p = ast_calloc(1, sizeof(*p));
-       if (!p) {
-               return(-1);
-       }
-
-       ast_copy_string(p->name, provider, sizeof(p->name));
-       p->handle = OSP_INVALID_HANDLE;
-       snprintf(p->privatekey, sizeof(p->privatekey), "%s/%s-privatekey.pem", ast_config_AST_KEY_DIR, provider);
-       snprintf(p->localcert, sizeof(p->localcert), "%s/%s-localcert.pem", ast_config_AST_KEY_DIR, provider);
-       p->maxconnections = OSP_DEF_MAXCONNECTIONS;
-       p->retrydelay = OSP_DEF_RETRYDELAY;
-       p->retrylimit = OSP_DEF_RETRYLIMIT;
-       p->timeout = OSP_DEF_TIMEOUT;
-       p->authpolicy = OSP_DEF_AUTHPOLICY;
-
-       v = ast_variable_browse(cfg, provider);
-       while(v) {
-               if (!strcasecmp(v->name, "privatekey")) {
-                       if (v->value[0] == '/') {
-                               ast_copy_string(p->privatekey, v->value, sizeof(p->privatekey));
-                       } else {
-                               snprintf(p->privatekey, sizeof(p->privatekey), "%s/%s", ast_config_AST_KEY_DIR, v->value);
-                       }
-                       ast_log(LOG_DEBUG, "OSP: privatekey '%s'\n", p->privatekey);
-               } else if (!strcasecmp(v->name, "localcert")) {
-                       if (v->value[0] == '/') {
-                               ast_copy_string(p->localcert, v->value, sizeof(p->localcert));
-                       } else {
-                               snprintf(p->localcert, sizeof(p->localcert), "%s/%s", ast_config_AST_KEY_DIR, v->value);
-                       }
-                       ast_log(LOG_DEBUG, "OSP: localcert '%s'\n", p->localcert);
-               } else if (!strcasecmp(v->name, "cacert")) {
-                       if (p->cacount < OSP_MAX_CERTS) {
-                               if (v->value[0] == '/') {
-                                       ast_copy_string(p->cacerts[p->cacount], v->value, sizeof(p->cacerts[0]));
-                               } else {
-                                       snprintf(p->cacerts[p->cacount], sizeof(p->cacerts[0]), "%s/%s", ast_config_AST_KEY_DIR, v->value);
-                               }
-                               ast_log(LOG_DEBUG, "OSP: cacert[%d]: '%s'\n", p->cacount, p->cacerts[p->cacount]);
-                               p->cacount++;
-                       } else {
-                               ast_log(LOG_WARNING, "OSP: Too many CA Certificates at line %d\n", v->lineno);
-                       }
-               } else if (!strcasecmp(v->name, "servicepoint")) {
-                       if (p->spcount < OSP_MAX_SRVS) {
-                               ast_copy_string(p->srvpoints[p->spcount], v->value, sizeof(p->srvpoints[0]));
-                               ast_log(LOG_DEBUG, "OSP: servicepoint[%d]: '%s'\n", p->spcount, p->srvpoints[p->spcount]);
-                               p->spcount++;
-                       } else {
-                               ast_log(LOG_WARNING, "OSP: Too many Service Points at line %d\n", v->lineno);
-                       }
-               } else if (!strcasecmp(v->name, "maxconnections")) {
-                       if ((sscanf(v->value, "%d", &t) == 1) && (t >= OSP_MIN_MAXCONNECTIONS) && (t <= OSP_MAX_MAXCONNECTIONS)) {
-                               p->maxconnections = t;
-                               ast_log(LOG_DEBUG, "OSP: maxconnections '%d'\n", t);
-                       } else {
-                               ast_log(LOG_WARNING, "OSP: maxconnections should be an integer from %d to %d, not '%s' at line %d\n", 
-                                       OSP_MIN_MAXCONNECTIONS, OSP_MAX_MAXCONNECTIONS, v->value, v->lineno);
-                       }
-               } else if (!strcasecmp(v->name, "retrydelay")) {
-                       if ((sscanf(v->value, "%d", &t) == 1) && (t >= OSP_MIN_RETRYDELAY) && (t <= OSP_MAX_RETRYDELAY)) {
-                               p->retrydelay = t;
-                               ast_log(LOG_DEBUG, "OSP: retrydelay '%d'\n", t);
-                       } else {
-                               ast_log(LOG_WARNING, "OSP: retrydelay should be an integer from %d to %d, not '%s' at line %d\n", 
-                                       OSP_MIN_RETRYDELAY, OSP_MAX_RETRYDELAY, v->value, v->lineno);
-                       }
-               } else if (!strcasecmp(v->name, "retrylimit")) {
-                       if ((sscanf(v->value, "%d", &t) == 1) && (t >= OSP_MIN_RETRYLIMIT) && (t <= OSP_MAX_RETRYLIMIT)) {
-                               p->retrylimit = t;
-                               ast_log(LOG_DEBUG, "OSP: retrylimit '%d'\n", t);
-                       } else {
-                               ast_log(LOG_WARNING, "OSP: retrylimit should be an integer from %d to %d, not '%s' at line %d\n", 
-                                       OSP_MIN_RETRYLIMIT, OSP_MAX_RETRYLIMIT, v->value, v->lineno);
-                       }
-               } else if (!strcasecmp(v->name, "timeout")) {
-                       if ((sscanf(v->value, "%d", &t) == 1) && (t >= OSP_MIN_TIMEOUT) && (t <= OSP_MAX_TIMEOUT)) {
-                               p->timeout = t;
-                               ast_log(LOG_DEBUG, "OSP: timeout '%d'\n", t);
-                       } else {
-                               ast_log(LOG_WARNING, "OSP: timeout should be an integer from %d to %d, not '%s' at line %d\n", 
-                                       OSP_MIN_TIMEOUT, OSP_MAX_TIMEOUT, v->value, v->lineno);
-                       }
-               } else if (!strcasecmp(v->name, "source")) {
-                       ast_copy_string(p->source, v->value, sizeof(p->source));
-                       ast_log(LOG_DEBUG, "OSP: source '%s'\n", p->source);
-               } else if (!strcasecmp(v->name, "authpolicy")) {
-                       if ((sscanf(v->value, "%d", &t) == 1) && ((t == OSP_AUTH_NO) || (t == OSP_AUTH_YES) || (t == OSP_AUTH_EXCLUSIVE))) {
-                               p->authpolicy = t;
-                               ast_log(LOG_DEBUG, "OSP: authpolicy '%d'\n", t);
-                       } else {
-                               ast_log(LOG_WARNING, "OSP: authpolicy should be %d, %d or %d, not '%s' at line %d\n", 
-                                       OSP_AUTH_NO, OSP_AUTH_YES, OSP_AUTH_EXCLUSIVE, v->value, v->lineno);
-                       }
-               }
-               v = v->next;
-       }
-
-       error = OSPPUtilLoadPEMPrivateKey(p->privatekey, &privatekey);
-       if (error != OSPC_ERR_NO_ERROR) {
-               ast_log(LOG_WARNING, "OSP: Unable to load privatekey '%s'\n", p->privatekey);
-               free(p);
-               return(-1);
-       }
-
-       error = OSPPUtilLoadPEMCert(p->localcert, &localcert);
-       if (error != OSPC_ERR_NO_ERROR) {
-               ast_log(LOG_WARNING, "OSP: Unable to load localcert '%s'\n", p->localcert);
-               if (privatekey.PrivateKeyData) {
-                       free(privatekey.PrivateKeyData);
-               }
-               free(p);
-               return(-1);
-       }
-
-       if (p->cacount < 1) {
-               snprintf(p->cacerts[p->cacount], sizeof(p->cacerts[0]), "%s/%s-cacert.pem", ast_config_AST_KEY_DIR, provider);
-               ast_log(LOG_DEBUG, "OSP: cacert[%d]: '%s'\n", p->cacount, p->cacerts[p->cacount]);
-               p->cacount++;
-       }
-       for (i = 0; i < p->cacount; i++) {
-               error = OSPPUtilLoadPEMCert(p->cacerts[i], &cacerts[i]);
-               if (error != OSPC_ERR_NO_ERROR) {
-                       ast_log(LOG_WARNING, "OSP: Unable to load cacert '%s'\n", p->cacerts[i]);
-                       for (j = 0; j < i; j++) {
-                               if (cacerts[j].CertData) {
-                                       free(cacerts[j].CertData);
-                               }
-                       }
-                       if (localcert.CertData) {
-                               free(localcert.CertData);
-                       }
-                       if (privatekey.PrivateKeyData) {
-                               free(privatekey.PrivateKeyData);
-                       }
-                       free(p);
-                       return(-1);
-               }
-               pcacerts[i] = &cacerts[i];
-       }
-       
-       for (i = 0; i < p->spcount; i++) {
-               psrvpoints[i] = p->srvpoints[i];
-       }
-
-       error = OSPPProviderNew(
-               p->spcount, psrvpoints,
-               NULL,
-               OSP_AUDIT_URL,
-               &privatekey,
-               &localcert,
-               p->cacount, pcacerts,
-               OSP_LOCAL_VALIDATION,
-               OSP_SSL_LIFETIME,
-               p->maxconnections,
-               OSP_HTTP_PERSISTENCE,
-               p->retrydelay,
-               p->retrylimit,
-               p->timeout,
-               OSP_CUSTOMER_ID,
-               OSP_DEVICE_ID,
-               &p->handle);
-       if (error != OSPC_ERR_NO_ERROR) {
-               ast_log(LOG_WARNING, "OSP: Unable to initialize provider '%s'\n", provider);
-               free(p);
-               res = -1;
-       } else {
-               ast_log(LOG_DEBUG, "OSP: provider '%s'\n", provider);
-               ast_mutex_lock(&osplock);
-               p->next = ospproviders;
-               ospproviders = p;
-               ast_mutex_unlock(&osplock);     
-               res = 0;
-       }
-
-       for (i = 0; i < p->cacount; i++) {
-               if (cacerts[i].CertData) {
-                       free(cacerts[i].CertData);
-               }
-       }
-       if (localcert.CertData) {
-               free(localcert.CertData);
-       }
-       if (privatekey.PrivateKeyData) {
-               free(privatekey.PrivateKeyData);
-       }
-
-       return(res);
-}
-
-static int osp_getPolicy(
-       const char* provider,           /* OSP provider context name */
-       int* policy)                            /* OSP authentication policy, output */
-{
-       int res = 0;
-       struct osp_provider* p;
-
-       ast_mutex_lock(&osplock);
-       p = ospproviders;
-       while(p) {
-               if (!strcasecmp(p->name, provider)) {
-                       *policy = p->authpolicy;
-                       ast_log(LOG_DEBUG, "OSP: authpolicy '%d'\n", *policy);
-                       res = 1;
-                       break;
-               }
-               p = p->next;
-       }
-       ast_mutex_unlock(&osplock);
-
-       return(res);
-}
-
-static int osp_genTransaction(
-       const char* provider,           /* OSP provider context name */
-       int* transaction,                       /* OSP transaction handle, output */
-       unsigned int sourcesize,        /* Size of source buffer, in/output */
-       char* source)                           /* Source of provider context, output */
-{
-       int res = 0;
-       struct osp_provider *p;
-       int error;
-
-       ast_mutex_lock(&osplock);
-       p = ospproviders;
-       while(p) {
-               if (!strcasecmp(p->name, provider)) {
-                       error = OSPPTransactionNew(p->handle, transaction);
-                       if (error == OSPC_ERR_NO_ERROR) {
-                               ast_log(LOG_DEBUG, "OSP: transaction '%d'\n", *transaction);
-                               ast_copy_string(source, p->source, sourcesize);
-                               ast_log(LOG_DEBUG, "OSP: source '%s'\n", source);
-                               res = 1;
-                       } else {
-                               *transaction = OSP_INVALID_HANDLE;
-                               ast_log(LOG_WARNING, "OSP: Unable to create transaction handle\n");
-                               res = -1;
-                       }
-                       break;
-               }
-               p = p->next;
-       }
-       ast_mutex_unlock(&osplock);
-
-       return(res);
-}
-
-static int osp_valToken(
-       int transaction,                        /* OSP transaction handle */
-       const char* source,                     /* Source of in_bound call */
-       const char* dest,                       /* Destination of in_bound call */
-       const char* calling,            /* Calling number */
-       const char* called,                     /* Called number */
-       const char* token,                      /* OSP token, may be empty */
-       unsigned int* timelimit)        /* Call duration limit, output */
-{
-       int res = 0;
-       char tokenstr[OSP_TOKSTR_SIZE];
-       int tokenlen;
-       unsigned int authorised;
-       unsigned int dummy = 0;
-       int error;
-
-       tokenlen = ast_base64decode(tokenstr, token, strlen(token));
-       error = OSPPTransactionValidateAuthorisation(
-               transaction, 
-               source, dest, NULL, NULL,
-               calling ? calling : "", OSPC_E164, 
-               called, OSPC_E164, 
-               0, NULL,
-               tokenlen, tokenstr, 
-               &authorised, 
-               timelimit, 
-               &dummy, NULL, 
-               osp_tokenformat); 
-       if (error == OSPC_ERR_NO_ERROR) {
-               if (authorised) {
-                       ast_log(LOG_DEBUG, "OSP: Authorised\n");
-                       res = 1;
-               }
-       }
-       return(res);
-}
-
-int ast_osp_auth(
-       const char* provider,           /* OSP provider context name */
-       int* transaction,                       /* OSP transaction handle, output */
-       const char* source,                     /* Source of in_bound call */
-       const char* calling,            /* Calling number */
-       const char* called,                     /* Called number */
-       const char* token,                      /* OSP token, may be empty */
-       unsigned int* timelimit)        /* Call duration limit, output */
-{
-       int res;
-       char dest[OSP_NORSTR_SIZE];
-       int policy = OSP_AUTH_YES;
-
-       *transaction = OSP_INVALID_HANDLE;
-       *timelimit = OSP_DEF_TIMELIMIT;
-
-       res = osp_getPolicy(provider, &policy);
-       if (!res) {
-               ast_log(LOG_WARNING, "OSP: Unabe to find authentication policy\n");
-               return(-1);
-       }
-
-       switch (policy) {
-               case OSP_AUTH_NO:
-                       res = 1;
-                       break;
-               case OSP_AUTH_EXCLUSIVE:
-                       if (ast_strlen_zero(token)) {
-                               res = 0;
-                       } else if ((res = osp_genTransaction(provider, transaction, sizeof(dest), dest)) <= 0) {
-                               *transaction = OSP_INVALID_HANDLE;
-                               ast_log(LOG_WARNING, "OSP: Unable to generate transaction handle\n");
-                               res = -1;
-                       } else {
-                               res = osp_valToken(*transaction, source, dest, calling, called, token, timelimit);
-                       }
-                       break;
-               case OSP_AUTH_YES:
-               default:
-                       if (ast_strlen_zero(token)) {
-                               res = 1;
-                       } else if ((res = osp_genTransaction(provider, transaction, sizeof(dest), dest)) <= 0) {
-                               *transaction = OSP_INVALID_HANDLE;
-                               ast_log(LOG_WARNING, "OSP: Unable to generate transaction handle\n");
-                               res = -1;
-                       } else {
-                               res = osp_valToken(*transaction, source, dest, calling, called, token, timelimit);
-                       }
-                       break;
-       }
-
-       if (!res) {
-               OSPPTransactionRecordFailure(*transaction, OSPC_FAIL_CALL_REJECTED);
-       }
-
-       return(res);    
-}
-
-static unsigned int osp_choTimelimit(
-       unsigned int in,                        /* In_bound OSP timelimit */
-       unsigned int out)                       /* Out_bound OSP timelimit */
-{
-       if (in == OSP_DEF_TIMELIMIT) {
-               return (out);
-       } else if (out == OSP_DEF_TIMELIMIT) {
-               return (in);
-       } else {
-               return(in < out ? in : out);
-       }
-}
-
-static int osp_chkDest(
-       const char* callednum,                  /* Called number */
-       const char* callingnum,                 /* Calling number */
-       char* destination,                              /* Destination IP in OSP format */
-       unsigned int tokenlen,                  /* OSP token length */
-       const char* token,                              /* OSP token */
-       enum OSPEFAILREASON* cause,             /* Failure cause, output */
-       struct ast_osp_result* result)  /* OSP lookup results, in/output */
-{
-       int res = 0;
-       OSPE_DEST_OSP_ENABLED enabled;
-       OSPE_DEST_PROT protocol;
-       int error;
-
-       if (strlen(destination) <= 2) {
-               *cause = OSPC_FAIL_INCOMPATIBLE_DEST;
-       } else {
-               error = OSPPTransactionIsDestOSPEnabled(result->outhandle, &enabled);
-               if ((error == OSPC_ERR_NO_ERROR) && (enabled == OSPE_OSP_FALSE)) {
-                       result->token[0] = '\0';
-               } else {
-                       ast_base64encode(result->token, token, tokenlen, sizeof(result->token) - 1);
-               }
-
-               error = OSPPTransactionGetDestProtocol(result->outhandle, &protocol);
-               if (error != OSPC_ERR_NO_ERROR) {
-                       *cause = OSPC_FAIL_PROTOCOL_ERROR; 
-               } else {
-                       res = 1;
-                       /* Strip leading and trailing brackets */
-                       destination[strlen(destination) - 1] = '\0';
-                       switch(protocol) {
-                               case OSPE_DEST_PROT_H323_SETUP:
-                                       ast_copy_string(result->tech, "H323", sizeof(result->tech));
-                                       ast_log(LOG_DEBUG, "OSP: protocol '%d'\n", protocol);
-                                       snprintf(result->dest, sizeof(result->dest), "%s@%s", callednum, destination + 1);
-                                       ast_copy_string(result->calling, callingnum, sizeof(result->calling));
-                                       break;
-                               case OSPE_DEST_PROT_SIP:
-                                       ast_copy_string(result->tech, "SIP", sizeof(result->tech));
-                                       ast_log(LOG_DEBUG, "OSP: protocol '%d'\n", protocol);
-                                       snprintf(result->dest, sizeof(result->dest), "%s@%s", callednum, destination + 1);
-                                       ast_copy_string(result->calling, callingnum, sizeof(result->calling));
-                                       break;
-                               case OSPE_DEST_PROT_IAX:
-                                       ast_copy_string(result->tech, "IAX", sizeof(result->tech));
-                                       ast_log(LOG_DEBUG, "OSP: protocol '%d'\n", protocol);
-                                       snprintf(result->dest, sizeof(result->dest), "%s@%s", callednum, destination + 1);
-                                       ast_copy_string(result->calling, callingnum, sizeof(result->calling));
-                                       break;
-                               default:
-                                       ast_log(LOG_DEBUG, "OSP: Unknown protocol '%d'\n", protocol);
-                                       *cause = OSPC_FAIL_PROTOCOL_ERROR; 
-                                       res = 0;
-                       }
-               }
-       }
-       return(res);
-}
-
-int ast_osp_lookup(
-       const char* provider,                   /* OSP provider conttext name */
-       const char* srcdev,                             /* Source device of out_bound call */
-       const char* calling,                    /* Calling number */
-       const char* called,                             /* Called number */
-       struct ast_osp_result* result)  /* OSP lookup results, in/output */
-{
-       int res;
-       char source[OSP_NORSTR_SIZE];
-       unsigned int callidlen;
-       char callidstr[OSPC_CALLID_MAXSIZE];
-       char callingnum[OSP_NORSTR_SIZE];
-       char callednum[OSP_NORSTR_SIZE];
-       char destination[OSP_NORSTR_SIZE];
-       unsigned int tokenlen;
-       char token[OSP_TOKSTR_SIZE];
-       unsigned int dummy = 0;
-       enum OSPEFAILREASON cause;
-       int error;
-
-       result->outhandle = OSP_INVALID_HANDLE;
-       result->tech[0] = '\0';
-       result->dest[0] = '\0';
-       result->calling[0] = '\0';
-       result->token[0] = '\0';
-       result->numresults = 0;
-       result->outtimelimit = OSP_DEF_TIMELIMIT;
-
-       if ((res = osp_genTransaction(provider, &result->outhandle, sizeof(source), source)) <= 0) {
-               result->outhandle = OSP_INVALID_HANDLE;
-               if (result->inhandle != OSP_INVALID_HANDLE) {
-                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
-               }
-               ast_log(LOG_WARNING, "OSP: Unable to generate transaction handle\n");
-               return(-1);
-       }
-
-       res = 0;
-       dummy = 0;
-       result->numresults = OSP_DEF_DESTINATIONS;
-       error = OSPPTransactionRequestAuthorisation(
-               result->outhandle, 
-               source, srcdev,
-               calling ? calling : "", OSPC_E164, 
-               called, OSPC_E164, 
-               NULL, 
-               0, NULL, 
-               NULL, 
-               &result->numresults, 
-               &dummy, NULL);
-       if (error != OSPC_ERR_NO_ERROR) {
-               result->numresults = 0;
-               OSPPTransactionRecordFailure(result->outhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
-               if (result->inhandle != OSP_INVALID_HANDLE) {
-                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
-               }
-               return(res);
-       }
-
-       if (!result->numresults) {
-               result->numresults = 0;
-               OSPPTransactionRecordFailure(result->outhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
-               if (result->inhandle != OSP_INVALID_HANDLE) {
-                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
-               }
-               return(res);
-       }
-
-       callidlen = sizeof(callidstr);
-       tokenlen = sizeof(token);
-       error = OSPPTransactionGetFirstDestination(
-               result->outhandle, 
-               0, NULL, NULL, 
-               &result->outtimelimit, 
-               &callidlen, callidstr,
-               sizeof(callednum), callednum, 
-               sizeof(callingnum), callingnum, 
-               sizeof(destination), destination, 
-               0, NULL, 
-               &tokenlen, token);
-       if (error != OSPC_ERR_NO_ERROR) {
-               result->token[0] = '\0';
-               result->numresults = 0;
-               result->outtimelimit = OSP_DEF_TIMELIMIT;
-               OSPPTransactionRecordFailure(result->outhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
-               if (result->inhandle != OSP_INVALID_HANDLE) {
-                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
-               }
-               ast_log(LOG_DEBUG, "OSP: Unable to get first route\n");
-               return(res);
-       }
-
-       do {
-               result->outtimelimit = osp_choTimelimit(result->intimelimit, result->outtimelimit);
-               ast_log(LOG_DEBUG, "OSP: outtimelimit '%d'\n", result->outtimelimit);
-               ast_log(LOG_DEBUG, "OSP: called '%s'\n", callednum);
-               ast_log(LOG_DEBUG, "OSP: calling '%s'\n", callingnum);
-               ast_log(LOG_DEBUG, "OSP: destination '%s'\n", destination);
-               ast_log(LOG_DEBUG, "OSP: token size '%d'\n", tokenlen);
-
-               res = osp_chkDest(callednum, callingnum, destination, tokenlen, token, &cause, result);
-               if (!res) {
-                       result->numresults--;
-                       if (result->numresults) {
-                               callidlen = sizeof(callidstr);
-                               tokenlen = sizeof(token);
-                               error = OSPPTransactionGetNextDestination(
-                                       result->outhandle, 
-                                       cause, 
-                                       0, NULL, NULL, 
-                                       &result->outtimelimit, 
-                                       &callidlen, callidstr,
-                                       sizeof(callednum), callednum, 
-                                       sizeof(callingnum), callingnum, 
-                                       sizeof(destination), destination, 
-                                       0, NULL, 
-                                       &tokenlen, token);
-                               if (error != OSPC_ERR_NO_ERROR) {
-                                       result->token[0] = '\0';
-                                       result->numresults = 0;
-                                       result->outtimelimit = OSP_DEF_TIMELIMIT;
-                                       OSPPTransactionRecordFailure(result->outhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
-                                       if (result->inhandle != OSP_INVALID_HANDLE) {
-                                               OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
-                                       }
-                                       break;
-                               }
-                       } else {
-                               result->token[0] = '\0';
-                               result->numresults = 0;
-                               result->outtimelimit = OSP_DEF_TIMELIMIT;
-                               OSPPTransactionRecordFailure(result->outhandle, cause);
-                               if (result->inhandle != OSP_INVALID_HANDLE) {
-                                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
-                               }
-                       }
-               } else {
-                       result->numresults--;
-               }
-       } while(!res && result->numresults);
-
-       return(res);
-}
-
-static enum OSPEFAILREASON reason2cause(
-       int reason)                                             /* Last call failure reason */
-{
-       enum OSPEFAILREASON cause;
-
-       switch(reason) {
-               case AST_CAUSE_NOTDEFINED:
-                       cause = OSPC_FAIL_NONE;
-                       break;
-               case AST_CAUSE_BUSY:
-                       cause = OSPC_FAIL_USER_BUSY;
-                       break;
-               case AST_CAUSE_CONGESTION:
-                       cause = OSPC_FAIL_SWITCHING_EQUIPMENT_CONGESTION;
-                       break;
-               case AST_CAUSE_UNALLOCATED:
-                       cause = OSPC_FAIL_UNALLOC_NUMBER;
-                       break;
-               case AST_CAUSE_NOANSWER:
-                       cause = OSPC_FAIL_NO_ANSWER_FROM_USER;
-                       break;
-               case AST_CAUSE_NORMAL:
-               default:
-                       cause = OSPC_FAIL_NORMAL_CALL_CLEARING;
-                       break;
-       }
-
-       return(cause);
-}
-
-int ast_osp_next(
-       int reason,                                             /* Last desintaion failure reason */
-       struct ast_osp_result *result)  /* OSP lookup results, output */
-{
-       int res = 0;
-       unsigned int callidlen;
-       char callidstr[OSPC_CALLID_MAXSIZE];
-       char callingnum[OSP_NORSTR_SIZE];
-       char callednum[OSP_NORSTR_SIZE];
-       char destination[OSP_NORSTR_SIZE];
-       unsigned int tokenlen;
-       char token[OSP_TOKSTR_SIZE];
-       enum OSPEFAILREASON cause;
-       int error;
-
-       result->tech[0] = '\0';
-       result->dest[0] = '\0';
-       result->calling[0] = '\0';
-       result->token[0] = '\0';
-       result->outtimelimit = OSP_DEF_TIMELIMIT;
-
-       if (result->outhandle == OSP_INVALID_HANDLE) {
-               result->numresults = 0;
-               if (result->inhandle != OSP_INVALID_HANDLE) {
-                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
-               }
-               ast_log(LOG_WARNING, "OSP: Transaction handle undefined\n");
-               return(-1);
-       }
-
-       cause = reason2cause(reason);
-       if (!result->numresults) {
-               OSPPTransactionRecordFailure(result->outhandle, cause);
-               if (result->inhandle != OSP_INVALID_HANDLE) {
-                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
-               }
-               ast_log(LOG_DEBUG, "OSP: No more destination\n");
-               return(res);
-       }
-
-       while(!res && result->numresults) {
-               result->numresults--;
-               callidlen = sizeof(callidstr);
-               tokenlen = sizeof(token);
-               error = OSPPTransactionGetNextDestination(
-                       result->outhandle, 
-                       cause, 
-                       0, NULL, NULL, 
-                       &result->outtimelimit, 
-                       &callidlen, callidstr,
-                       sizeof(callednum), callednum, 
-                       sizeof(callingnum), callingnum, 
-                       sizeof(destination), destination, 
-                       0, NULL, 
-                       &tokenlen, token);
-               if (error == OSPC_ERR_NO_ERROR) {
-                       result->outtimelimit = osp_choTimelimit(result->intimelimit, result->outtimelimit);
-                       ast_log(LOG_DEBUG, "OSP: outtimelimit '%d'\n", result->outtimelimit);
-                       ast_log(LOG_DEBUG, "OSP: called '%s'\n", callednum);
-                       ast_log(LOG_DEBUG, "OSP: calling '%s'\n", callingnum);
-                       ast_log(LOG_DEBUG, "OSP: destination '%s'\n", destination);
-                       ast_log(LOG_DEBUG, "OSP: token size '%d'\n", tokenlen);
-
-                       res = osp_chkDest(callednum, callingnum, destination, tokenlen, token, &cause, result);
-                       if (!res && !result->numresults) {
-                               OSPPTransactionRecordFailure(result->outhandle, cause);
-                               if (result->inhandle != OSP_INVALID_HANDLE) {
-                                       OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
-                               }
-                       }
-               } else {
-                       result->token[0] = '\0';
-                       result->numresults = 0;
-                       result->outtimelimit = OSP_DEF_TIMELIMIT;
-                       OSPPTransactionRecordFailure(result->outhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
-                       if (result->inhandle != OSP_INVALID_HANDLE) {
-                               OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
-                       }
-               }
-       }
-
-       return(res);
-}
-
-int ast_osp_finish(
-       int handle,                                             /* OSP in/out_bound transaction handle */
-       int reason,                                             /* Last destination failure reason */
-       time_t start,                                   /* Call start time */
-       time_t connect,                                 /* Call connect time */
-       time_t end)                                             /* Call end time*/
-{
-       int res = 1;
-       unsigned int dummy = 0;
-       enum OSPEFAILREASON cause;
-       time_t alert = 0;
-       unsigned isPddInfoPresent = 0;
-       unsigned pdd = 0;
-       unsigned releaseSource = 0;
-       unsigned char *confId = "";
-       int error;
-       
-       if (handle == OSP_INVALID_HANDLE) {
-               return(res);
-       }
-
-       if ((cause = reason2cause(reason)) != OSPC_FAIL_NONE) {
-               OSPPTransactionRecordFailure(handle, cause);
-       }
-       error = OSPPTransactionReportUsage(
-               handle, 
-               difftime(end, connect), start, end, alert, connect, 
-               isPddInfoPresent, pdd, 
-               releaseSource, 
-               confId,
-               0, 0, 0, 0,
-               &dummy, NULL);
-       if (error == OSPC_ERR_NO_ERROR) {
-               ast_log(LOG_DEBUG, "OSP: Usage reported\n");
-               res = 1;
-       } else {
-               ast_log(LOG_DEBUG, "OSP: Unable to report usage, error = %d\n", error);
-               res = 0;
-       }
-       OSPPTransactionDelete(handle);
-
-       return(res);
-}
-
-void ast_osp_adduse(void)
-{
-       osp_usecount++;
-}
-
-void ast_osp_deluse(void)
-{
-       if (osp_usecount > 0) {
-               osp_usecount--;
-       }
-}
-
-static char osp_usage[] =
-"Usage: show osp\n"
-"       Displays information on Open Settlement Protocol support\n";
-
-static struct ast_cli_entry osp_cli = {
-       {"show", "osp", NULL}, 
-       osp_show, 
-       "Displays OSP information", 
-       osp_usage 
-};
-
-static int osp_load(void)
-{
-       char* t;
-       unsigned int v;
-       struct ast_config* cfg;
-       int error = OSPC_ERR_NO_ERROR;
-
-       cfg = ast_config_load(OSP_CONFIG_FILE);
-       if (cfg) {
-               t = ast_variable_retrieve(cfg, OSP_GENERAL_CAT, "accelerate");
-               if (t && ast_true(t)) {
-                       if ((error = OSPPInit(1)) != OSPC_ERR_NO_ERROR) {
-                               ast_log(LOG_WARNING, "OSP: Unable to enable hardware accelleration\n");
-                               OSPPInit(0);
-                       } else {
-                               osp_hardware = 1;
-                       }
-               } else {
-                       OSPPInit(0);
-               }
-               ast_log(LOG_DEBUG, "OSP: osp_hardware '%d'\n", osp_hardware);
-
-               t = ast_variable_retrieve(cfg, OSP_GENERAL_CAT, "tokenformat");
-               if (t) {
-                       if ((sscanf(t, "%d", &v) == 1) && 
-                               ((v == TOKEN_ALGO_SIGNED) || (v == TOKEN_ALGO_UNSIGNED) || (v == TOKEN_ALGO_BOTH))) 
-                       {
-                               osp_tokenformat = v;
-                       } else {
-                               ast_log(LOG_WARNING, "tokenformat should be an integer from %d, %d or %d, not '%s'\n", 
-                                       TOKEN_ALGO_SIGNED, TOKEN_ALGO_UNSIGNED, TOKEN_ALGO_BOTH, t);
-                       }
-               }
-               ast_log(LOG_DEBUG, "OSP: osp_tokenformat '%d'\n", osp_tokenformat);
-
-               t = ast_category_browse(cfg, NULL);
-               while(t) {
-                       if (strcasecmp(t, OSP_GENERAL_CAT)) {
-                               osp_buildProvider(cfg, t);
-                       }
-                       t = ast_category_browse(cfg, t);
-               }
-
-               osp_initialized = 1;
-
-               ast_config_destroy(cfg);
-       } else {
-               ast_log(LOG_WARNING, "OSP: Unable to find configuration. OSP support disabled\n");
-       }
-       ast_log(LOG_DEBUG, "OSP: osp_initialized '%d'\n", osp_initialized);
-
-       return(0);
-}
-
-static int osp_unload(void)
-{
-       struct osp_provider* p;
-       struct osp_provider* next;
-
-       if (osp_initialized) {
-               ast_mutex_lock(&osplock);
-               p = ospproviders;
-               while(p) {
-                       next = p->next;
-                       OSPPProviderDelete(p->handle, 0);
-                       free(p);
-                       p = next;
-               }
-               ospproviders = NULL;
-               ast_mutex_unlock(&osplock);
-
-               OSPPCleanup();
-
-               osp_usecount = 0;
-               osp_tokenformat = TOKEN_ALGO_SIGNED;
-               osp_hardware = 0;
-               osp_initialized = 0;
-       }
-       return(0);
-}
-
-static int osp_show(int fd, int argc, char *argv[])
-{
-       int i;
-       int found = 0;
-       struct osp_provider* p;
-       char* provider = NULL;
-       char* tokenalgo;
-
-       if ((argc < 2) || (argc > 3)) {
-               return(RESULT_SHOWUSAGE);
-       }
-       if (argc > 2) {
-               provider = argv[2];
-       }
-       if (!provider) {
-               switch (osp_tokenformat) {
-                       case TOKEN_ALGO_BOTH:
-                               tokenalgo = "Both";
-                               break;
-                       case TOKEN_ALGO_UNSIGNED:
-                               tokenalgo = "Unsigned";
-                               break;
-                       case TOKEN_ALGO_SIGNED:
-                       default:
-                               tokenalgo = "Signed";
-                               break;
-               }
-               ast_cli(fd, "OSP: %s %s %s\n", 
-                       osp_initialized ? "Initialized" : "Uninitialized", osp_hardware ? "Accelerated" : "Normal", tokenalgo);
-       }
-
-       ast_mutex_lock(&osplock);
-       p = ospproviders;
-       while(p) {
-               if (!provider || !strcasecmp(p->name, provider)) {
-                       if (found) {
-                               ast_cli(fd, "\n");
-                       }
-                       ast_cli(fd, " == OSP Provider '%s' == \n", p->name);
-                       ast_cli(fd, "Local Private Key: %s\n", p->privatekey);
-                       ast_cli(fd, "Local Certificate: %s\n", p->localcert);
-                       for (i = 0; i < p->cacount; i++) {
-                               ast_cli(fd, "CA Certificate %d:  %s\n", i + 1, p->cacerts[i]);
-                       }
-                       for (i = 0; i < p->spcount; i++) {
-                               ast_cli(fd, "Service Point %d:   %s\n", i + 1, p->srvpoints[i]);
-                       }
-                       ast_cli(fd, "Max Connections:   %d\n", p->maxconnections);
-                       ast_cli(fd, "Retry Delay:       %d seconds\n", p->retrydelay);
-                       ast_cli(fd, "Retry Limit:       %d\n", p->retrylimit);
-                       ast_cli(fd, "Timeout:           %d milliseconds\n", p->timeout);
-                       ast_cli(fd, "Source:            %s\n", strlen(p->source) ? p->source : "<unspecified>");
-                       ast_cli(fd, "Auth Policy        %d\n", p->authpolicy);
-                       ast_cli(fd, "OSP Handle:        %d\n", p->handle);
-                       found++;
-               }
-               p = p->next;
-       }
-       ast_mutex_unlock(&osplock);
-
-       if (!found) {
-               if (provider) {
-                       ast_cli(fd, "Unable to find OSP provider '%s'\n", provider);
-               } else {
-                       ast_cli(fd, "No OSP providers configured\n");
-               }
-       }
-       return(RESULT_SUCCESS);
-}
-
-static int load_module(void *mod)
-{
-       osp_load();
-       ast_cli_register(&osp_cli);
-       return 0;
-}
-
-static int reload(void *mod)
-{
-       ast_cli_unregister(&osp_cli);
-       osp_unload();
-       osp_load();
-       ast_cli_register(&osp_cli);
-       return 0;
-}
-
-static int unload_module(void *mod)
-{
-       ast_cli_unregister(&osp_cli);
-       osp_unload();
-       return 0;
-}
-
-static const char *description(void)
-{
-       return "Open Settlement Protocol Support";
-}
-
-#if 0
-/* XXX usecount handling still needs to be fixed.
- */
-int usecount(void)
-{
-       return(osp_usecount);
-}
-#endif
-
-static const char *key(void)
-{
-       return ASTERISK_GPL_KEY;
-}
-
-STD_MOD(MOD_0, reload, NULL, NULL)
-
-