update dependency information to match new names for dependencies
[asterisk/asterisk.git] / apps / app_osplookup.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  * \brief Open Settlement Protocol (OSP) Applications
22  *
23  * \author Mark Spencer <markster@digium.com>
24  * 
25  * \ingroup applications
26  */
27
28 /*** MODULEINFO
29         <depend>osptk</depend>
30         <depend>ssl</depend>
31  ***/
32
33 #include "asterisk.h"
34
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36
37 #include <sys/types.h>
38 #include <stdio.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <errno.h>
42 #include <osp/osp.h>
43 #include <osp/osputils.h>
44
45 #include "asterisk/lock.h"
46 #include "asterisk/config.h"
47 #include "asterisk/utils.h"
48 #include "asterisk/causes.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/app.h"
51 #include "asterisk/module.h"
52 #include "asterisk/pbx.h"
53 #include "asterisk/options.h"
54 #include "asterisk/cli.h"
55 #include "asterisk/logger.h"
56 #include "asterisk/astosp.h"
57
58 /* OSP Buffer Sizes */
59 #define OSP_INTSTR_SIZE                 ((unsigned int)16)                      /* OSP signed/unsigned int string buffer size */
60 #define OSP_NORSTR_SIZE                 ((unsigned int)256)                     /* OSP normal string buffer size */
61 #define OSP_TOKSTR_SIZE                 ((unsigned int)4096)                    /* OSP token string buffer size */
62
63 /* OSP Constants */
64 #define OSP_INVALID_HANDLE              ((int)-1)                               /* Invalid OSP handle, provider, transaction etc. */
65 #define OSP_CONFIG_FILE                 ((const char*)"osp.conf")               /* OSP configuration file name */
66 #define OSP_GENERAL_CAT                 ((const char*)"general")                /* OSP global configuration context name */
67 #define OSP_DEF_PROVIDER                ((const char*)"default")                /* OSP default provider context name */
68 #define OSP_MAX_CERTS                   ((unsigned int)10)                      /* OSP max number of cacerts */
69 #define OSP_MAX_SRVS                    ((unsigned int)10)                      /* OSP max number of service points */
70 #define OSP_DEF_MAXCONNECTIONS          ((unsigned int)20)                      /* OSP default max_connections */
71 #define OSP_MIN_MAXCONNECTIONS          ((unsigned int)1)                       /* OSP min max_connections */
72 #define OSP_MAX_MAXCONNECTIONS          ((unsigned int)1000)                    /* OSP max max_connections */
73 #define OSP_DEF_RETRYDELAY              ((unsigned int)0)                       /* OSP default retry delay */
74 #define OSP_MIN_RETRYDELAY              ((unsigned int)0)                       /* OSP min retry delay */
75 #define OSP_MAX_RETRYDELAY              ((unsigned int)10)                      /* OSP max retry delay */
76 #define OSP_DEF_RETRYLIMIT              ((unsigned int)2)                       /* OSP default retry times */
77 #define OSP_MIN_RETRYLIMIT              ((unsigned int)0)                       /* OSP min retry times */
78 #define OSP_MAX_RETRYLIMIT              ((unsigned int)100)                     /* OSP max retry times */
79 #define OSP_DEF_TIMEOUT                 ((unsigned int)500)                     /* OSP default timeout in ms */
80 #define OSP_MIN_TIMEOUT                 ((unsigned int)200)                     /* OSP min timeout in ms */
81 #define OSP_MAX_TIMEOUT                 ((unsigned int)10000)                   /* OSP max timeout in ms */
82 #define OSP_DEF_AUTHPOLICY              ((enum osp_authpolicy)OSP_AUTH_YES)
83 #define OSP_AUDIT_URL                   ((const char*)"localhost")              /* OSP default Audit URL */
84 #define OSP_LOCAL_VALIDATION            ((int)1)                                /* Validate OSP token locally */
85 #define OSP_SSL_LIFETIME                ((unsigned int)300)                     /* SSL life time, in seconds */
86 #define OSP_HTTP_PERSISTENCE            ((int)1)                                /* In seconds */
87 #define OSP_CUSTOMER_ID                 ((const char*)"")                       /* OSP customer ID */
88 #define OSP_DEVICE_ID                   ((const char*)"")                       /* OSP device ID */
89 #define OSP_DEF_DESTINATIONS            ((unsigned int)5)                       /* OSP default max number of destinations */
90 #define OSP_DEF_TIMELIMIT               ((unsigned int)0)                       /* OSP default duration limit, no limit */
91
92 /* OSP Authentication Policy */
93 enum osp_authpolicy {
94         OSP_AUTH_NO,            /* Accept any call */
95         OSP_AUTH_YES,           /* Accept call with valid OSP token or without OSP token */
96         OSP_AUTH_EXCLUSIVE      /* Only accept call with valid OSP token */
97 };
98
99 /* OSP Provider */
100 struct osp_provider {
101         char name[OSP_NORSTR_SIZE];                             /* OSP provider context name */
102         char privatekey[OSP_NORSTR_SIZE];                       /* OSP private key file name */
103         char localcert[OSP_NORSTR_SIZE];                        /* OSP local cert file name */
104         unsigned int cacount;                                   /* Number of cacerts */
105         char cacerts[OSP_MAX_CERTS][OSP_NORSTR_SIZE];           /* Cacert file names */
106         unsigned int spcount;                                   /* Number of service points */
107         char srvpoints[OSP_MAX_SRVS][OSP_NORSTR_SIZE];          /* Service point URLs */
108         int maxconnections;                                     /* Max number of connections */
109         int retrydelay;                                         /* Retry delay */
110         int retrylimit;                                         /* Retry limit */
111         int timeout;                                            /* Timeout in ms */
112         char source[OSP_NORSTR_SIZE];                           /* IP of self */
113         enum osp_authpolicy authpolicy;                         /* OSP authentication policy */
114         OSPTPROVHANDLE handle;                                  /* OSP provider handle */
115         struct osp_provider* next;                              /* Pointer to next OSP provider */
116 };
117
118 /* OSP Application In/Output Results */
119 struct osp_result {
120         int inhandle;                                           /* Inbound transaction handle */
121         int outhandle;                                          /* Outbound transaction handle */
122         unsigned int intimelimit;                               /* Inbound duration limit */
123         unsigned int outtimelimit;                              /* Outbound duration limit */
124         char tech[20];                                          /* Asterisk TECH string */
125         char dest[OSP_NORSTR_SIZE];                             /* Destination in called@IP format */
126         char calling[OSP_NORSTR_SIZE];                          /* Calling number, may be translated */
127         char token[OSP_TOKSTR_SIZE];                            /* Outbound OSP token */
128         int numresults;                                         /* Number of remain destinations */
129 };
130
131 /* OSP Module Global Variables */
132 AST_MUTEX_DEFINE_STATIC(osplock);                               /* Lock of OSP provider list */
133 static int osp_initialized = 0;                                 /* Init flag */
134 static int osp_hardware = 0;                                    /* Hardware accelleration flag */
135 static struct osp_provider* ospproviders = NULL;                /* OSP provider list */
136 static unsigned int osp_tokenformat = TOKEN_ALGO_SIGNED;        /* Token format supported */
137
138 /* OSP Client Wrapper APIs */
139
140 /*!
141  * \brief Create OSP provider handle according to configuration
142  * \param cfg OSP configuration
143  * \param provider OSP provider context name
144  * \return 1 Success, 0 Failed, -1 Error
145  */
146 static int osp_create_provider(struct ast_config* cfg, const char* provider)
147 {
148         int res;
149         unsigned int t, i, j;
150         struct osp_provider* p;
151         struct ast_variable* v;
152         OSPTPRIVATEKEY privatekey;
153         OSPTCERT localcert;
154         const char* psrvpoints[OSP_MAX_SRVS];
155         OSPTCERT cacerts[OSP_MAX_CERTS];
156         const OSPTCERT* pcacerts[OSP_MAX_CERTS];
157         int error = OSPC_ERR_NO_ERROR;
158
159         if (!(p = ast_calloc(1, sizeof(*p)))) {
160                 ast_log(LOG_ERROR, "Out of memory\n");
161                 return -1;
162         }
163
164         ast_copy_string(p->name, provider, sizeof(p->name));
165         snprintf(p->privatekey, sizeof(p->privatekey), "%s/%s-privatekey.pem", ast_config_AST_KEY_DIR, provider);
166         snprintf(p->localcert, sizeof(p->localcert), "%s/%s-localcert.pem", ast_config_AST_KEY_DIR, provider);
167         p->maxconnections = OSP_DEF_MAXCONNECTIONS;
168         p->retrydelay = OSP_DEF_RETRYDELAY;
169         p->retrylimit = OSP_DEF_RETRYLIMIT;
170         p->timeout = OSP_DEF_TIMEOUT;
171         p->authpolicy = OSP_DEF_AUTHPOLICY;
172         p->handle = OSP_INVALID_HANDLE;
173
174         v = ast_variable_browse(cfg, provider);
175         while(v) {
176                 if (!strcasecmp(v->name, "privatekey")) {
177                         if (v->value[0] == '/') {
178                                 ast_copy_string(p->privatekey, v->value, sizeof(p->privatekey));
179                         } else {
180                                 snprintf(p->privatekey, sizeof(p->privatekey), "%s/%s", ast_config_AST_KEY_DIR, v->value);
181                         }
182                         ast_log(LOG_DEBUG, "OSP: privatekey '%s'\n", p->privatekey);
183                 } else if (!strcasecmp(v->name, "localcert")) {
184                         if (v->value[0] == '/') {
185                                 ast_copy_string(p->localcert, v->value, sizeof(p->localcert));
186                         } else {
187                                 snprintf(p->localcert, sizeof(p->localcert), "%s/%s", ast_config_AST_KEY_DIR, v->value);
188                         }
189                         ast_log(LOG_DEBUG, "OSP: localcert '%s'\n", p->localcert);
190                 } else if (!strcasecmp(v->name, "cacert")) {
191                         if (p->cacount < OSP_MAX_CERTS) {
192                                 if (v->value[0] == '/') {
193                                         ast_copy_string(p->cacerts[p->cacount], v->value, sizeof(p->cacerts[0]));
194                                 } else {
195                                         snprintf(p->cacerts[p->cacount], sizeof(p->cacerts[0]), "%s/%s", ast_config_AST_KEY_DIR, v->value);
196                                 }
197                                 ast_log(LOG_DEBUG, "OSP: cacert[%d]: '%s'\n", p->cacount, p->cacerts[p->cacount]);
198                                 p->cacount++;
199                         } else {
200                                 ast_log(LOG_WARNING, "OSP: Too many CA Certificates at line %d\n", v->lineno);
201                         }
202                 } else if (!strcasecmp(v->name, "servicepoint")) {
203                         if (p->spcount < OSP_MAX_SRVS) {
204                                 ast_copy_string(p->srvpoints[p->spcount], v->value, sizeof(p->srvpoints[0]));
205                                 ast_log(LOG_DEBUG, "OSP: servicepoint[%d]: '%s'\n", p->spcount, p->srvpoints[p->spcount]);
206                                 p->spcount++;
207                         } else {
208                                 ast_log(LOG_WARNING, "OSP: Too many Service Points at line %d\n", v->lineno);
209                         }
210                 } else if (!strcasecmp(v->name, "maxconnections")) {
211                         if ((sscanf(v->value, "%d", &t) == 1) && (t >= OSP_MIN_MAXCONNECTIONS) && (t <= OSP_MAX_MAXCONNECTIONS)) {
212                                 p->maxconnections = t;
213                                 ast_log(LOG_DEBUG, "OSP: maxconnections '%d'\n", t);
214                         } else {
215                                 ast_log(LOG_WARNING, "OSP: maxconnections should be an integer from %d to %d, not '%s' at line %d\n", 
216                                         OSP_MIN_MAXCONNECTIONS, OSP_MAX_MAXCONNECTIONS, v->value, v->lineno);
217                         }
218                 } else if (!strcasecmp(v->name, "retrydelay")) {
219                         if ((sscanf(v->value, "%d", &t) == 1) && (t >= OSP_MIN_RETRYDELAY) && (t <= OSP_MAX_RETRYDELAY)) {
220                                 p->retrydelay = t;
221                                 ast_log(LOG_DEBUG, "OSP: retrydelay '%d'\n", t);
222                         } else {
223                                 ast_log(LOG_WARNING, "OSP: retrydelay should be an integer from %d to %d, not '%s' at line %d\n", 
224                                         OSP_MIN_RETRYDELAY, OSP_MAX_RETRYDELAY, v->value, v->lineno);
225                         }
226                 } else if (!strcasecmp(v->name, "retrylimit")) {
227                         if ((sscanf(v->value, "%d", &t) == 1) && (t >= OSP_MIN_RETRYLIMIT) && (t <= OSP_MAX_RETRYLIMIT)) {
228                                 p->retrylimit = t;
229                                 ast_log(LOG_DEBUG, "OSP: retrylimit '%d'\n", t);
230                         } else {
231                                 ast_log(LOG_WARNING, "OSP: retrylimit should be an integer from %d to %d, not '%s' at line %d\n", 
232                                         OSP_MIN_RETRYLIMIT, OSP_MAX_RETRYLIMIT, v->value, v->lineno);
233                         }
234                 } else if (!strcasecmp(v->name, "timeout")) {
235                         if ((sscanf(v->value, "%d", &t) == 1) && (t >= OSP_MIN_TIMEOUT) && (t <= OSP_MAX_TIMEOUT)) {
236                                 p->timeout = t;
237                                 ast_log(LOG_DEBUG, "OSP: timeout '%d'\n", t);
238                         } else {
239                                 ast_log(LOG_WARNING, "OSP: timeout should be an integer from %d to %d, not '%s' at line %d\n", 
240                                         OSP_MIN_TIMEOUT, OSP_MAX_TIMEOUT, v->value, v->lineno);
241                         }
242                 } else if (!strcasecmp(v->name, "source")) {
243                         ast_copy_string(p->source, v->value, sizeof(p->source));
244                         ast_log(LOG_DEBUG, "OSP: source '%s'\n", p->source);
245                 } else if (!strcasecmp(v->name, "authpolicy")) {
246                         if ((sscanf(v->value, "%d", &t) == 1) && ((t == OSP_AUTH_NO) || (t == OSP_AUTH_YES) || (t == OSP_AUTH_EXCLUSIVE))) {
247                                 p->authpolicy = t;
248                                 ast_log(LOG_DEBUG, "OSP: authpolicy '%d'\n", t);
249                         } else {
250                                 ast_log(LOG_WARNING, "OSP: authpolicy should be %d, %d or %d, not '%s' at line %d\n", 
251                                         OSP_AUTH_NO, OSP_AUTH_YES, OSP_AUTH_EXCLUSIVE, v->value, v->lineno);
252                         }
253                 }
254                 v = v->next;
255         }
256
257         error = OSPPUtilLoadPEMPrivateKey(p->privatekey, &privatekey);
258         if (error != OSPC_ERR_NO_ERROR) {
259                 ast_log(LOG_WARNING, "OSP: Unable to load privatekey '%s', error '%d'\n", p->privatekey, error);
260                 free(p);
261                 return 0;
262         }
263
264         error = OSPPUtilLoadPEMCert(p->localcert, &localcert);
265         if (error != OSPC_ERR_NO_ERROR) {
266                 ast_log(LOG_WARNING, "OSP: Unable to load localcert '%s', error '%d'\n", p->localcert, error);
267                 if (privatekey.PrivateKeyData) {
268                         free(privatekey.PrivateKeyData);
269                 }
270                 free(p);
271                 return 0;
272         }
273
274         if (p->cacount < 1) {
275                 snprintf(p->cacerts[p->cacount], sizeof(p->cacerts[0]), "%s/%s-cacert.pem", ast_config_AST_KEY_DIR, provider);
276                 ast_log(LOG_DEBUG, "OSP: cacert[%d]: '%s'\n", p->cacount, p->cacerts[p->cacount]);
277                 p->cacount++;
278         }
279         for (i = 0; i < p->cacount; i++) {
280                 error = OSPPUtilLoadPEMCert(p->cacerts[i], &cacerts[i]);
281                 if (error != OSPC_ERR_NO_ERROR) {
282                         ast_log(LOG_WARNING, "OSP: Unable to load cacert '%s', error '%d'\n", p->cacerts[i], error);
283                         for (j = 0; j < i; j++) {
284                                 if (cacerts[j].CertData) {
285                                         free(cacerts[j].CertData);
286                                 }
287                         }
288                         if (localcert.CertData) {
289                                 free(localcert.CertData);
290                         }
291                         if (privatekey.PrivateKeyData) {
292                                 free(privatekey.PrivateKeyData);
293                         }
294                         free(p);
295                         return 0;
296                 }
297                 pcacerts[i] = &cacerts[i];
298         }
299         
300         for (i = 0; i < p->spcount; i++) {
301                 psrvpoints[i] = p->srvpoints[i];
302         }
303
304         error = OSPPProviderNew(p->spcount, psrvpoints, NULL, OSP_AUDIT_URL, &privatekey, &localcert, p->cacount, pcacerts, OSP_LOCAL_VALIDATION,
305                                 OSP_SSL_LIFETIME, p->maxconnections, OSP_HTTP_PERSISTENCE, p->retrydelay, p->retrylimit,p->timeout, OSP_CUSTOMER_ID,
306                                 OSP_DEVICE_ID, &p->handle);
307         if (error != OSPC_ERR_NO_ERROR) {
308                 ast_log(LOG_WARNING, "OSP: Unable to create provider '%s', error '%d'\n", provider, error);
309                 free(p);
310                 res = -1;
311         } else {
312                 ast_log(LOG_DEBUG, "OSP: provider '%s'\n", provider);
313                 ast_mutex_lock(&osplock);
314                 p->next = ospproviders;
315                 ospproviders = p;
316                 ast_mutex_unlock(&osplock);     
317                 res = 1;
318         }
319
320         for (i = 0; i < p->cacount; i++) {
321                 if (cacerts[i].CertData) {
322                         free(cacerts[i].CertData);
323                 }
324         }
325         if (localcert.CertData) {
326                 free(localcert.CertData);
327         }
328         if (privatekey.PrivateKeyData) {
329                 free(privatekey.PrivateKeyData);
330         }
331
332         return res;
333 }
334
335 /*!
336  * \brief Get OSP authenticiation policy of provider
337  * \param provider OSP provider context name
338  * \param policy OSP authentication policy, output
339  * \return 1 Success, 0 Failed, -1 Error
340  */
341 static int osp_get_policy(const char* provider, int* policy)
342 {
343         int res = 0;
344         struct osp_provider* p;
345
346         ast_mutex_lock(&osplock);
347         p = ospproviders;
348         while(p) {
349                 if (!strcasecmp(p->name, provider)) {
350                         *policy = p->authpolicy;
351                         ast_log(LOG_DEBUG, "OSP: authpolicy '%d'\n", *policy);
352                         res = 1;
353                         break;
354                 }
355                 p = p->next;
356         }
357         ast_mutex_unlock(&osplock);
358
359         return res;
360 }
361
362 /*!
363  * \brief Create OSP transaction handle
364  * \param provider OSP provider context name
365  * \param transaction OSP transaction handle, output
366  * \param sourcesize Size of source buffer, in/output
367  * \param source Source of provider, output
368  * \return 1 Success, 0 Failed, -1 Error
369  */
370 static int osp_create_transaction(const char* provider, int* transaction, unsigned int sourcesize, char* source)
371 {
372         int res = 0;
373         struct osp_provider* p;
374         int error;
375
376         ast_mutex_lock(&osplock);
377         p = ospproviders;
378         while(p) {
379                 if (!strcasecmp(p->name, provider)) {
380                         error = OSPPTransactionNew(p->handle, transaction);
381                         if (error == OSPC_ERR_NO_ERROR) {
382                                 ast_log(LOG_DEBUG, "OSP: transaction '%d'\n", *transaction);
383                                 ast_copy_string(source, p->source, sourcesize);
384                                 ast_log(LOG_DEBUG, "OSP: source '%s'\n", source);
385                                 res = 1;
386                         } else {
387                                 *transaction = OSP_INVALID_HANDLE;
388                                 ast_log(LOG_DEBUG, "OSP: Unable to create transaction handle, error '%d'\n", error);
389                                 res = -1;
390                         }
391                         break;
392                 }
393                 p = p->next;
394         }
395         ast_mutex_unlock(&osplock);
396
397         return res;
398 }
399
400 /*!
401  * \brief Validate OSP token of inbound call
402  * \param transaction OSP transaction handle
403  * \param source Source of inbound call
404  * \param dest Destination of inbound call
405  * \param calling Calling number
406  * \param called Called number
407  * \param token OSP token, may be empty
408  * \param timelimit Call duration limit, output
409  * \return 1 Success, 0 Failed, -1 Error
410  */
411 static int osp_validate_token(int transaction, const char* source, const char* dest, const char* calling, const char* called, const char* token, unsigned int* timelimit)
412 {
413         int res;
414         int tokenlen;
415         char tokenstr[OSP_TOKSTR_SIZE];
416         unsigned int authorised;
417         unsigned int dummy = 0;
418         int error;
419
420         tokenlen = ast_base64decode(tokenstr, token, strlen(token));
421         error = OSPPTransactionValidateAuthorisation(
422                 transaction, 
423                 source, dest, NULL, NULL,
424                 calling ? calling : "", OSPC_E164, 
425                 called, OSPC_E164, 
426                 0, NULL,
427                 tokenlen, tokenstr, 
428                 &authorised, 
429                 timelimit, 
430                 &dummy, NULL, 
431                 osp_tokenformat); 
432         if (error != OSPC_ERR_NO_ERROR) {
433                 ast_log(LOG_DEBUG, "OSP: Unable to validate inbound token\n");
434                 res = -1;
435         } else if (authorised) {
436                 ast_log(LOG_DEBUG, "OSP: Authorised\n");
437                 res = 1;
438         } else {
439                 ast_log(LOG_DEBUG, "OSP: Unauthorised\n");
440                 res = 0;
441         }
442         
443         return res;
444 }
445
446 /*!
447  * \brief Choose min duration limit
448  * \param in Inbound duration limit
449  * \param out Outbound duration limit
450  * \return min duration limit
451  */
452 static unsigned int osp_choose_timelimit(unsigned int in, unsigned int out)
453 {
454         if (in == OSP_DEF_TIMELIMIT) {
455                 return out;
456         } else if (out == OSP_DEF_TIMELIMIT) {
457                 return in;
458         } else {
459                 return in < out ? in : out;
460         }
461 }
462
463 /*!
464  * \brief Choose min duration limit
465  * \param called Called number
466  * \param calling Calling number
467  * \param destination Destination IP in '[x.x.x.x]' format
468  * \param tokenlen OSP token length
469  * \param token OSP token
470  * \param reason Failure reason, output
471  * \param result OSP lookup results, in/output
472  * \return 1 Success, 0 Failed, -1 Error
473  */
474 static int osp_check_destination(const char* called, const char* calling, char* destination, unsigned int tokenlen, const char* token, enum OSPEFAILREASON* reason, struct osp_result* result)
475 {
476         int res;
477         OSPE_DEST_OSP_ENABLED enabled;
478         OSPE_DEST_PROT protocol;
479         int error;
480
481         if (strlen(destination) <= 2) {
482                 ast_log(LOG_DEBUG, "OSP: Wrong destination format '%s'\n", destination);
483                 *reason = OSPC_FAIL_NORMAL_UNSPECIFIED;
484                 return -1;
485         } 
486
487         if ((error = OSPPTransactionIsDestOSPEnabled(result->outhandle, &enabled)) != OSPC_ERR_NO_ERROR) {
488                 ast_log(LOG_DEBUG, "OSP: Unable to get destination OSP version, error '%d'\n", error);
489                 *reason = OSPC_FAIL_NORMAL_UNSPECIFIED;
490                 return -1;
491         }
492
493         if (enabled == OSPE_OSP_FALSE) {
494                 result->token[0] = '\0';
495         } else {
496                 ast_base64encode(result->token, token, tokenlen, sizeof(result->token) - 1);
497         }
498
499         if ((error = OSPPTransactionGetDestProtocol(result->outhandle, &protocol)) != OSPC_ERR_NO_ERROR) {
500                 ast_log(LOG_DEBUG, "OSP: Unable to get destination protocol, error '%d'\n", error);
501                 *reason = OSPC_FAIL_NORMAL_UNSPECIFIED; 
502                 result->token[0] = '\0';
503                 return -1;
504         } 
505
506         res = 1;
507         /* Strip leading and trailing brackets */
508         destination[strlen(destination) - 1] = '\0';
509         switch(protocol) {
510                 case OSPE_DEST_PROT_H323_SETUP:
511                         ast_log(LOG_DEBUG, "OSP: protocol '%d'\n", protocol);
512                         ast_copy_string(result->tech, "H323", sizeof(result->tech));
513                         snprintf(result->dest, sizeof(result->dest), "%s@%s", called, destination + 1);
514                         ast_copy_string(result->calling, calling, sizeof(result->calling));
515                         break;
516                 case OSPE_DEST_PROT_SIP:
517                         ast_log(LOG_DEBUG, "OSP: protocol '%d'\n", protocol);
518                         ast_copy_string(result->tech, "SIP", sizeof(result->tech));
519                         snprintf(result->dest, sizeof(result->dest), "%s@%s", called, destination + 1);
520                         ast_copy_string(result->calling, calling, sizeof(result->calling));
521                         break;
522                 case OSPE_DEST_PROT_IAX:
523                         ast_log(LOG_DEBUG, "OSP: protocol '%d'\n", protocol);
524                         ast_copy_string(result->tech, "IAX", sizeof(result->tech));
525                         snprintf(result->dest, sizeof(result->dest), "%s@%s", called, destination + 1);
526                         ast_copy_string(result->calling, calling, sizeof(result->calling));
527                         break;
528                 default:
529                         ast_log(LOG_DEBUG, "OSP: Unknown protocol '%d'\n", protocol);
530                         *reason = OSPC_FAIL_PROTOCOL_ERROR; 
531                         result->token[0] = '\0';
532                         res = 0;
533         }
534
535         return res;
536 }
537
538 /*!
539  * \brief Convert Asterisk status to TC code
540  * \param cause Asterisk hangup cause
541  * \return OSP TC code
542  */
543 static enum OSPEFAILREASON asterisk2osp(int cause)
544 {
545         return (enum OSPEFAILREASON)cause;
546 }
547
548 /*!
549  * \brief OSP Authentication function
550  * \param provider OSP provider context name
551  * \param transaction OSP transaction handle, output
552  * \param source Source of inbound call
553  * \param calling Calling number
554  * \param called Called number
555  * \param token OSP token, may be empty
556  * \param timelimit Call duration limit, output
557  * \return 1 Authenricated, 0 Unauthenticated, -1 Error
558  */
559 static int osp_auth(const char* provider, int* transaction, const char* source, const char* calling, const char* called, const char* token, unsigned int* timelimit)
560 {
561         int res;
562         int policy = OSP_AUTH_YES;
563         char dest[OSP_NORSTR_SIZE];
564
565         *transaction = OSP_INVALID_HANDLE;
566         *timelimit = OSP_DEF_TIMELIMIT;
567         res = osp_get_policy(provider, &policy);
568         if (!res) {
569                 ast_log(LOG_DEBUG, "OSP: Unabe to find OSP authentication policy\n");
570                 return res;
571         }
572
573         switch (policy) {
574                 case OSP_AUTH_NO:
575                         res = 1;
576                         break;
577                 case OSP_AUTH_EXCLUSIVE:
578                         if (ast_strlen_zero(token)) {
579                                 res = 0;
580                         } else if ((res = osp_create_transaction(provider, transaction, sizeof(dest), dest)) <= 0) {
581                                 ast_log(LOG_DEBUG, "OSP: Unable to generate transaction handle\n");
582                                 *transaction = OSP_INVALID_HANDLE;
583                                 res = 0;
584                         } else if((res = osp_validate_token(*transaction, source, dest, calling, called, token, timelimit)) <= 0) {
585                                 OSPPTransactionRecordFailure(*transaction, OSPC_FAIL_CALL_REJECTED);
586                         }
587                         break;
588                 case OSP_AUTH_YES:
589                 default:
590                         if (ast_strlen_zero(token)) {
591                                 res = 1;
592                         } else if ((res = osp_create_transaction(provider, transaction, sizeof(dest), dest)) <= 0) {
593                                 ast_log(LOG_DEBUG, "OSP: Unable to generate transaction handle\n");
594                                 *transaction = OSP_INVALID_HANDLE;
595                                 res = 0;
596                         } else if((res = osp_validate_token(*transaction, source, dest, calling, called, token, timelimit)) <= 0) {
597                                 OSPPTransactionRecordFailure(*transaction, OSPC_FAIL_CALL_REJECTED);
598                         }
599                         break;
600         }
601
602         return res;
603 }
604
605 /*!
606  * \brief OSP Lookup function
607  * \param provider OSP provider context name
608  * \param srcdev Source device of outbound call
609  * \param calling Calling number
610  * \param called Called number
611  * \param result Lookup results
612  * \return 1 Found , 0 No route, -1 Error
613  */
614 static int osp_lookup(const char* provider, const char* srcdev, const char* calling, const char* called, struct osp_result* result)
615 {
616         int res;
617         char source[OSP_NORSTR_SIZE];
618         unsigned int callidlen;
619         char callid[OSPC_CALLID_MAXSIZE];
620         char callingnum[OSP_NORSTR_SIZE];
621         char callednum[OSP_NORSTR_SIZE];
622         char destination[OSP_NORSTR_SIZE];
623         unsigned int tokenlen;
624         char token[OSP_TOKSTR_SIZE];
625         unsigned int dummy = 0;
626         enum OSPEFAILREASON reason;
627         int error;
628
629         result->outhandle = OSP_INVALID_HANDLE;
630         result->tech[0] = '\0';
631         result->dest[0] = '\0';
632         result->calling[0] = '\0';
633         result->token[0] = '\0';
634         result->numresults = 0;
635         result->outtimelimit = OSP_DEF_TIMELIMIT;
636
637         if ((res = osp_create_transaction(provider, &result->outhandle, sizeof(source), source)) <= 0) {
638                 ast_log(LOG_DEBUG, "OSP: Unable to generate transaction handle\n");
639                 result->outhandle = OSP_INVALID_HANDLE;
640                 if (result->inhandle != OSP_INVALID_HANDLE) {
641                         OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
642                 }
643                 return -1;
644         }
645
646         result->numresults = OSP_DEF_DESTINATIONS;
647         error = OSPPTransactionRequestAuthorisation(result->outhandle, source, srcdev, calling ? calling : "",
648                         OSPC_E164, called, OSPC_E164, NULL, 0, NULL, NULL, &result->numresults, &dummy, NULL);
649         if (error != OSPC_ERR_NO_ERROR) {
650                 ast_log(LOG_DEBUG, "OSP: Unable to request authorization\n");
651                 result->numresults = 0;
652                 if (result->inhandle != OSP_INVALID_HANDLE) {
653                         OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
654                 }
655                 return -1;
656         }
657
658         if (!result->numresults) {
659                 ast_log(LOG_DEBUG, "OSP: No more destination\n");
660                 if (result->inhandle != OSP_INVALID_HANDLE) {
661                         OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
662                 }
663                 return 0;
664         }
665
666         callidlen = sizeof(callid);
667         tokenlen = sizeof(token);
668         error = OSPPTransactionGetFirstDestination(result->outhandle, 0, NULL, NULL, &result->outtimelimit, &callidlen, callid,
669                         sizeof(callednum), callednum, sizeof(callingnum), callingnum, sizeof(destination), destination, 0, NULL, &tokenlen, token);
670         if (error != OSPC_ERR_NO_ERROR) {
671                 ast_log(LOG_DEBUG, "OSP: Unable to get first route\n");
672                 result->numresults = 0;
673                 result->outtimelimit = OSP_DEF_TIMELIMIT;
674                 if (result->inhandle != OSP_INVALID_HANDLE) {
675                         OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
676                 }
677                 return -1;
678         }
679
680         result->numresults--;
681         result->outtimelimit = osp_choose_timelimit(result->intimelimit, result->outtimelimit);
682         ast_log(LOG_DEBUG, "OSP: outtimelimit '%d'\n", result->outtimelimit);
683         ast_log(LOG_DEBUG, "OSP: called '%s'\n", callednum);
684         ast_log(LOG_DEBUG, "OSP: calling '%s'\n", callingnum);
685         ast_log(LOG_DEBUG, "OSP: destination '%s'\n", destination);
686         ast_log(LOG_DEBUG, "OSP: token size '%d'\n", tokenlen);
687
688         if ((res = osp_check_destination(callednum, callingnum, destination, tokenlen, token, &reason, result)) > 0) {
689                 return 1;
690         }
691
692         if (!result->numresults) {
693                 ast_log(LOG_DEBUG, "OSP: No more destination\n");
694                 result->outtimelimit = OSP_DEF_TIMELIMIT;
695                 OSPPTransactionRecordFailure(result->outhandle, reason);
696                 if (result->inhandle != OSP_INVALID_HANDLE) {
697                         OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
698                 }
699                 return 0;
700         }
701
702         while(result->numresults) {
703                 callidlen = sizeof(callid);
704                 tokenlen = sizeof(token);
705                 error = OSPPTransactionGetNextDestination(result->outhandle, reason, 0, NULL, NULL, &result->outtimelimit, &callidlen, callid,
706                                 sizeof(callednum), callednum, sizeof(callingnum), callingnum, sizeof(destination), destination, 0, NULL, &tokenlen, token);
707                 if (error == OSPC_ERR_NO_ERROR) {
708                         result->numresults--;
709                         result->outtimelimit = osp_choose_timelimit(result->intimelimit, result->outtimelimit);
710                         ast_log(LOG_DEBUG, "OSP: outtimelimit '%d'\n", result->outtimelimit);
711                         ast_log(LOG_DEBUG, "OSP: called '%s'\n", callednum);
712                         ast_log(LOG_DEBUG, "OSP: calling '%s'\n", callingnum);
713                         ast_log(LOG_DEBUG, "OSP: destination '%s'\n", destination);
714                         ast_log(LOG_DEBUG, "OSP: token size '%d'\n", tokenlen);
715                         if ((res = osp_check_destination(callednum, callingnum, destination, tokenlen, token, &reason, result)) > 0) {
716                                 break;
717                         } else if (!result->numresults) {
718                                 ast_log(LOG_DEBUG, "OSP: No more destination\n");
719                                 OSPPTransactionRecordFailure(result->outhandle, reason);
720                                 if (result->inhandle != OSP_INVALID_HANDLE) {
721                                         OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
722                                 }
723                                 res = 0;
724                                 break;
725                         }
726                 } else {
727                         ast_log(LOG_DEBUG, "OSP: Unable to get route, error '%d'\n", error);
728                         result->numresults = 0;
729                         result->outtimelimit = OSP_DEF_TIMELIMIT;
730                         if (result->inhandle != OSP_INVALID_HANDLE) {
731                                 OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
732                         }
733                         res = -1;
734                         break;
735                 }
736         }
737         return res;
738 }
739
740 /*!
741  * \brief OSP Lookup Next function
742  * \param cause Asterisk hangup cuase
743  * \param result Lookup results, in/output
744  * \return 1 Found , 0 No route, -1 Error
745  */
746 static int osp_next(int cause, struct osp_result* result)
747 {
748         int res;
749         unsigned int callidlen;
750         char callid[OSPC_CALLID_MAXSIZE];
751         char callingnum[OSP_NORSTR_SIZE];
752         char callednum[OSP_NORSTR_SIZE];
753         char destination[OSP_NORSTR_SIZE];
754         unsigned int tokenlen;
755         char token[OSP_TOKSTR_SIZE];
756         enum OSPEFAILREASON reason;
757         int error;
758
759         result->tech[0] = '\0';
760         result->dest[0] = '\0';
761         result->calling[0] = '\0';
762         result->token[0] = '\0';
763         result->outtimelimit = OSP_DEF_TIMELIMIT;
764
765         if (result->outhandle == OSP_INVALID_HANDLE) {
766                 ast_log(LOG_DEBUG, "OSP: Transaction handle undefined\n");
767                 result->numresults = 0;
768                 if (result->inhandle != OSP_INVALID_HANDLE) {
769                         OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
770                 }
771                 return -1;
772         }
773
774         reason = asterisk2osp(cause);
775
776         if (!result->numresults) {
777                 ast_log(LOG_DEBUG, "OSP: No more destination\n");
778                 OSPPTransactionRecordFailure(result->outhandle, reason);
779                 if (result->inhandle != OSP_INVALID_HANDLE) {
780                         OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
781                 }
782                 return 0;
783         }
784
785         while(result->numresults) {
786                 callidlen = sizeof(callid);
787                 tokenlen = sizeof(token);
788                 error = OSPPTransactionGetNextDestination(result->outhandle, reason, 0, NULL, NULL, &result->outtimelimit, &callidlen,
789                                 callid, sizeof(callednum), callednum, sizeof(callingnum), callingnum, sizeof(destination), destination, 0, NULL, &tokenlen, token);
790                 if (error == OSPC_ERR_NO_ERROR) {
791                         result->numresults--;
792                         result->outtimelimit = osp_choose_timelimit(result->intimelimit, result->outtimelimit);
793                         ast_log(LOG_DEBUG, "OSP: outtimelimit '%d'\n", result->outtimelimit);
794                         ast_log(LOG_DEBUG, "OSP: called '%s'\n", callednum);
795                         ast_log(LOG_DEBUG, "OSP: calling '%s'\n", callingnum);
796                         ast_log(LOG_DEBUG, "OSP: destination '%s'\n", destination);
797                         ast_log(LOG_DEBUG, "OSP: token size '%d'\n", tokenlen);
798                         if ((res = osp_check_destination(callednum, callingnum, destination, tokenlen, token, &reason, result)) > 0) {
799                                 res = 1;
800                                 break;
801                         } else if (!result->numresults) {
802                                 ast_log(LOG_DEBUG, "OSP: No more destination\n");
803                                 OSPPTransactionRecordFailure(result->outhandle, reason);
804                                 if (result->inhandle != OSP_INVALID_HANDLE) {
805                                         OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NO_ROUTE_TO_DEST);
806                                 }
807                                 res = 0;
808                                 break;
809                         }
810                 } else {
811                         ast_log(LOG_DEBUG, "OSP: Unable to get route, error '%d'\n", error);
812                         result->token[0] = '\0';
813                         result->numresults = 0;
814                         result->outtimelimit = OSP_DEF_TIMELIMIT;
815                         if (result->inhandle != OSP_INVALID_HANDLE) {
816                                 OSPPTransactionRecordFailure(result->inhandle, OSPC_FAIL_NORMAL_UNSPECIFIED);
817                         }
818                         res = -1;
819                         break;
820                 }
821         }
822
823         return res;
824 }
825
826 /*!
827  * \brief OSP Finish function
828  * \param handle OSP in/outbound transaction handle
829  * \param recorded If failure reason has been recorded
830  * \param cause Asterisk hangup cause
831  * \param start Call start time
832  * \param connect Call connect time
833  * \param end Call end time
834  * \param release Who release first, 0 source, 1 destination
835  * \return 1 Success, 0 Failed, -1 Error
836  */
837 static int osp_finish(int handle, int recorded, int cause, time_t start, time_t connect, time_t end, unsigned int release)
838 {
839         int res;
840         enum OSPEFAILREASON reason;
841         time_t alert = 0;
842         unsigned isPddInfoPresent = 0;
843         unsigned pdd = 0;
844         unsigned char* confId = "";
845         unsigned int dummy = 0;
846         int error;
847         
848         if (handle == OSP_INVALID_HANDLE) {
849                 return 0;
850         }
851
852         if (!recorded) {
853                 reason = asterisk2osp(cause);
854                 OSPPTransactionRecordFailure(handle, reason);
855         }
856
857         error = OSPPTransactionReportUsage(handle, difftime(end, connect), start, end, alert, connect, isPddInfoPresent, pdd,
858                                                 release, confId, 0, 0, 0, 0, &dummy, NULL);
859         if (error == OSPC_ERR_NO_ERROR) {
860                 ast_log(LOG_DEBUG, "OSP: Usage reported\n");
861                 res = 1;
862         } else {
863                 ast_log(LOG_DEBUG, "OSP: Unable to report usage, error '%d'\n", error);
864                 res = -1;
865         }
866         OSPPTransactionDelete(handle);
867
868         return res;
869 }
870
871 /* OSP Application APIs */
872
873 /*!
874  * \brief OSP Application OSPAuth
875  * \param chan Channel
876  * \param data Parameter
877  * \return 0 Success, -1 Failed
878  */
879 static int ospauth_exec(struct ast_channel* chan, void* data)
880 {
881         int res;
882         struct localuser* u;
883         const char* provider = OSP_DEF_PROVIDER;
884         int priority_jump = 0;
885         struct varshead* headp;
886         struct ast_var_t* current;
887         const char* source = "";
888         const char* token = "";
889         int handle;
890         unsigned int timelimit;
891         char buffer[OSP_INTSTR_SIZE];
892         const char* status;
893         char* tmp;
894
895         AST_DECLARE_APP_ARGS(args,
896                 AST_APP_ARG(provider);
897                 AST_APP_ARG(options);
898         );
899
900         LOCAL_USER_ADD(u);
901
902         if (!(tmp = ast_strdupa(data))) {
903                 ast_log(LOG_ERROR, "Out of memory\n");
904                 LOCAL_USER_REMOVE(u);
905                 return -1;
906         }
907
908         AST_STANDARD_APP_ARGS(args, tmp);
909
910         if (!ast_strlen_zero(args.provider)) {
911                 provider = args.provider;
912         }
913         ast_log(LOG_DEBUG, "OSPAuth: provider '%s'\n", provider);
914
915         if ((args.options) && (strchr(args.options, 'j'))) {
916                 priority_jump = 1;
917         }
918         ast_log(LOG_DEBUG, "OSPAuth: priority jump '%d'\n", priority_jump);
919
920         headp = &chan->varshead;
921         AST_LIST_TRAVERSE(headp, current, entries) {
922                 if (!strcasecmp(ast_var_name(current), "OSPPEERIP")) {
923                         source = ast_var_value(current);
924                 } else if (!strcasecmp(ast_var_name(current), "OSPINTOKEN")) {
925                         token = ast_var_value(current);
926                 }
927         }
928         ast_log(LOG_DEBUG, "OSPAuth: source '%s'\n", source);
929         ast_log(LOG_DEBUG, "OSPAuth: token size '%zd'\n", strlen(token));
930
931         
932         if ((res = osp_auth(provider, &handle, source, chan->cid.cid_num, chan->exten, token, &timelimit)) > 0) {
933                 status = AST_OSP_SUCCESS;
934         } else {
935                 timelimit = OSP_DEF_TIMELIMIT;
936                 if (!res) {
937                         status = AST_OSP_FAILED;
938                 } else {
939                         status = AST_OSP_ERROR;
940                 }
941         }
942
943         snprintf(buffer, sizeof(buffer), "%d", handle);
944         pbx_builtin_setvar_helper(chan, "OSPINHANDLE", buffer);
945         ast_log(LOG_DEBUG, "OSPAuth: OSPINHANDLE '%s'\n", buffer);
946         snprintf(buffer, sizeof(buffer), "%d", timelimit);
947         pbx_builtin_setvar_helper(chan, "OSPINTIMELIMIT", buffer);
948         ast_log(LOG_DEBUG, "OSPAuth: OSPINTIMELIMIT '%s'\n", buffer);
949         pbx_builtin_setvar_helper(chan, "OSPAUTHSTATUS", status);
950         ast_log(LOG_DEBUG, "OSPAuth: %s\n", status);
951
952         if(res <= 0) {
953                 if (priority_jump || ast_opt_priority_jumping) {
954                         ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101);
955                         res = 0;
956                 } else {
957                         res = -1;
958                 }
959         } else {
960                 res = 0;
961         }
962
963         LOCAL_USER_REMOVE(u);
964
965         return res;
966 }
967
968 /*!
969  * \brief OSP Application OSPLookup
970  * \param chan Channel
971  * \param data Parameter
972  * \return 0 Success, -1 Failed
973  */
974 static int osplookup_exec(struct ast_channel* chan, void* data)
975 {
976         int res, cres;
977         struct localuser* u;
978         const char* provider = OSP_DEF_PROVIDER;
979         int priority_jump = 0;
980         struct varshead* headp;
981         struct ast_var_t* current;
982         const char* srcdev = "";
983         char buffer[OSP_TOKSTR_SIZE];
984         struct osp_result result;
985         const char* status;
986         char* tmp;
987
988         AST_DECLARE_APP_ARGS(args,
989                 AST_APP_ARG(exten);
990                 AST_APP_ARG(provider);
991                 AST_APP_ARG(options);
992         );
993         
994         if (ast_strlen_zero(data)) {
995                 ast_log(LOG_WARNING, "OSPLookup: Arg required, OSPLookup(exten[|provider[|options]])\n");
996                 return -1;
997         }
998
999         LOCAL_USER_ADD(u);
1000
1001         if (!(tmp = ast_strdupa(data))) {
1002                 ast_log(LOG_ERROR, "Out of memory\n");
1003                 LOCAL_USER_REMOVE(u);
1004                 return -1;
1005         }
1006
1007         AST_STANDARD_APP_ARGS(args, tmp);
1008
1009         ast_log(LOG_DEBUG, "OSPLookup: exten '%s'\n", args.exten);
1010
1011         if (!ast_strlen_zero(args.provider)) {
1012                 provider = args.provider;
1013         }
1014         ast_log(LOG_DEBUG, "OSPlookup: provider '%s'\n", provider);
1015
1016         if ((args.options) && (strchr(args.options, 'j'))) {
1017                 priority_jump = 1;
1018         }
1019         ast_log(LOG_DEBUG, "OSPLookup: priority jump '%d'\n", priority_jump);
1020
1021         result.inhandle = OSP_INVALID_HANDLE;
1022         result.intimelimit = OSP_DEF_TIMELIMIT;
1023
1024         headp = &chan->varshead;
1025         AST_LIST_TRAVERSE(headp, current, entries) {
1026                 if (!strcasecmp(ast_var_name(current), "OSPINHANDLE")) {
1027                         if (sscanf(ast_var_value(current), "%d", &result.inhandle) != 1) {
1028                                 result.inhandle = OSP_INVALID_HANDLE;
1029                         }
1030                 } else if (!strcasecmp(ast_var_name(current), "OSPINTIMELIMIT")) {
1031                         if (sscanf(ast_var_value(current), "%d", &result.intimelimit) != 1) {
1032                                 result.intimelimit = OSP_DEF_TIMELIMIT;
1033                         }
1034                 } else if (!strcasecmp(ast_var_name(current), "OSPPEERIP")) {
1035                         srcdev = ast_var_value(current);
1036                 }
1037         }
1038         ast_log(LOG_DEBUG, "OSPLookup: OSPINHANDLE '%d'\n", result.inhandle);
1039         ast_log(LOG_DEBUG, "OSPLookup: OSPINTIMELIMIT '%d'\n", result.intimelimit);
1040         ast_log(LOG_DEBUG, "OSPLookup: source device '%s'\n", srcdev);
1041         
1042         if ((cres = ast_autoservice_start(chan)) < 0) {
1043                 LOCAL_USER_REMOVE(u);
1044                 return -1;
1045         }
1046
1047         if ((res = osp_lookup(provider, srcdev, chan->cid.cid_num, args.exten, &result)) > 0) {
1048                 status = AST_OSP_SUCCESS;
1049         } else {
1050                 result.tech[0] = '\0';
1051                 result.dest[0] = '\0';
1052                 result.calling[0] = '\0';
1053                 result.token[0] = '\0'; 
1054                 result.numresults = 0;
1055                 result.outtimelimit = OSP_DEF_TIMELIMIT;
1056                 if (!res) {
1057                         status = AST_OSP_FAILED;
1058                 } else {
1059                         status = AST_OSP_ERROR;
1060                 }
1061         }
1062
1063         snprintf(buffer, sizeof(buffer), "%d", result.outhandle);
1064         pbx_builtin_setvar_helper(chan, "OSPOUTHANDLE", buffer);
1065         ast_log(LOG_DEBUG, "OSPLookup: OSPOUTHANDLE '%s'\n", buffer);
1066         pbx_builtin_setvar_helper(chan, "OSPTECH", result.tech);
1067         ast_log(LOG_DEBUG, "OSPLookup: OSPTECH '%s'\n", result.tech);
1068         pbx_builtin_setvar_helper(chan, "OSPDEST", result.dest);
1069         ast_log(LOG_DEBUG, "OSPLookup: OSPDEST '%s'\n", result.dest);
1070         pbx_builtin_setvar_helper(chan, "OSPCALLING", result.calling);
1071         ast_log(LOG_DEBUG, "OSPLookup: OSPCALLING '%s'\n", result.calling);
1072         pbx_builtin_setvar_helper(chan, "OSPOUTTOKEN", result.token);
1073         ast_log(LOG_DEBUG, "OSPLookup: OSPOUTTOKEN size '%zd'\n", strlen(result.token));
1074         snprintf(buffer, sizeof(buffer), "%d", result.numresults);
1075         pbx_builtin_setvar_helper(chan, "OSPRESULTS", buffer);
1076         ast_log(LOG_DEBUG, "OSPLookup: OSPRESULTS '%s'\n", buffer);
1077         snprintf(buffer, sizeof(buffer), "%d", result.outtimelimit);
1078         pbx_builtin_setvar_helper(chan, "OSPOUTTIMELIMIT", buffer);
1079         ast_log(LOG_DEBUG, "OSPLookup: OSPOUTTIMELIMIT '%s'\n", buffer);
1080         pbx_builtin_setvar_helper(chan, "OSPLOOKUPSTATUS", status);
1081         ast_log(LOG_DEBUG, "OSPLookup: %s\n", status);
1082
1083         if (!strcasecmp(result.tech, "SIP")) {
1084                 if (!ast_strlen_zero(result.token)) {
1085                         snprintf(buffer, sizeof(buffer), "P-OSP-Auth-Token: %s", result.token);
1086                         pbx_builtin_setvar_helper(chan, "_SIPADDHEADER", buffer);
1087                         ast_log(LOG_DEBUG, "OSPLookup: SIPADDHEADER size '%zd'\n", strlen(buffer));
1088                 }
1089         } else if (!strcasecmp(result.tech, "H323")) {
1090         } else if (!strcasecmp(result.tech, "IAX")) {
1091         }
1092
1093         if ((cres = ast_autoservice_stop(chan)) < 0) {
1094                 LOCAL_USER_REMOVE(u);
1095                 return -1;
1096         }
1097
1098         if(res <= 0) {
1099                 if (priority_jump || ast_opt_priority_jumping) {
1100                         ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101);
1101                         res = 0;
1102                 } else {
1103                         res = -1;
1104                 }
1105         } else {
1106                 res = 0;
1107         }
1108
1109         LOCAL_USER_REMOVE(u);
1110
1111         return res;
1112 }
1113
1114 /*!
1115  * \brief OSP Application OSPNext
1116  * \param chan Channel
1117  * \param data Parameter
1118  * \return 0 Success, -1 Failed
1119  */
1120 static int ospnext_exec(struct ast_channel* chan, void* data)
1121 {
1122         int res;
1123         struct localuser* u;
1124         int priority_jump = 0;
1125         int cause = 0;
1126         struct varshead* headp;
1127         struct ast_var_t* current;
1128         struct osp_result result;
1129         char buffer[OSP_TOKSTR_SIZE];
1130         const char* status;
1131         char* tmp;
1132
1133         AST_DECLARE_APP_ARGS(args,
1134                 AST_APP_ARG(cause);
1135                 AST_APP_ARG(options);
1136         );
1137         
1138         if (ast_strlen_zero(data)) {
1139                 ast_log(LOG_WARNING, "OSPNext: Arg required, OSPNext(cause[|options])\n");
1140                 return -1;
1141         }
1142
1143         LOCAL_USER_ADD(u);
1144
1145         if (!(tmp = ast_strdupa(data))) {
1146                 ast_log(LOG_ERROR, "Out of memory\n");
1147                 LOCAL_USER_REMOVE(u);
1148                 return -1;
1149         }
1150
1151         AST_STANDARD_APP_ARGS(args, tmp);
1152
1153         if (!ast_strlen_zero(args.cause) && sscanf(args.cause, "%d", &cause) != 1) {
1154                 cause = 0;
1155         }
1156         ast_log(LOG_DEBUG, "OSPNext: cause '%d'\n", cause);
1157
1158         if ((args.options) && (strchr(args.options, 'j'))) {
1159                 priority_jump = 1;
1160         }
1161         ast_log(LOG_DEBUG, "OSPNext: priority jump '%d'\n", priority_jump);
1162
1163         result.inhandle = OSP_INVALID_HANDLE;
1164         result.outhandle = OSP_INVALID_HANDLE;
1165         result.intimelimit = OSP_DEF_TIMELIMIT;
1166         result.numresults = 0;
1167
1168         headp = &chan->varshead;
1169         AST_LIST_TRAVERSE(headp, current, entries) {
1170                 if (!strcasecmp(ast_var_name(current), "OSPINHANDLE")) {
1171                         if (sscanf(ast_var_value(current), "%d", &result.inhandle) != 1) {
1172                                 result.inhandle = OSP_INVALID_HANDLE;
1173                         }
1174                 } else if (!strcasecmp(ast_var_name(current), "OSPOUTHANDLE")) {
1175                         if (sscanf(ast_var_value(current), "%d", &result.outhandle) != 1) {
1176                                 result.outhandle = OSP_INVALID_HANDLE;
1177                         }
1178                 } else if (!strcasecmp(ast_var_name(current), "OSPINTIMELIMIT")) {
1179                         if (sscanf(ast_var_value(current), "%d", &result.intimelimit) != 1) {
1180                                 result.intimelimit = OSP_DEF_TIMELIMIT;
1181                         }
1182                 } else if (!strcasecmp(ast_var_name(current), "OSPRESULTS")) {
1183                         if (sscanf(ast_var_value(current), "%d", &result.numresults) != 1) {
1184                                 result.numresults = 0;
1185                         }
1186                 }
1187         }
1188         ast_log(LOG_DEBUG, "OSPNext: OSPINHANDLE '%d'\n", result.inhandle);
1189         ast_log(LOG_DEBUG, "OSPNext: OSPOUTHANDLE '%d'\n", result.outhandle);
1190         ast_log(LOG_DEBUG, "OSPNext: OSPINTIMELIMIT '%d'\n", result.intimelimit);
1191         ast_log(LOG_DEBUG, "OSPNext: OSPRESULTS '%d'\n", result.numresults);
1192
1193         if ((res = osp_next(cause, &result)) > 0) {
1194                 status = AST_OSP_SUCCESS;
1195         } else {
1196                 result.tech[0] = '\0';
1197                 result.dest[0] = '\0';
1198                 result.calling[0] = '\0';
1199                 result.token[0] = '\0'; 
1200                 result.numresults = 0;
1201                 result.outtimelimit = OSP_DEF_TIMELIMIT;
1202                 if (!res) {
1203                         status = AST_OSP_FAILED;
1204                 } else {
1205                         status = AST_OSP_ERROR;
1206                 }
1207         }
1208
1209         pbx_builtin_setvar_helper(chan, "OSPTECH", result.tech);
1210         ast_log(LOG_DEBUG, "OSPNext: OSPTECH '%s'\n", result.tech);
1211         pbx_builtin_setvar_helper(chan, "OSPDEST", result.dest);
1212         ast_log(LOG_DEBUG, "OSPNext: OSPDEST '%s'\n", result.dest);
1213         pbx_builtin_setvar_helper(chan, "OSPCALLING", result.calling);
1214         ast_log(LOG_DEBUG, "OSPNext: OSPCALLING '%s'\n", result.calling);
1215         pbx_builtin_setvar_helper(chan, "OSPOUTTOKEN", result.token);
1216         ast_log(LOG_DEBUG, "OSPNext: OSPOUTTOKEN size '%zd'\n", strlen(result.token));
1217         snprintf(buffer, sizeof(buffer), "%d", result.numresults);
1218         pbx_builtin_setvar_helper(chan, "OSPRESULTS", buffer);
1219         ast_log(LOG_DEBUG, "OSPNext: OSPRESULTS '%s'\n", buffer);
1220         snprintf(buffer, sizeof(buffer), "%d", result.outtimelimit);
1221         pbx_builtin_setvar_helper(chan, "OSPOUTTIMELIMIT", buffer);
1222         ast_log(LOG_DEBUG, "OSPNext: OSPOUTTIMELIMIT '%s'\n", buffer);
1223         pbx_builtin_setvar_helper(chan, "OSPNEXTSTATUS", status);
1224         ast_log(LOG_DEBUG, "OSPNext: %s\n", status);
1225
1226         if (!strcasecmp(result.tech, "SIP")) {
1227                 if (!ast_strlen_zero(result.token)) {
1228                         snprintf(buffer, sizeof(buffer), "P-OSP-Auth-Token: %s", result.token);
1229                         pbx_builtin_setvar_helper(chan, "_SIPADDHEADER", buffer);
1230                         ast_log(LOG_DEBUG, "OSPLookup: SIPADDHEADER size '%zd'\n", strlen(buffer));
1231                 }
1232         } else if (!strcasecmp(result.tech, "H323")) {
1233         } else if (!strcasecmp(result.tech, "IAX")) {
1234         }
1235
1236         if(res <= 0) {
1237                 if (priority_jump || ast_opt_priority_jumping) {
1238                         ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101);
1239                         res = 0;
1240                 } else {
1241                         res = -1;
1242                 }
1243         } else {
1244                 res = 0;
1245         }
1246
1247         LOCAL_USER_REMOVE(u);
1248
1249         return res;
1250 }
1251
1252 /*!
1253  * \brief OSP Application OSPFinish
1254  * \param chan Channel
1255  * \param data Parameter
1256  * \return 0 Success, -1 Failed
1257  */
1258 static int ospfinished_exec(struct ast_channel* chan, void* data)
1259 {
1260         int res = 1;
1261         struct localuser* u;
1262         int priority_jump = 0;
1263         int cause = 0;
1264         struct varshead* headp;
1265         struct ast_var_t* current;
1266         int inhandle = OSP_INVALID_HANDLE;
1267         int outhandle = OSP_INVALID_HANDLE;
1268         int recorded = 0;
1269         time_t start, connect, end;
1270         unsigned int release;
1271         char buffer[OSP_INTSTR_SIZE];
1272         const char* status;
1273         char* tmp;
1274
1275         AST_DECLARE_APP_ARGS(args,
1276                 AST_APP_ARG(cause);
1277                 AST_APP_ARG(options);
1278         );
1279         
1280         LOCAL_USER_ADD(u);
1281
1282         if (!(tmp = ast_strdupa(data))) {
1283                 ast_log(LOG_ERROR, "Out of memory\n");
1284                 LOCAL_USER_REMOVE(u);
1285                 return -1;
1286         }
1287
1288         AST_STANDARD_APP_ARGS(args, tmp);
1289
1290         if ((args.options) && (strchr(args.options, 'j'))) {
1291                 priority_jump = 1;
1292         }
1293         ast_log(LOG_DEBUG, "OSPFinish: priority jump '%d'\n", priority_jump);
1294
1295         headp = &chan->varshead;
1296         AST_LIST_TRAVERSE(headp, current, entries) {
1297                 if (!strcasecmp(ast_var_name(current), "OSPINHANDLE")) {
1298                         if (sscanf(ast_var_value(current), "%d", &inhandle) != 1) {
1299                                 inhandle = OSP_INVALID_HANDLE;
1300                         }
1301                 } else if (!strcasecmp(ast_var_name(current), "OSPOUTHANDLE")) {
1302                         if (sscanf(ast_var_value(current), "%d", &outhandle) != 1) {
1303                                 outhandle = OSP_INVALID_HANDLE;
1304                         }
1305                 } else if (!recorded &&
1306                         (!strcasecmp(ast_var_name(current), "OSPAUTHSTATUS") ||
1307                         !strcasecmp(ast_var_name(current), "OSPLOOKUPSTATUS") || 
1308                         !strcasecmp(ast_var_name(current), "OSPNEXTSTATUS"))) 
1309                 {
1310                         if (strcasecmp(ast_var_value(current), AST_OSP_SUCCESS)) {
1311                                 recorded = 1;
1312                         }
1313                 }
1314         }
1315         ast_log(LOG_DEBUG, "OSPFinish: OSPINHANDLE '%d'\n", inhandle);
1316         ast_log(LOG_DEBUG, "OSPFinish: OSPOUTHANDLE '%d'\n", outhandle);
1317         ast_log(LOG_DEBUG, "OSPFinish: recorded '%d'\n", recorded);
1318
1319         if (!ast_strlen_zero(args.cause) && sscanf(args.cause, "%d", &cause) != 1) {
1320                 cause = 0;
1321         }
1322         ast_log(LOG_DEBUG, "OSPFinish: cause '%d'\n", cause);
1323
1324         if (chan->cdr) {
1325                 start = chan->cdr->start.tv_sec;
1326                 connect = chan->cdr->answer.tv_sec;
1327                 if (connect) {
1328                         end = time(NULL);
1329                 } else {
1330                         end = connect;
1331                 }
1332         } else {
1333                 start = 0;
1334                 connect = 0;
1335                 end = 0;
1336         }
1337         ast_log(LOG_DEBUG, "OSPFinish: start '%ld'\n", start);
1338         ast_log(LOG_DEBUG, "OSPFinish: connect '%ld'\n", connect);
1339         ast_log(LOG_DEBUG, "OSPFinish: end '%ld'\n", end);
1340
1341         release = chan->_softhangup ? 0 : 1;
1342
1343         if (osp_finish(outhandle, recorded, cause, start, connect, end, release) <= 0) {
1344                 ast_log(LOG_DEBUG, "OSPFinish: Unable to report usage for outbound call\n");
1345         }
1346         switch (cause) {
1347                 case AST_CAUSE_NORMAL_CLEARING:
1348                         break;
1349                 default:
1350                         cause = AST_CAUSE_NO_ROUTE_DESTINATION;
1351                         break;
1352         }
1353         if (osp_finish(inhandle, recorded, cause, start, connect, end, release) <= 0) {
1354                 ast_log(LOG_DEBUG, "OSPFinish: Unable to report usage for inbound call\n");
1355         }
1356         snprintf(buffer, sizeof(buffer), "%d", OSP_INVALID_HANDLE);
1357         pbx_builtin_setvar_helper(chan, "OSPOUTHANDLE", buffer);
1358         pbx_builtin_setvar_helper(chan, "OSPINHANDLE", buffer);
1359
1360         if (res > 0) {
1361                 status = AST_OSP_SUCCESS;
1362         } else if (!res) {
1363                 status = AST_OSP_FAILED;
1364         } else {
1365                 status = AST_OSP_ERROR;
1366         }
1367         pbx_builtin_setvar_helper(chan, "OSPFINISHSTATUS", status);
1368
1369         if(!res) {
1370                 if (priority_jump || ast_opt_priority_jumping) {
1371                         ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101);
1372                         res = 0;
1373                 } else {
1374                         res = -1;
1375                 }
1376         } else {
1377                 res = 0;
1378         }
1379
1380         LOCAL_USER_REMOVE(u);
1381
1382         return res;
1383 }
1384
1385 /* OSP Module APIs */
1386
1387 static int osp_load(void)
1388 {
1389         char* t;
1390         unsigned int v;
1391         struct ast_config* cfg;
1392         int error = OSPC_ERR_NO_ERROR;
1393
1394         cfg = ast_config_load(OSP_CONFIG_FILE);
1395         if (cfg) {
1396                 t = ast_variable_retrieve(cfg, OSP_GENERAL_CAT, "accelerate");
1397                 if (t && ast_true(t)) {
1398                         if ((error = OSPPInit(1)) != OSPC_ERR_NO_ERROR) {
1399                                 ast_log(LOG_WARNING, "OSP: Unable to enable hardware accelleration\n");
1400                                 OSPPInit(0);
1401                         } else {
1402                                 osp_hardware = 1;
1403                         }
1404                 } else {
1405                         OSPPInit(0);
1406                 }
1407                 ast_log(LOG_DEBUG, "OSP: osp_hardware '%d'\n", osp_hardware);
1408
1409                 t = ast_variable_retrieve(cfg, OSP_GENERAL_CAT, "tokenformat");
1410                 if (t) {
1411                         if ((sscanf(t, "%d", &v) == 1) && 
1412                                 ((v == TOKEN_ALGO_SIGNED) || (v == TOKEN_ALGO_UNSIGNED) || (v == TOKEN_ALGO_BOTH))) 
1413                         {
1414                                 osp_tokenformat = v;
1415                         } else {
1416                                 ast_log(LOG_WARNING, "tokenformat should be an integer from %d, %d or %d, not '%s'\n", 
1417                                         TOKEN_ALGO_SIGNED, TOKEN_ALGO_UNSIGNED, TOKEN_ALGO_BOTH, t);
1418                         }
1419                 }
1420                 ast_log(LOG_DEBUG, "OSP: osp_tokenformat '%d'\n", osp_tokenformat);
1421
1422                 t = ast_category_browse(cfg, NULL);
1423                 while(t) {
1424                         if (strcasecmp(t, OSP_GENERAL_CAT)) {
1425                                 osp_create_provider(cfg, t);
1426                         }
1427                         t = ast_category_browse(cfg, t);
1428                 }
1429
1430                 osp_initialized = 1;
1431
1432                 ast_config_destroy(cfg);
1433         } else {
1434                 ast_log(LOG_WARNING, "OSP: Unable to find configuration. OSP support disabled\n");
1435         }
1436         ast_log(LOG_DEBUG, "OSP: osp_initialized '%d'\n", osp_initialized);
1437
1438         return 0;
1439 }
1440
1441 static int osp_unload(void)
1442 {
1443         struct osp_provider* p;
1444         struct osp_provider* next;
1445
1446         if (osp_initialized) {
1447                 ast_mutex_lock(&osplock);
1448                 p = ospproviders;
1449                 while(p) {
1450                         next = p->next;
1451                         OSPPProviderDelete(p->handle, 0);
1452                         free(p);
1453                         p = next;
1454                 }
1455                 ospproviders = NULL;
1456                 ast_mutex_unlock(&osplock);
1457
1458                 OSPPCleanup();
1459
1460                 osp_tokenformat = TOKEN_ALGO_SIGNED;
1461                 osp_hardware = 0;
1462                 osp_initialized = 0;
1463         }
1464         return 0;
1465 }
1466
1467 static int osp_show(int fd, int argc, char* argv[])
1468 {
1469         int i;
1470         int found = 0;
1471         struct osp_provider* p;
1472         const char* provider = NULL;
1473         const char* tokenalgo;
1474
1475         if ((argc < 2) || (argc > 3)) {
1476                 return RESULT_SHOWUSAGE;
1477         }
1478         if (argc > 2) {
1479                 provider = argv[2];
1480         }
1481         if (!provider) {
1482                 switch (osp_tokenformat) {
1483                         case TOKEN_ALGO_BOTH:
1484                                 tokenalgo = "Both";
1485                                 break;
1486                         case TOKEN_ALGO_UNSIGNED:
1487                                 tokenalgo = "Unsigned";
1488                                 break;
1489                         case TOKEN_ALGO_SIGNED:
1490                         default:
1491                                 tokenalgo = "Signed";
1492                                 break;
1493                 }
1494                 ast_cli(fd, "OSP: %s %s %s\n", 
1495                         osp_initialized ? "Initialized" : "Uninitialized", osp_hardware ? "Accelerated" : "Normal", tokenalgo);
1496         }
1497
1498         ast_mutex_lock(&osplock);
1499         p = ospproviders;
1500         while(p) {
1501                 if (!provider || !strcasecmp(p->name, provider)) {
1502                         if (found) {
1503                                 ast_cli(fd, "\n");
1504                         }
1505                         ast_cli(fd, " == OSP Provider '%s' == \n", p->name);
1506                         ast_cli(fd, "Local Private Key: %s\n", p->privatekey);
1507                         ast_cli(fd, "Local Certificate: %s\n", p->localcert);
1508                         for (i = 0; i < p->cacount; i++) {
1509                                 ast_cli(fd, "CA Certificate %d:  %s\n", i + 1, p->cacerts[i]);
1510                         }
1511                         for (i = 0; i < p->spcount; i++) {
1512                                 ast_cli(fd, "Service Point %d:   %s\n", i + 1, p->srvpoints[i]);
1513                         }
1514                         ast_cli(fd, "Max Connections:   %d\n", p->maxconnections);
1515                         ast_cli(fd, "Retry Delay:       %d seconds\n", p->retrydelay);
1516                         ast_cli(fd, "Retry Limit:       %d\n", p->retrylimit);
1517                         ast_cli(fd, "Timeout:           %d milliseconds\n", p->timeout);
1518                         ast_cli(fd, "Source:            %s\n", strlen(p->source) ? p->source : "<unspecified>");
1519                         ast_cli(fd, "Auth Policy        %d\n", p->authpolicy);
1520                         ast_cli(fd, "OSP Handle:        %d\n", p->handle);
1521                         found++;
1522                 }
1523                 p = p->next;
1524         }
1525         ast_mutex_unlock(&osplock);
1526
1527         if (!found) {
1528                 if (provider) {
1529                         ast_cli(fd, "Unable to find OSP provider '%s'\n", provider);
1530                 } else {
1531                         ast_cli(fd, "No OSP providers configured\n");
1532                 }
1533         }
1534         return RESULT_SUCCESS;
1535 }
1536
1537 static const char* app1= "OSPAuth";
1538 static const char* synopsis1 = "OSP authentication";
1539 static const char* descrip1 = 
1540 "  OSPAuth([provider[|options]]):  Authenticate a SIP INVITE by OSP and sets\n"
1541 "the variables:\n"
1542 " ${OSPINHANDLE}:  The inbound call transaction handle\n"
1543 " ${OSPINTIMELIMIT}:  The inbound call duration limit in seconds\n"
1544 "\n"
1545 "The option string may contain the following character:\n"
1546 "       'j' -- jump to n+101 priority if the authentication was NOT successful\n"
1547 "This application sets the following channel variable upon completion:\n"
1548 "       OSPAUTHSTATUS   The status of the OSP Auth attempt as a text string, one of\n"
1549 "               SUCCESS | FAILED | ERROR\n";
1550
1551 static const char* app2= "OSPLookup";
1552 static const char* synopsis2 = "Lookup destination by OSP";
1553 static const char* descrip2 = 
1554 "  OSPLookup(exten[|provider[|options]]):  Looks up an extension via OSP and sets\n"
1555 "the variables, where 'n' is the number of the result beginning with 1:\n"
1556 " ${OSPOUTHANDLE}:  The OSP Handle for anything remaining\n"
1557 " ${OSPTECH}:  The technology to use for the call\n"
1558 " ${OSPDEST}:  The destination to use for the call\n"
1559 " ${OSPCALLING}:  The calling number to use for the call\n"
1560 " ${OSPOUTTOKEN}:  The actual OSP token as a string\n"
1561 " ${OSPOUTTIMELIMIT}:  The outbound call duration limit in seconds\n"
1562 " ${OSPRESULTS}:  The number of OSP results total remaining\n"
1563 "\n"
1564 "The option string may contain the following character:\n"
1565 "       'j' -- jump to n+101 priority if the lookup was NOT successful\n"
1566 "This application sets the following channel variable upon completion:\n"
1567 "       OSPLOOKUPSTATUS The status of the OSP Lookup attempt as a text string, one of\n"
1568 "               SUCCESS | FAILED | ERROR\n";
1569
1570 static const char* app3 = "OSPNext";
1571 static const char* synopsis3 = "Lookup next destination by OSP";
1572 static const char* descrip3 = 
1573 "  OSPNext(cause[|options]):  Looks up the next OSP Destination for ${OSPOUTHANDLE}\n"
1574 "See OSPLookup for more information\n"
1575 "\n"
1576 "The option string may contain the following character:\n"
1577 "       'j' -- jump to n+101 priority if the lookup was NOT successful\n"
1578 "This application sets the following channel variable upon completion:\n"
1579 "       OSPNEXTSTATUS   The status of the OSP Next attempt as a text string, one of\n"
1580 "               SUCCESS | FAILED |ERROR\n";
1581
1582 static const char* app4 = "OSPFinish";
1583 static const char* synopsis4 = "Record OSP entry";
1584 static const char* descrip4 = 
1585 "  OSPFinish([status[|options]]):  Records call state for ${OSPINHANDLE}, according to\n"
1586 "status, which should be one of BUSY, CONGESTION, ANSWER, NOANSWER, or CHANUNAVAIL\n"
1587 "or coincidentally, just what the Dial application stores in its ${DIALSTATUS}.\n"
1588 "\n"
1589 "The option string may contain the following character:\n"
1590 "       'j' -- jump to n+101 priority if the finish attempt was NOT successful\n"
1591 "This application sets the following channel variable upon completion:\n"
1592 "       OSPFINISHSTATUS The status of the OSP Finish attempt as a text string, one of\n"
1593 "               SUCCESS | FAILED |ERROR \n";
1594
1595 static const char osp_usage[] =
1596 "Usage: osp show\n"
1597 "       Displays information on Open Settlement Protocol support\n";
1598
1599 static struct ast_cli_entry osp_cli = {
1600         {"osp", "show", NULL}, 
1601         osp_show, 
1602         "Displays OSP information", 
1603         osp_usage 
1604 };
1605
1606 LOCAL_USER_DECL;
1607
1608 static int load_module(void* mod)
1609 {
1610         int res;
1611         
1612         osp_load();
1613         res = ast_cli_register(&osp_cli);
1614         res |= ast_register_application(app1, ospauth_exec, synopsis1, descrip1);
1615         res |= ast_register_application(app2, osplookup_exec, synopsis2, descrip2);
1616         res |= ast_register_application(app3, ospnext_exec, synopsis3, descrip3);
1617         res |= ast_register_application(app4, ospfinished_exec, synopsis4, descrip4);
1618
1619         return res;
1620 }
1621
1622 static int unload_module(void* mod)
1623 {
1624         int res;
1625         
1626         res = ast_unregister_application(app4);
1627         res |= ast_unregister_application(app3);
1628         res |= ast_unregister_application(app2);
1629         res |= ast_unregister_application(app1);
1630         res |= ast_cli_unregister(&osp_cli);
1631         osp_unload();
1632
1633         STANDARD_HANGUP_LOCALUSERS;
1634
1635         return res;
1636 }
1637
1638 static int reload(void* mod)
1639 {
1640         osp_unload();
1641         osp_load();
1642         return 0;
1643 }
1644
1645 static const char* description(void)
1646 {
1647         return "Open Settlement Protocol Applications";
1648 }
1649
1650 static const char* key(void)
1651 {
1652         return ASTERISK_GPL_KEY;
1653 }
1654
1655 STD_MOD(MOD_1, reload, NULL, NULL);