Răsfoiți Sursa

* Just the call-control module from OpenSIPS ported to Sip-Router

Raul Alexis Betancor Santana 16 ani în urmă
părinte
comite
b8d12a322f

+ 16 - 0
modules_k/call_control/Makefile

@@ -0,0 +1,16 @@
+# $Id: Makefile,v 1.1 2005/12/12 08:57:22 dan Exp $
+#
+# call_control module makefile
+#
+# 
+# WARNING: do not run this directly, it should be run by the master Makefile
+
+include ../../Makefile.defs
+auto_gen=
+NAME=call_control.so
+LIBS=
+DEFS+=-DOPENSER_MOD_INTERFACE
+
+
+include ../../Makefile.modules
+

+ 354 - 0
modules_k/call_control/README

@@ -0,0 +1,354 @@
+Call Control Module
+
+Dan Pascu
+
+   <[email protected]>
+
+Edited by
+
+Dan Pascu
+
+   <[email protected]>
+
+   Copyright © 2005-2008 Dan Pascu
+   Revision History
+   Revision $Revision: 1 $ $Date: 2008-12-17 13:05:29 +0200 (Wed, 17 Dec
+                           2008) $
+     __________________________________________________________________
+
+   Table of Contents
+
+   1. Admin Guide
+
+        1. Overview
+        2. Description
+        3. Features
+        4. Dependencies
+
+              4.1. Kamailio Modules
+              4.2. External Libraries or Applications
+
+        5. Exported parameters
+
+              5.1. disable (int)
+              5.2. socket_name (string)
+              5.3. socket_timeout (int)
+              5.4. signaling_ip_avp (string)
+              5.5. canonical_uri_avp (string)
+              5.6. diverter_avp_id (string)
+
+        6. Exported Functions
+
+              6.1. call_control()
+
+   List of Examples
+
+   1.1. Setting the disable parameter
+   1.2. Setting the socket_name parameter
+   1.3. Setting the socket_timeout parameter
+   1.4. Setting the signaling_ip_avp parameter
+   1.5. Setting the canonical_uri_avp parameter
+   1.6. Setting the diverter_avp_id parameter
+   1.7. Using the call_control function
+
+Chapter 1. Admin Guide
+
+   Table of Contents
+
+   1. Overview
+   2. Description
+   3. Features
+   4. Dependencies
+
+        4.1. Kamailio Modules
+        4.2. External Libraries or Applications
+
+   5. Exported parameters
+
+        5.1. disable (int)
+        5.2. socket_name (string)
+        5.3. socket_timeout (int)
+        5.4. signaling_ip_avp (string)
+        5.5. canonical_uri_avp (string)
+        5.6. diverter_avp_id (string)
+
+   6. Exported Functions
+
+        6.1. call_control()
+
+1. Overview
+
+   This module allows one to limit the duration of calls and automatically
+   end them when they exceed the imposed limit. Its main use case is to
+   implement a prepaid system, but it can also be used to impose a global
+   limit on all calls processed by the proxy.
+
+2. Description
+
+   Callcontrol consists of 3 components:
+     * The Kamailio call_control module
+     * An external application called callcontrol which keeps track of the
+       calls that have a time limit and automatically ends them when they
+       exceed it. This application receives requests from Kamailio and
+       makes requests to a rating engine (see below) to find out if a call
+       needs to be limited or not. When a call ends (or is ended) it will
+       also instruct the rating engine to debit the balance for the caller
+       with the consumed amount. The callcontrol application is available
+       from http://callcontrol.ag-projects.com/
+     * A rating engine that is used to calculate the time limit based on
+       the caller's credit and the destination price and to debit the
+       caller's balance after a call ends. This is available as part of
+       CDRTool from http://cdrtool.ag-projects.com/
+
+   The callcontrol application runs on the same machine as Kamailio and
+   they communicate over a filesystem socket, while the rating engine can
+   run on a different host and communicates with the callcontrol
+   application using a TCP connection.
+
+   Callcontrol is invoked by calling the call_control() function for the
+   initial INVITE of every call we want to apply a limit to. This will end
+   up as a request to the callcontrol application, which will interogate
+   the rating engine for a time limit for the given caller and
+   destination. The rating engine will determine if the destination has
+   any associated cost and if the caller has any credit limit and if so
+   will return the amount of time he is allowed to call that destination.
+   Otherwise it will indicate that there is no limit associated with the
+   call. If there is a limit, the callcontrol application will retain the
+   session and attach a timer to it that will expire after the given time
+   causing it to call back to Kamailio with a request to end the dialog.
+   If the rating engine returns that there is no limit for the call, the
+   session is discarded by the callcontrol application and it will allow
+   it to go proceed any limit. An appropriate response is returned to the
+   call_control module that is then returned by the call_control()
+   function call and allows the script to make a decision based on the
+   answer.
+
+3. Features
+
+     * Very simple API consisting of a single function that needs to be
+       called once for the first INVITE of every call. The rest is done
+       automatically in the background using dialog callbacks.
+     * Gracefully end dialogs when they exceed their time by triggering a
+       dlg_end_dlg request into the dialog module, that will generate two
+       BYE messages towards each endpoint, ending the call cleanly.
+     * Allow parallel sessions using one balance per subscriber
+     * Integrates with mediaproxy's ability to detect when a call does
+       timeout sending media and is closed. In this case the dlg_end_dlg
+       that is triggered by mediaproxy will end the callcontrol session
+       before it reaches the limit and consumes all the credit for a call
+       that died and didn't actually take place. For this mediaproxy has
+       to be used and it has to be started by engage_media_proxy() to be
+       able to keep track of the call's dialog and end it on timeout.
+       Even when mediaproxy is unable to end the dialog because it was not
+       started with engage_media_proxy(), the callcantrol application is
+       still able to detect calls that did timeout sending media, by
+       looking in the radius accounting records for entries recorded by
+       mediaproxy for calls that did timeout. These calls will also be
+       ended gracefully by the callcontrol application itself.
+
+4. Dependencies
+
+   4.1. Kamailio Modules
+   4.2. External Libraries or Applications
+
+4.1. Kamailio Modules
+
+   The following modules must be loaded before this module:
+     * dialog module
+
+4.2. External Libraries or Applications
+
+   The following libraries or applications must be installed before
+   running Kamailio with this module loaded:
+     * None.
+
+5. Exported parameters
+
+   5.1. disable (int)
+   5.2. socket_name (string)
+   5.3. socket_timeout (int)
+   5.4. signaling_ip_avp (string)
+   5.5. canonical_uri_avp (string)
+   5.6. diverter_avp_id (string)
+
+5.1. disable (int)
+
+   Boolean flag that specifies if callcontrol should be disabled. This is
+   useful when you want to use the same Kamailio configuration in two
+   different context, one using callcontrol, the other not. In the case
+   callcontrol is disabled, calls to the call_control() function will
+   return a code indicating that there is no limit associated with the
+   call, allowing the use of the same configuration without changes.
+
+   Default value is "0".
+
+   Example 1.1. Setting the disable parameter
+...
+modparam("call_control", "disable", 1)
+...
+
+5.2. socket_name (string)
+
+   It is the path to the filesystem socket where the callcontrol
+   application listens for commands from the module.
+
+   Default value is "/var/run/callcontrol/socket".
+
+   Example 1.2. Setting the socket_name parameter
+...
+modparam("call_control", "socket_name", "/var/run/callcontrol/socket")
+...
+
+5.3. socket_timeout (int)
+
+   How much time (in milliseconds) to wait for an answer from the
+   callcontrol application.
+
+   Default value is "500" (ms).
+
+   Example 1.3. Setting the socket_timeout parameter
+...
+modparam("call_control", "socket_timeout", 500)
+...
+
+5.4. signaling_ip_avp (string)
+
+   Specification of the AVP which holds the IP address from where the SIP
+   signaling originated. If this AVP is set it will be used to get the
+   signaling IP address, else the source IP address from where the SIP
+   message was received will be used. This AVP is meant to be used in
+   cases where there are more than one proxy in the call setup path and
+   the proxy that actually starts callcontrol doesn't receive the SIP
+   messages directly from the UA and it cannot determine the NAT IP
+   address from where the signaling originated. In such a case attaching a
+   SIP header at the first proxy and then copying that header's value into
+   the signaling_ip_avp on the proxy that starts callcontrol will allow it
+   to get the correct NAT IP address from where the SIP signaling
+   originated.
+
+   This is used by the rating engine which finds the rates to apply to a
+   call based on caller's SIP URI, caller's SIP domain or caller's IP
+   address (whichever yields a rate forst, in this order).
+
+   Default value is "$avp(s:signaling_ip)".
+
+   Example 1.4. Setting the signaling_ip_avp parameter
+...
+modparam("call_control", "signaling_ip_avp", "$avp(s:signaling_ip)")
+...
+
+5.5. canonical_uri_avp (string)
+
+   Specification of the AVP which holds an optional application defined
+   canonical request URI. When this is set, it will be used as the
+   destination when computing the call price, otherwise the request URI
+   will be used. This is useful when the username of the ruri needs to
+   have a different, canonical form in the rating engine computation than
+   it has in the ruri.
+
+   Default value is "$avp(s:can_uri)".
+
+   Example 1.5. Setting the canonical_uri_avp parameter
+...
+modparam("call_control", "canonical_uri_avp", "$avp(s:can_uri)")
+...
+
+5.6. diverter_avp_id (string)
+
+   Specification of the id of an integer AVP which holds an optional
+   application defined diverter SIP URI. When this is set, it will be used
+   by the rating engine as the billing party when finding the rates to
+   apply to a given call, otherwise, the caller's URI taken from the From
+   field will be used. When set, this AVP should contain a value in the
+   form "user@domain" (no sip: prefix should be used).
+
+   This is useful when a destination diverts a call, thus becoming the new
+   caller. In this case the billing party is the diverter and this AVP
+   should be set to it, to allow the rating engine to pick the right rates
+   for the call. For example, if A calls B and B diverts all its calls
+   unconditionally to C, then the diverter AVP should the set to B's URI,
+   because B is the billing party in the call not A after the call was
+   diverted.
+
+   Default value is "805".
+
+   Example 1.6. Setting the diverter_avp_id parameter
+...
+modparam("call_control", "diverter_avp_id", 805)
+
+route {
+  ...
+  # [email protected] is paying for this call
+  $avp(i:805) = "sip:[email protected]";
+  ...
+}
+...
+
+6. Exported Functions
+
+   6.1. call_control()
+
+6.1. call_control()
+
+   Trigger the use of callcontrol for the dialog started by the INVITE for
+   which this function is called (the function should only be called for
+   the first INVITE of a call). Further in-dialog requests will be
+   processed automatically using internal bindings into the dialog state
+   machine, allowing callcontrol to update its internal state as the
+   dialog progresses, without any other intervention from the script.
+
+   This function should be called right before the message is sent out
+   using t_relay(), when all the request uri modifications are over and a
+   final destination has been determined.
+
+   This function has the following return codes:
+
+     * +2 - call has no limit
+     * +1 - call has limit and is traced by callcontrol
+     * -1 - not enough credit to make the call
+     * -2 - call is locked by another call in progress
+     * -5 - internal error (message parsing, communication, ...)
+
+   This function can be used from REQUEST_ROUTE.
+
+   Example 1.7. Using the call_control function
+...
+if (is_avp_set("$avp(i:805)")) {
+    # the diverter AVP is set, use it as billing party
+    $avp(s:billing_party_domain) = $(avp(i:805){uri.domain});
+} else {
+    $avp(s:billing_party_domain) = $fd;
+}
+
+if (method==INVITE && !has_totag() &&
+    is_domain_local("$avp(s:billing_party_domain)")) {
+    call_control();
+    switch ($retcode) {
+    case 2:
+        # Call with no limit
+    case 1:
+        # Call has limit and is under callcontrol management
+        break;
+    case -1:
+        # Not enough credit (prepaid call)
+        sl_send_reply("402", "Not enough credit");
+        exit;
+        break;
+    case -2:
+        # Locked by another call in progress (prepaid call)
+        sl_send_reply("403", "Call locked by another call in progress");
+        exit;
+        break;
+    default:
+        # Internal error (message parsing, communication, ...)
+        if (PREPAID_ACCOUNT) {
+            xlog("Call control: internal server error\n");
+            sl_send_reply("500", "Internal server error");
+            exit;
+        } else {
+            xlog("L_WARN", "Cannot set time limit for postpaid call\n");
+        }
+    }
+}
+t_relay();
+...

+ 967 - 0
modules_k/call_control/call_control.c

@@ -0,0 +1,967 @@
+/* $Id$
+ *
+ * Copyright (C) 2005-2008 Dan Pascu
+ *
+ * This file is part of Kamailio, a free SIP server.
+ *
+ * Kamailio is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version
+ *
+ * Kamailio is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <time.h>
+#include <ctype.h>
+#include <errno.h>
+#include <assert.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/select.h>
+#include <sys/un.h>
+
+#include "../../sr_module.h"
+#include "../../mem/mem.h"
+#include "../../dprint.h"
+#include "../../str.h"
+#include "../../pvar.h"
+#include "../../ut.h"
+#include "../../script_cb.h"
+#include "../../parser/digest/digest.h"
+#include "../../parser/parse_from.h"
+#include "../dialog/dlg_load.h"
+#include "../dialog/dlg_hash.h"
+
+
+MODULE_VERSION
+
+#define FL_USE_CALL_CONTROL       (1<<30) // use call control for a dialog
+
+#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
+# define INLINE inline
+#else
+# define INLINE
+#endif
+
+#define CANONICAL_URI_AVP_SPEC "$avp(s:can_uri)"
+#define SIGNALING_IP_AVP_SPEC  "$avp(s:signaling_ip)"
+
+// Although `AF_LOCAL' is mandated by POSIX.1g, `AF_UNIX' is portable to
+// more systems.  `AF_UNIX' was the traditional name stemming from BSD, so
+// even most POSIX systems support it.  It is also the name of choice in
+// the Unix98 specification. So if there's no AF_LOCAL fallback to AF_UNIX
+#ifndef AF_LOCAL
+# define AF_LOCAL AF_UNIX
+#endif
+
+// Solaris does not have the MSG_NOSIGNAL flag for the send(2) syscall
+#ifndef MSG_NOSIGNAL
+# define MSG_NOSIGNAL 0
+#endif
+
+
+
+typedef int Bool;
+#define True  1
+#define False 0
+
+
+typedef struct AVP_Param {
+    str spec;
+    int_str name;
+    unsigned short type;
+} AVP_Param;
+
+#define RETRY_INTERVAL 10
+#define BUFFER_SIZE    8192
+
+typedef struct CallControlSocket {
+    char *name;             // name
+    int  sock;              // socket
+    int  timeout;           // how many miliseconds to wait for an answer
+    time_t last_failure;    // time of the last failure
+    char data[BUFFER_SIZE]; // buffer for the answer data
+} CallControlSocket;
+
+
+/* Function prototypes */
+static int CallControl(struct sip_msg *msg, char *str1, char *str2);
+
+static int mod_init(void);
+static int child_init(int rank);
+static int postprocess_request(struct sip_msg *msg, unsigned int flags, void *_param);
+
+
+/* Local global variables */
+static CallControlSocket callcontrol_socket = {
+    "/var/run/callcontrol/socket", // name
+    -1,                            // sock
+    500,                           // timeout in 500 miliseconds if there is no answer
+    0,                             // time of the last failure
+    ""                             // data
+};
+
+static int disable = False;
+static int diverter_avp_id = 805;
+
+/* The AVP where the canonical URI is stored (if defined) */
+static AVP_Param canonical_uri_avp = {str_init(CANONICAL_URI_AVP_SPEC), {0}, 0};
+
+/* The AVP where the caller signaling IP is stored (if defined) */
+static AVP_Param signaling_ip_avp = {str_init(SIGNALING_IP_AVP_SPEC), {0}, 0};
+
+
+struct dlg_binds dlg_api;
+static int dialog_flag = -1;
+
+
+static cmd_export_t commands[] = {
+    {"call_control",  (cmd_function)CallControl, 0, 0, 0, REQUEST_ROUTE },
+    {0, 0, 0, 0, 0, 0}
+};
+
+static param_export_t parameters[] = {
+    {"disable",             INT_PARAM, &disable},
+    {"socket_name",         STR_PARAM, &(callcontrol_socket.name)},
+    {"socket_timeout",      INT_PARAM, &(callcontrol_socket.timeout)},
+    {"diverter_avp_id",     INT_PARAM, &diverter_avp_id},
+    {"canonical_uri_avp",   STR_PARAM, &(canonical_uri_avp.spec.s)},
+    {"signaling_ip_avp",    STR_PARAM, &(signaling_ip_avp.spec.s)},
+    {0, 0, 0}
+};
+
+struct module_exports exports = {
+    "call_control",  // module name
+    DEFAULT_DLFLAGS, // dlopen flags
+    commands,        // exported functions
+    parameters,      // exported parameters
+    NULL,            // exported statistics
+    NULL,            // exported MI functions
+    NULL,            // exported pseudo-variables
+    NULL,            // extra processes
+    mod_init,        // module init function (before fork. kids will inherit)
+    NULL,            // reply processing function
+    NULL,            // destroy function
+    child_init       // child init function
+};
+
+
+
+typedef enum CallControlAction {
+    CAInitialize = 1,
+    CAStart,
+    CAStop
+} CallControlAction;
+
+
+typedef struct Contact {
+    str username;
+    str ip;
+    str port;
+} Contact;
+
+typedef struct DialogID {
+    unsigned int h_entry;
+    unsigned int h_id;
+} DialogID;
+
+typedef struct CallInfo {
+    CallControlAction action;
+    DialogID dialog_id;
+    str ruri;
+    str diverter;
+    str source_ip;
+    str callid;
+    str from;
+    str from_tag;
+} CallInfo;
+
+
+// Functions dealing with strings
+//
+
+// returns string with whitespace trimmed from left end
+static inline void
+ltrim(str *string)
+{
+    while (string->len>0 && isspace((int)*(string->s))) {
+        string->len--;
+        string->s++;
+    }
+}
+
+// returns string with whitespace trimmed from right end
+static inline void
+rtrim(str *string)
+{
+    char *ptr;
+
+    ptr = string->s + string->len - 1;
+    while (string->len>0 && (*ptr==0 || isspace((int)*ptr))) {
+        string->len--;
+        ptr--;
+    }
+}
+
+// returns string with whitespace trimmed from both ends
+static inline void
+trim(str *string)
+{
+    ltrim(string);
+    rtrim(string);
+}
+
+
+// Message checking and parsing
+//
+
+static Bool
+has_to_tag(struct sip_msg *msg)
+{
+    str tag;
+
+    if (!msg->to) {
+        if (parse_headers(msg, HDR_TO_F, 0)==-1) {
+            LM_ERR("cannot parse 'To' header\n");
+            return False;
+        }
+        if (!msg->to) {
+            LM_ERR("missing 'To' header\n");
+            return False;
+        }
+    }
+
+    tag = get_to(msg)->tag_value;
+
+    if (tag.s==NULL || tag.len==0) {
+        return False;
+    }
+
+    return True;
+}
+
+
+// Get canonical request URI
+static str
+get_canonical_request_uri(struct sip_msg* msg)
+{
+    int_str value;
+
+    if (!search_first_avp(canonical_uri_avp.type | AVP_VAL_STR,
+                          canonical_uri_avp.name, &value, NULL) ||
+        value.s.s==NULL || value.s.len==0) {
+
+        return *GET_RURI(msg);
+    }
+
+    return value.s;
+}
+
+
+// Get caller signaling IP
+static str
+get_signaling_ip(struct sip_msg* msg)
+{
+    int_str value;
+
+    if (!search_first_avp(signaling_ip_avp.type | AVP_VAL_STR,
+                          signaling_ip_avp.name, &value, NULL) ||
+        !value.s.s || value.s.len==0) {
+
+        value.s.s = ip_addr2a(&msg->rcv.src_ip);
+        value.s.len = strlen(value.s.s);
+    }
+
+    return value.s;
+}
+
+
+static str
+get_diverter(struct sip_msg *msg)
+{
+    struct hdr_field *header;
+    dig_cred_t *credentials;
+    int_str avpname, avpvalue;
+    static str diverter;
+
+    diverter.s   = "None";
+    diverter.len = 4;
+
+    avpname.n = diverter_avp_id;
+
+    if (search_first_avp(AVP_VAL_STR, avpname, &avpvalue, NULL)) {
+        // have a diverted call
+        diverter = avpvalue.s;
+    } else {
+        get_authorized_cred(msg->proxy_auth, &header);
+        if (header) {
+            credentials = &((auth_body_t*)(header->parsed))->digest;
+        } else {
+            if (parse_headers(msg, HDR_PROXYAUTH_F, 0) == -1) {
+                LM_ERR("cannot parse Proxy-Authorization header\n");
+                return diverter;
+            }
+            if (!msg->proxy_auth)
+                return diverter;
+            if (parse_credentials(msg->proxy_auth) != 0) {
+                LM_ERR("cannot parse credentials\n");
+                return diverter;
+            }
+            credentials = &((auth_body_t*)(msg->proxy_auth->parsed))->digest;
+        }
+
+        if (credentials->username.user.len > 0 &&
+            credentials->username.domain.len > 0 &&
+            credentials->realm.len == 0 &&
+            credentials->nonce.len == 0 &&
+            credentials->response.len == 0) {
+            // this is a call diverted from the failure route
+            // and sent back to proxy with append_pa_hf()
+            diverter = credentials->username.whole;
+        }
+    }
+
+    return diverter;
+}
+
+
+static CallInfo*
+get_call_info(struct sip_msg *msg, CallControlAction action)
+{
+    static CallInfo call_info;
+    int headers;
+
+    memset(&call_info, 0, sizeof(struct CallInfo));
+
+    switch (action) {
+    case CAInitialize:
+        headers = HDR_CALLID_F|HDR_FROM_F;
+        break;
+    case CAStart:
+    case CAStop:
+        headers = HDR_CALLID_F;
+        break;
+    default:
+        // Invalid action. Should never get here.
+        assert(False);
+        return NULL;
+    }
+
+    if (parse_headers(msg, headers, 0) == -1) {
+        LM_ERR("cannot parse required headers\n");
+        return NULL;
+    }
+
+    if (headers & HDR_CALLID_F) {
+        if (msg->callid == NULL) {
+            LM_ERR("missing Call-ID header\n");
+            return NULL;
+        }
+
+        call_info.callid = msg->callid->body;
+        trim(&call_info.callid);
+    }
+
+    if (headers & HDR_FROM_F) {
+        struct to_body *from; // yeah. suggestive structure name ;)
+
+        if (msg->from == NULL) {
+            LM_ERR("missing From header\n");
+            return NULL;
+        }
+        if (!msg->from->parsed && parse_from_header(msg)==-1) {
+            LM_ERR("cannot parse From header\n");
+            return NULL;
+        }
+
+        from = get_from(msg);
+
+        if (from->body.s==NULL || from->body.len==0) {
+            LM_ERR("missing From\n");
+            return NULL;
+        }
+        if (from->tag_value.s==NULL || from->tag_value.len==0) {
+            LM_ERR("missing From tag\n");
+            return NULL;
+        }
+
+        call_info.from = from->body;
+        call_info.from_tag = from->tag_value;
+    }
+
+    if (action == CAInitialize) {
+        call_info.ruri = get_canonical_request_uri(msg);
+        call_info.diverter = get_diverter(msg);
+        call_info.source_ip = get_signaling_ip(msg);
+    }
+
+    call_info.action = action;
+
+    return &call_info;
+}
+
+
+static char*
+make_request(CallInfo *call)
+{
+    static char request[8192];
+    int len;
+
+    switch (call->action) {
+    case CAInitialize:
+        len = snprintf(request, sizeof(request),
+                       "init\r\n"
+                       "ruri: %.*s\r\n"
+                       "diverter: %.*s\r\n"
+                       "sourceip: %.*s\r\n"
+                       "callid: %.*s\r\n"
+                       "from: %.*s\r\n"
+                       "fromtag: %.*s\r\n"
+                       "\r\n",
+                       call->ruri.len, call->ruri.s,
+                       call->diverter.len, call->diverter.s,
+                       call->source_ip.len, call->source_ip.s,
+                       call->callid.len, call->callid.s,
+                       call->from.len, call->from.s,
+                       call->from_tag.len, call->from_tag.s);
+
+        if (len >= sizeof(request)) {
+            LM_ERR("callcontrol request is longer than %ld bytes\n", (unsigned long)sizeof(request));
+            return NULL;
+        }
+
+        break;
+
+    case CAStart:
+        len = snprintf(request, sizeof(request),
+                       "start\r\n"
+                       "callid: %.*s\r\n"
+                       "dialogid: %d:%d\r\n"
+                       "\r\n",
+                       call->callid.len, call->callid.s,
+                       call->dialog_id.h_entry, call->dialog_id.h_id);
+
+        if (len >= sizeof(request)) {
+            LM_ERR("callcontrol request is longer than %ld bytes\n", (unsigned long)sizeof(request));
+            return NULL;
+        }
+
+        break;
+
+    case CAStop:
+        len = snprintf(request, sizeof(request),
+                       "stop\r\n"
+                       "callid: %.*s\r\n"
+                       "\r\n",
+                       call->callid.len, call->callid.s);
+
+        if (len >= sizeof(request)) {
+            LM_ERR("callcontrol request is longer than %ld bytes\n", (unsigned long)sizeof(request));
+            return NULL;
+        }
+
+        break;
+
+    default:
+        // should never get here, but keep gcc from complaining
+        assert(False);
+        return NULL;
+    }
+
+    return request;
+}
+
+
+// Functions dealing with the external call_control helper
+//
+
+static Bool
+callcontrol_connect(void)
+{
+    struct sockaddr_un addr;
+
+    if (callcontrol_socket.sock >= 0)
+        return True;
+
+    if (callcontrol_socket.last_failure + RETRY_INTERVAL > time(NULL))
+        return False;
+
+    memset(&addr, 0, sizeof(addr));
+    addr.sun_family = AF_LOCAL;
+    strncpy(addr.sun_path, callcontrol_socket.name, sizeof(addr.sun_path) - 1);
+#ifdef HAVE_SOCKADDR_SA_LEN
+    addr.sun_len = strlen(addr.sun_path);
+#endif
+
+    callcontrol_socket.sock = socket(AF_LOCAL, SOCK_STREAM, 0);
+    if (callcontrol_socket.sock < 0) {
+        LM_ERR("can't create socket\n");
+        callcontrol_socket.last_failure = time(NULL);
+        return False;
+    }
+    if (connect(callcontrol_socket.sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
+        LM_ERR("failed to connect to %s: %s\n", callcontrol_socket.name, strerror(errno));
+        close(callcontrol_socket.sock);
+        callcontrol_socket.sock = -1;
+        callcontrol_socket.last_failure = time(NULL);
+        return False;
+    }
+
+    return True;
+}
+
+static void
+callcontrol_disconnect(void)
+{
+    if (callcontrol_socket.sock < 0)
+        return;
+
+    close(callcontrol_socket.sock);
+    callcontrol_socket.sock = -1;
+    callcontrol_socket.last_failure = time(NULL);
+}
+
+static char*
+send_command(char *command)
+{
+    int cmd_len, bytes, tries, sent, received, count;
+    struct timeval timeout;
+    fd_set rset;
+
+    if (!callcontrol_connect())
+        return NULL;
+
+    cmd_len = strlen(command);
+
+    for (sent=0, tries=0; sent<cmd_len && tries<3; tries++, sent+=bytes) {
+        do
+            bytes = send(callcontrol_socket.sock, command+sent, cmd_len-sent, MSG_DONTWAIT|MSG_NOSIGNAL);
+        while (bytes == -1 && errno == EINTR);
+        if (bytes == -1) {
+            switch (errno) {
+            case ECONNRESET:
+            case EPIPE:
+                callcontrol_disconnect();
+                callcontrol_socket.last_failure = 0; // we want to reconnect immediately
+                if (callcontrol_connect()) {
+                    sent = bytes = 0;
+                    continue;
+                } else {
+                    LM_ERR("connection with callcontrol did die\n");
+                }
+                break;
+            case EACCES:
+                LM_ERR("permission denied sending to %s\n", callcontrol_socket.name);
+                break;
+            case EWOULDBLOCK:
+                // this shouldn't happen as we read back all the answer after a request.
+                // if it would block, it means there is an error.
+                LM_ERR("sending command would block!\n");
+                break;
+            default:
+                LM_ERR("%d: %s\n", errno, strerror(errno));
+                break;
+            }
+            callcontrol_disconnect();
+            return NULL;
+        }
+    }
+    if (sent < cmd_len) {
+        LM_ERR("couldn't send complete command after 3 tries\n");
+        callcontrol_disconnect();
+        return NULL;
+    }
+
+    callcontrol_socket.data[0] = 0;
+    received = 0;
+    while (True) {
+        FD_ZERO(&rset);
+        FD_SET(callcontrol_socket.sock, &rset);
+        timeout.tv_sec = callcontrol_socket.timeout / 1000;
+        timeout.tv_usec = (callcontrol_socket.timeout % 1000) * 1000;
+
+        do
+            count = select(callcontrol_socket.sock + 1, &rset, NULL, NULL, &timeout);
+        while (count == -1 && errno == EINTR);
+
+        if (count == -1) {
+            LM_ERR("select failed: %d: %s\n", errno, strerror(errno));
+            callcontrol_disconnect();
+            return NULL;
+        } else if (count == 0) {
+            LM_ERR("did timeout waiting for an answer\n");
+            callcontrol_disconnect();
+            return NULL;
+        } else {
+            do
+                bytes = recv(callcontrol_socket.sock, callcontrol_socket.data+received, BUFFER_SIZE-1-received, 0);
+            while (bytes == -1 && errno == EINTR);
+            if (bytes == -1) {
+                LM_ERR("failed to read answer: %d: %s\n", errno, strerror(errno));
+                callcontrol_disconnect();
+                return NULL;
+            } else if (bytes == 0) {
+                LM_ERR("connection with callcontrol closed\n");
+                callcontrol_disconnect();
+                return NULL;
+            } else {
+                callcontrol_socket.data[received+bytes] = 0;
+                if (strstr(callcontrol_socket.data+received, "\r\n")!=NULL) {
+                    break;
+                }
+                received += bytes;
+            }
+        }
+    }
+
+    return callcontrol_socket.data;
+}
+
+
+// Call control processing
+//
+
+// Return codes:
+//   2 - No limit
+//   1 - Limited
+//  -1 - No credit
+//  -2 - Locked
+//  -5 - Internal error (message parsing, communication, ...)
+static int
+call_control_initialize(struct sip_msg *msg)
+{
+    CallInfo *call;
+    char *message, *result;
+
+    call = get_call_info(msg, CAInitialize);
+    if (!call) {
+        LM_ERR("can't retrieve call info\n");
+        return -5;
+    }
+    message = make_request(call);
+    if (!message)
+        return -5;
+
+    result = send_command(message);
+
+    if (result==NULL) {
+        return -5;
+    } else if (strcasecmp(result, "No limit\r\n")==0) {
+        return 2;
+    } else if (strcasecmp(result, "Limited\r\n")==0) {
+        return 1;
+    } else if (strcasecmp(result, "No credit\r\n")==0) {
+        return -1;
+    } else if (strcasecmp(result, "Locked\r\n")==0) {
+        return -2;
+    } else {
+        return -5;
+    }
+}
+
+
+// Called during a dialog for start and update requests
+//
+// Return codes:
+//   1 - Ok
+//  -1 - Session not found
+//  -5 - Internal error (message parsing, communication, ...)
+static int
+call_control_start(struct sip_msg *msg, struct dlg_cell *dlg)
+{
+    CallInfo *call;
+    char *message, *result;
+
+    call = get_call_info(msg, CAStart);
+    if (!call) {
+        LM_ERR("can't retrieve call info\n");
+        return -5;
+    }
+
+    call->dialog_id.h_entry = dlg->h_entry;
+    call->dialog_id.h_id = dlg->h_id;
+
+    message = make_request(call);
+    if (!message)
+        return -5;
+
+    result = send_command(message);
+
+    if (result==NULL) {
+        return -5;
+    } else if (strcasecmp(result, "Ok\r\n")==0) {
+        return 1;
+    } else if (strcasecmp(result, "Not found\r\n")==0) {
+        return -1;
+    } else {
+        return -5;
+    }
+}
+
+
+// Called during a dialog ending to stop callcontrol
+//
+// Return codes:
+//   1 - Ok
+//  -1 - Session not found
+//  -5 - Internal error (message parsing, communication, ...)
+static int
+call_control_stop(struct sip_msg *msg, str callid)
+{
+    CallInfo call;
+    char *message, *result;
+
+    call.action = CAStop;
+    call.callid = callid;
+
+    message = make_request(&call);
+    if (!message)
+        return -5;
+
+    result = send_command(message);
+
+    if (result==NULL) {
+        return -5;
+    } else if (strcasecmp(result, "Ok\r\n")==0) {
+        return 1;
+    } else if (strcasecmp(result, "Not found\r\n")==0) {
+        return -1;
+    } else {
+        return -5;
+    }
+}
+
+
+// Dialog callbacks and helpers
+//
+
+typedef enum {
+    CCInactive = 0,
+    CCActive
+} CallControlState;
+
+
+static void
+__dialog_replies(struct dlg_cell *dlg, int type, struct dlg_cb_params *_params)
+{
+    struct sip_msg *reply = _params->msg;
+
+    if (reply!=FAKED_REPLY && reply->REPLY_STATUS==200) {
+        call_control_start(reply, dlg);
+    }
+}
+
+
+static void
+__dialog_ended(struct dlg_cell *dlg, int type, struct dlg_cb_params *_params)
+{
+    if ((int)(long)*_params->param == CCActive) {
+        call_control_stop(_params->msg, dlg->callid);
+        *_params->param = CCInactive;
+    }
+}
+
+
+static void
+__dialog_created(struct dlg_cell *dlg, int type, struct dlg_cb_params *_params)
+{
+    struct sip_msg *request = _params->msg;
+
+    if (request->REQ_METHOD != METHOD_INVITE)
+        return;
+
+    if ((request->msg_flags & FL_USE_CALL_CONTROL) == 0)
+        return;
+
+    if (dlg_api.register_dlgcb(dlg, DLGCB_RESPONSE_FWDED, __dialog_replies, NULL, NULL) != 0)
+        LM_ERR("cannot register callback for dialog confirmation\n");
+    if (dlg_api.register_dlgcb(dlg, DLGCB_TERMINATED | DLGCB_FAILED | DLGCB_EXPIRED | DLGCB_DESTROY, __dialog_ended, (void*)CCActive, NULL) != 0)
+        LM_ERR("cannot register callback for dialog termination\n");
+
+    // reset the flag to indicate that the dialog for callcontrol was created
+    request->msg_flags &= ~FL_USE_CALL_CONTROL;
+}
+
+
+static void
+__dialog_loaded(struct dlg_cell *dlg, int type, struct dlg_cb_params *_params)
+{
+    if (dlg_api.register_dlgcb(dlg, DLGCB_RESPONSE_FWDED, __dialog_replies, NULL, NULL) != 0)
+        LM_ERR("cannot register callback for dialog confirmation\n");
+    if (dlg_api.register_dlgcb(dlg, DLGCB_TERMINATED | DLGCB_FAILED | DLGCB_EXPIRED | DLGCB_DESTROY, __dialog_ended, (void*)CCActive, NULL) != 0)
+        LM_ERR("cannot register callback for dialog termination\n");
+}
+
+
+// Public API
+//
+
+// Return codes:
+//   2 - No limit
+//   1 - Limited
+//  -1 - No credit
+//  -2 - Locked
+//  -3 - No provider
+//  -5 - Internal error (message parsing, communication, ...)
+static int
+CallControl(struct sip_msg *msg, char *str1, char *str2)
+{
+    int result;
+
+    if (disable)
+        return 2;
+
+    if (msg->first_line.type!=SIP_REQUEST || msg->REQ_METHOD!=METHOD_INVITE || has_to_tag(msg)) {
+        LM_WARN("call_control should only be called for the first INVITE\n");
+        return -5;
+    }
+
+    result = call_control_initialize(msg);
+    if (result == 1) {
+        // A call with a time limit that will be traced by callcontrol
+        msg->msg_flags |= FL_USE_CALL_CONTROL;
+        setflag(msg, dialog_flag); // have the dialog module trace this dialog
+    }
+
+    return result;
+}
+
+
+// Module management: initialization/destroy/function-parameter-fixing/...
+//
+
+static int
+mod_init(void)
+{
+    pv_spec_t avp_spec;
+    int *param;
+	 modparam_t type;
+
+
+    // initialize the canonical_uri_avp structure
+    if (canonical_uri_avp.spec.s==NULL || *(canonical_uri_avp.spec.s)==0) {
+        LM_ERR("missing/empty canonical_uri_avp parameter. using default.\n");
+        canonical_uri_avp.spec.s = CANONICAL_URI_AVP_SPEC;
+    }
+    canonical_uri_avp.spec.len = strlen(canonical_uri_avp.spec.s);
+    if (pv_parse_spec(&(canonical_uri_avp.spec), &avp_spec)==0 || avp_spec.type!=PVT_AVP) {
+        LM_CRIT("invalid AVP specification for canonical_uri_avp: `%s'\n", canonical_uri_avp.spec.s);
+        return -1;
+    }
+    if (pv_get_avp_name(0, &(avp_spec.pvp), &(canonical_uri_avp.name), &(canonical_uri_avp.type))!=0) {
+        LM_CRIT("invalid AVP specification for canonical_uri_avp: `%s'\n", canonical_uri_avp.spec.s);
+        return -1;
+    }
+
+    // initialize the signaling_ip_avp structure
+    if (signaling_ip_avp.spec.s==NULL || *(signaling_ip_avp.spec.s)==0) {
+        LM_ERR("missing/empty signaling_ip_avp parameter. using default.\n");
+        signaling_ip_avp.spec.s = SIGNALING_IP_AVP_SPEC;
+    }
+    signaling_ip_avp.spec.len = strlen(signaling_ip_avp.spec.s);
+    if (pv_parse_spec(&(signaling_ip_avp.spec), &avp_spec)==0 || avp_spec.type!=PVT_AVP) {
+        LM_CRIT("invalid AVP specification for signaling_ip_avp: `%s'\n", signaling_ip_avp.spec.s);
+        return -1;
+    }
+    if (pv_get_avp_name(0, &(avp_spec.pvp), &(signaling_ip_avp.name), &(signaling_ip_avp.type))!=0) {
+        LM_CRIT("invalid AVP specification for signaling_ip_avp: `%s'\n", signaling_ip_avp.spec.s);
+        return -1;
+    }
+
+    // bind to the dialog API
+    if (load_dlg_api(&dlg_api)!=0) {
+        LM_CRIT("cannot load the dialog module API\n");
+        return -1;
+    }
+
+    // load dlg_flag and default_timeout parameters from the dialog module
+    param = find_param_export(find_module_by_name("dialog"), "dlg_flag", INT_PARAM, &type);
+    if (!param) {
+        LM_CRIT("cannot find dlg_flag parameter in the dialog module\n");
+        return -1;
+    }
+    if (type != INT_PARAM) {
+        LM_CRIT("dlg_flag parameter found but with wrong type: %d\n", type);
+        return -1;
+    }
+
+    dialog_flag = *param;
+
+    // register dialog creation callback
+    if (dlg_api.register_dlgcb(NULL, DLGCB_CREATED, __dialog_created, NULL, NULL) != 0) {
+        LM_CRIT("cannot register callback for dialog creation\n");
+        return -1;
+    }
+
+    // register dialog loading callback
+    if (dlg_api.register_dlgcb(NULL, DLGCB_LOADED, __dialog_loaded, NULL, NULL) != 0) {
+        LM_ERR("cannot register callback for dialogs loaded from the database\n");
+    }
+
+    // register a pre-script callback to automatically enable dialog tracing
+    if (register_script_cb(postprocess_request, POST_SCRIPT_CB|REQUEST_CB, 0) != 0) {
+        LOG(L_CRIT, "ERROR:call_control:mod_init: could not register request postprocessing callback\n");
+        return -1;
+    }
+
+    return 0;
+}
+
+
+static int
+child_init(int rank)
+{
+    // initialize the connection to callcontrol if needed
+    if (!disable)
+        callcontrol_connect();
+
+    return 0;
+}
+
+
+// Postprocess a request after the main script route is done.
+//
+// After all script processing is done, check if the dialog was actually
+// created to take care of call control. If the FL_USE_CALL_CONTROL flag
+// is still set, then the dialog creation callback was not called which
+// means that there was a failure relaying the message and we have to
+// tell the call control application to discard the call, otherwise it
+// would remain dangling until it expires.
+//
+static int
+postprocess_request(struct sip_msg *msg, unsigned int flags, void *_param)
+{
+    CallInfo *call;
+
+    if ((msg->msg_flags & FL_USE_CALL_CONTROL) == 0)
+        return 1;
+
+    // the FL_USE_CALL_CONTROL flag is still set => the dialog was not created
+
+    LM_WARN("dialog to trace controlled call was not created. discarding callcontrol.");
+
+    call = get_call_info(msg, CAStop);
+    if (!call) {
+        LM_ERR("can't retrieve call info\n");
+        return -1;
+    }
+    call_control_stop(msg, call->callid);
+
+    return 1;
+}
+
+

+ 4 - 0
modules_k/call_control/doc/Makefile

@@ -0,0 +1,4 @@
+docs = call_control.xml
+
+docbook_dir = ../../../docbook
+include $(docbook_dir)/Makefile.module

+ 125 - 0
modules_k/call_control/doc/call_control.8

@@ -0,0 +1,125 @@
+
+.TH Call Control Module
+.SH Overview
+.TP
+This module allows one to limit the duration of calls and automatically end them when they exceed the imposed limit. Its main use case is to implement a prepaid system, but it can also be used to impose a global limit on all calls processed by the proxy.
+.SH Description
+.TP
+Callcontrol consists of 3 components: The Kamailio call_control module An external application called callcontrol which keeps track of the calls that have a time limit and automatically ends them when they exceed it. This application receives requests from Kamailio and makes requests to a rating engine (see below) to find out if a call needs to be limited or not. When a call ends (or is ended) it will also instruct the rating engine to debit the balance for the caller with the consumed amount. The callcontrol application is available from http://callcontrol.ag-projects.com/ A rating engine that is used to calculate the time limit based on the caller's credit and the destination price and to debit the caller's balance after a call ends. This is available as part of CDRTool from http://cdrtool.ag-projects.com/
+.TP
+The callcontrol application runs on the same machine as Kamailio and they communicate over a filesystem socket, while the rating engine can run on a different host and communicates with the callcontrol application using a TCP connection.
+.TP
+Callcontrol is invoked by calling the call_control() function for the initial INVITE of every call we want to apply a limit to. This will end up as a request to the callcontrol application, which will interogate the rating engine for a time limit for the given caller and destination. The rating engine will determine if the destination has any associated cost and if the caller has any credit limit and if so will return the amount of time he is allowed to call that destination. Otherwise it will indicate that there is no limit associated with the call. If there is a limit, the callcontrol application will retain the session and attach a timer to it that will expire after the given time causing it to call back to Kamailio with a request to end the dialog. If the rating engine returns that there is no limit for the call, the session is discarded by the callcontrol application and it will allow it to go proceed any limit. An appropriate response is returned to the call_control module that is then returned by the call_control() function call and allows the script to make a decision based on the answer.
+.SH Features
+.TP
+Very simple API consisting of a single function that needs to be called once for the first INVITE of every call. The rest is done automatically in the background using dialog callbacks. Gracefully end dialogs when they exceed their time by triggering a dlg_end_dlg request into the dialog module, that will generate two BYE messages towards each endpoint, ending the call cleanly. Allow parallel sessions using one balance per subscriber Integrates with mediaproxy's ability to detect when a call does timeout sending media and is closed. In this case the dlg_end_dlg that is triggered by mediaproxy will end the callcontrol session before it reaches the limit and consumes all the credit for a call that died and didn't actually take place. For this mediaproxy has to be used and it has to be started by engage_media_proxy() to be able to keep track of the call's dialog and end it on timeout. Even when mediaproxy is unable to end the dialog because it was not started with engage_media_proxy(), the callcantrol application is still able to detect calls that did timeout sending media, by looking in the radius accounting records for entries recorded by mediaproxy for calls that did timeout. These calls will also be ended gracefully by the callcontrol application itself.
+.SH Dependencies
+.TP 16
+.I Kamailio Modules
+.TP
+The following modules must be loaded before this module: dialog module
+.TP 16
+.I External Libraries or Applications
+.TP
+The following libraries or applications must be installed before running Kamailio with this module loaded: None.
+.SH Exported parameters
+.TP 16
+.I disable (int)
+.TP
+Boolean flag that specifies if callcontrol should be disabled. This is useful when you want to use the same Kamailio configuration in two different context, one using callcontrol, the other not. In the case callcontrol is disabled, calls to the call_control() function will return a code indicating that there is no limit associated with the call, allowing the use of the same configuration without changes.
+.TP
+Default value is 0.
+.TP
+.B Setting the disable parameter
+.TP
+ modparam("call_control", "disable", 1) ...
+.TP 16
+.I socket_name (string)
+.TP
+It is the path to the filesystem socket where the callcontrol application listens for commands from the module.
+.TP
+Default value is /var/run/callcontrol/socket.
+.TP
+.B Setting the socket_name parameter
+.TP
+ modparam("call_control", "socket_name", "/var/run/callcontrol/socket") ...
+.TP 16
+.I socket_timeout (int)
+.TP
+How much time (in milliseconds) to wait for an answer from the callcontrol application.
+.TP
+Default value is 500 (ms).
+.TP
+.B Setting the socket_timeout parameter
+.TP
+ modparam("call_control", "socket_timeout", 500) ...
+.TP 16
+.I signaling_ip_avp (string)
+.TP
+Specification of the AVP which holds the IP address from where the SIP signaling originated. If this AVP is set it will be used to get the signaling IP address, else the source IP address from where the SIP message was received will be used. This AVP is meant to be used in cases where there are more than one proxy in the call setup path and the proxy that actually starts callcontrol doesn't receive the SIP messages directly from the UA and it cannot determine the NAT IP address from where the signaling originated. In such a case attaching a SIP header at the first proxy and then copying that header's value into the signaling_ip_avp on the proxy that starts callcontrol will allow it to get the correct NAT IP address from where the SIP signaling originated.
+.TP
+This is used by the rating engine which finds the rates to apply to a call based on caller's SIP URI, caller's SIP domain or caller's IP address (whichever yields a rate forst, in this order).
+.TP
+Default value is $avp(s:signaling_ip).
+.TP
+.B Setting the signaling_ip_avp parameter
+.TP
+ modparam("call_control", "signaling_ip_avp", "$avp(s:signaling_ip)") ...
+.TP 16
+.I canonical_uri_avp (string)
+.TP
+Specification of the AVP which holds an optional application defined canonical request URI. When this is set, it will be used as the destination when computing the call price, otherwise the request URI will be used. This is useful when the username of the ruri needs to have a different, canonical form in the rating engine computation than it has in the ruri.
+.TP
+Default value is $avp(s:can_uri).
+.TP
+.B Setting the canonical_uri_avp parameter
+.TP
+ modparam("call_control", "canonical_uri_avp", "$avp(s:can_uri)") ...
+.TP 16
+.I diverter_avp_id (string)
+.TP
+Specification of the id of an integer AVP which holds an optional application defined diverter SIP URI. When this is set, it will be used by the rating engine as the billing party when finding the rates to apply to a given call, otherwise, the caller's URI taken from the From field will be used. When set, this AVP should contain a value in the form user@domain (no sip: prefix should be used).
+.TP
+This is useful when a destination diverts a call, thus becoming the new caller. In this case the billing party is the diverter and this AVP should be set to it, to allow the rating engine to pick the right rates for the call. For example, if A calls B and B diverts all its calls unconditionally to C, then the diverter AVP should the set to B's URI, because B is the billing party in the call not A after the call was diverted.
+.TP
+Default value is 805.
+.TP
+.B Setting the diverter_avp_id parameter
+.TP
+ modparam("call_control", "diverter_avp_id", 805) route { ... # [email protected] is paying for this call $avp(i:805) = "sip:[email protected]"; ... } ...
+.SH Exported Functions
+.TP 16
+.I call_control()
+.TP
+Trigger the use of callcontrol for the dialog started by the INVITE for which this function is called (the function should only be called for the first INVITE of a call). Further in-dialog requests will be processed automatically using internal bindings into the dialog state machine, allowing callcontrol to update its internal state as the dialog progresses, without any other intervention from the script.
+.TP
+This function should be called right before the message is sent out using t_relay(), when all the request uri modifications are over and a final destination has been determined.
+.TP
+This function has the following return codes:
+.TP
++2 - call has no limit +1 - call has limit and is traced by callcontrol -1 - not enough credit to make the call -2 - call is locked by another call in progress -5 - internal error (message parsing, communication, )
+.TP
+This function can be used from REQUEST_ROUTE.
+.TP
+.B Using the call_control function
+.TP
+ if (is_avp_set("$avp(i:805)")) { # the diverter AVP is set, use it as billing party $avp(s:billing_party_domain) = $(avp(i:805){uri.domain}); } else { $avp(s:billing_party_domain) = $fd; } if (method==INVITE &amp;&amp; !has_totag() &amp;&amp; is_domain_local("$avp(s:billing_party_domain)")) { call_control(); switch ($retcode) { case 2: # Call with no limit case 1: # Call has limit and is under callcontrol management break; case -1: # Not enough credit (prepaid call) sl_send_reply("402", "Not enough credit"); exit; break; case -2: # Locked by another call in progress (prepaid call) sl_send_reply("403", "Call locked by another call in progress"); exit; break; default: # Internal error (message parsing, communication, ...) if (PREPAID_ACCOUNT) { xlog("Call control: internal server error\n"); sl_send_reply("500", "Internal server error"); exit; } else { xlog("L_WARN", "Cannot set time limit for postpaid call\n"); } } } t_relay(); ...
+
+.SH AUTHORS
+
+see 
+.B /usr/share/doc/kamailio/AUTHORS
+
+.SH SEE ALSO
+.BR kamailio(8), 
+.BR kamailio.cfg(5)
+.PP
+Full documentation on Kamailio is available at
+.I http://www.kamailio.org/.
+.PP
+Mailing lists:
+.nf 
[email protected] - Kamailio user community
+.nf 
[email protected] - Kamailio development, new features and unstable version
+

+ 45 - 0
modules_k/call_control/doc/call_control.xml

@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding='ISO-8859-1'?>
+<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
+"http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd" [
+
+<!ENTITY admin SYSTEM "call_control_admin.xml">
+<!ENTITY faq SYSTEM "call_control_faq.xml">
+
+<!-- Include general documentation entities -->
+<!ENTITY % docentities SYSTEM "../../../docbook/entities.xml">
+%docentities;
+
+]>
+
+<book>
+  <bookinfo>
+  <title>Call Control Module</title>
+  <authorgroup>
+    <author>
+    <firstname>Dan</firstname>
+    <surname>Pascu</surname>
+    <email>[email protected]</email>
+    </author>
+    <editor>
+    <firstname>Dan</firstname>
+    <surname>Pascu</surname>
+    <email>[email protected]</email>
+    </editor>
+  </authorgroup>
+  <copyright>
+    <year>2005-2008</year>
+    <holder>Dan Pascu</holder>
+  </copyright>
+  <revhistory>
+    <revision>
+    <revnumber>$Revision: 1 $</revnumber>
+    <date>$Date: 2008-12-17 13:05:29 +0200 (Wed, 17 Dec 2008) $</date>
+    </revision>
+  </revhistory>
+  </bookinfo>
+  <toc></toc>
+
+  &admin;
+  &faq;
+
+</book>

+ 437 - 0
modules_k/call_control/doc/call_control_admin.xml

@@ -0,0 +1,437 @@
+<!-- Module User's Guide -->
+
+<chapter>
+  
+  <title>&adminguide;</title>
+  
+  <section>
+  <title>Overview</title>
+    <para>
+      This module allows one to limit the duration of calls and automatically
+      end them when they exceed the imposed limit. Its main use case is to
+      implement a prepaid system, but it can also be used to impose a global
+      limit on all calls processed by the proxy.
+    </para>
+  </section>
+  
+  <section>
+  <title>Description</title>
+    <para>
+      Callcontrol consists of 3 components:
+      <itemizedlist>
+        <listitem>
+          <para>The &kamailio; call_control module</para>
+        </listitem>
+        <listitem>
+          <para>
+            An external application called callcontrol which keeps track of
+            the calls that have a time limit and automatically ends them when
+            they exceed it. This application receives requests from &kamailio;
+            and makes requests to a rating engine (see below) to find out if
+            a call needs to be limited or not. When a call ends (or is ended)
+            it will also instruct the rating engine to debit the balance for
+            the caller with the consumed amount. The callcontrol application
+            is available from http://callcontrol.ag-projects.com/
+          </para>
+        </listitem>
+        <listitem>
+          <para>
+            A rating engine that is used to calculate the time limit based on
+            the caller's credit and the destination price and to debit the
+            caller's balance after a call ends. This is available as part of
+            CDRTool from http://cdrtool.ag-projects.com/
+          </para>
+        </listitem>
+      </itemizedlist>
+    </para>
+
+    <para>
+      The callcontrol application runs on the same machine as &kamailio; and they
+      communicate over a filesystem socket, while the rating engine can run on
+      a different host and communicates with the callcontrol application using
+      a TCP connection.
+    </para>
+
+    <para>
+      Callcontrol is invoked by calling the call_control() function for the
+      initial INVITE of every call we want to apply a limit to. This will end
+      up as a request to the callcontrol application, which will interogate
+      the rating engine for a time limit for the given caller and destination.
+      The rating engine will determine if the destination has any associated
+      cost and if the caller has any credit limit and if so will return the
+      amount of time he is allowed to call that destination. Otherwise it will
+      indicate that there is no limit associated with the call. If there is a
+      limit, the callcontrol application will retain the session and attach
+      a timer to it that will expire after the given time causing it to call
+      back to &kamailio; with a request to end the dialog. If the rating engine
+      returns that there is no limit for the call, the session is discarded
+      by the callcontrol application and it will allow it to go proceed any
+      limit. An appropriate response is returned to the call_control module
+      that is then returned by the call_control() function call and allows
+      the script to make a decision based on the answer.
+    </para>
+  </section>
+
+  <section>
+  <title>Features</title>
+    <para>
+      <itemizedlist>
+        <listitem>
+          <para>
+            Very simple API consisting of a single function that needs to be
+            called once for the first INVITE of every call. The rest is done
+            automatically in the background using dialog callbacks.
+          </para>
+        </listitem>
+
+        <listitem>
+          <para>
+            Gracefully end dialogs when they exceed their time by triggering
+            a dlg_end_dlg request into the dialog module, that will generate
+            two BYE messages towards each endpoint, ending the call cleanly.
+          </para>
+        </listitem>
+
+        <listitem>
+          <para>
+            Allow parallel sessions using one balance per subscriber
+          </para>
+        </listitem>
+
+        <listitem>
+          <para>
+            Integrates with mediaproxy's ability to detect when a call does
+            timeout sending media and is closed. In this case the dlg_end_dlg
+            that is triggered by mediaproxy will end the callcontrol session
+            before it reaches the limit and consumes all the credit for a call
+            that died and didn't actually take place. For this mediaproxy has
+            to be used and it has to be started by engage_media_proxy() to be
+            able to keep track of the call's dialog and end it on timeout.
+          </para>
+          <para>
+            Even when mediaproxy is unable to end the dialog because it was
+            not started with engage_media_proxy(), the callcantrol application
+            is still able to detect calls that did timeout sending media, by
+            looking in the radius accounting records for entries recorded by
+            mediaproxy for calls that did timeout. These calls will also be
+            ended gracefully by the callcontrol application itself.
+          </para>
+        </listitem>
+      </itemizedlist>
+    </para>
+  </section>
+
+  <section>
+  <title>Dependencies</title>
+    <section>
+    <title>&kamailio; Modules</title>
+      <para>
+        The following modules must be loaded before this module:
+        <itemizedlist>
+          <listitem>
+            <para>
+              <emphasis>dialog</emphasis> module 
+            </para>
+          </listitem>
+        </itemizedlist>
+      </para>
+    </section>
+
+    <section>
+    <title>External Libraries or Applications</title>
+      <para>
+        The following libraries or applications must be installed before
+        running &kamailio; with this module loaded:
+        <itemizedlist>
+          <listitem>
+            <para>
+              <emphasis>None</emphasis>.
+            </para>
+          </listitem>
+        </itemizedlist>
+      </para>
+    </section>
+  </section>
+  
+  <section>
+  <title>Exported parameters</title>
+    <section>
+    <title><varname>disable</varname> (int)</title>
+      <para>
+        Boolean flag that specifies if callcontrol should be disabled. This
+        is useful when you want to use the same &kamailio; configuration in
+        two different context, one using callcontrol, the other not. In the
+        case callcontrol is disabled, calls to the call_control() function
+        will return a code indicating that there is no limit associated with
+        the call, allowing the use of the same configuration without changes.
+      </para>
+
+      <para>
+        <emphasis>
+          Default value is <quote>0</quote>.
+        </emphasis>
+      </para>
+
+      <example>
+      <title>Setting the <varname>disable</varname> parameter</title>
+        <programlisting format="linespecific">
+...
+modparam("call_control", "disable", 1)
+...
+        </programlisting>
+      </example>
+    </section>
+
+    <section>
+    <title><varname>socket_name</varname> (string)</title>
+      <para>
+        It is the path to the filesystem socket where the callcontrol
+        application listens for commands from the module.
+      </para>
+
+      <para>
+        <emphasis>
+          Default value is 
+            <quote>/var/run/callcontrol/socket</quote>.
+        </emphasis>
+      </para>
+
+      <example>
+      <title>Setting the <varname>socket_name</varname> parameter</title>
+        <programlisting format="linespecific">
+...
+modparam("call_control", "socket_name", "/var/run/callcontrol/socket")
+...
+        </programlisting>
+      </example>
+    </section>
+
+    <section>
+    <title><varname>socket_timeout</varname> (int)</title>
+      <para>
+        How much time (in milliseconds) to wait for an answer from the
+        callcontrol application.
+      </para>
+
+      <para>
+        <emphasis>
+          Default value is <quote>500</quote> (ms).
+        </emphasis>
+      </para>
+
+      <example>
+      <title>Setting the <varname>socket_timeout</varname> parameter</title>
+        <programlisting format="linespecific">
+...
+modparam("call_control", "socket_timeout", 500)
+...
+        </programlisting>
+      </example>
+    </section>
+
+    <section>
+    <title><varname>signaling_ip_avp</varname> (string)</title>
+      <para>
+        Specification of the AVP which holds the IP address from where
+        the SIP signaling originated. If this AVP is set it will be used
+        to get the signaling IP address, else the source IP address
+        from where the SIP message was received will be used.
+        This AVP is meant to be used in cases where there are more than
+        one proxy in the call setup path and the proxy that actually
+        starts callcontrol doesn't receive the SIP messages directly
+        from the UA and it cannot determine the NAT IP address from
+        where the signaling originated. In such a case attaching a
+        SIP header at the first proxy and then copying that header's
+        value into the signaling_ip_avp on the proxy that starts
+        callcontrol will allow it to get the correct NAT IP address
+        from where the SIP signaling originated.
+      </para>
+      
+      <para>
+        This is used by the rating engine which finds the rates to apply to a
+        call based on caller's SIP URI, caller's SIP domain or caller's IP
+        address (whichever yields a rate forst, in this order).
+      </para>
+
+      <para>
+        <emphasis>
+          Default value is <quote>$avp(s:signaling_ip)</quote>.
+        </emphasis>
+      </para>
+
+      <example>
+      <title>Setting the <varname>signaling_ip_avp</varname> parameter</title>
+        <programlisting format="linespecific">
+...
+modparam("call_control", "signaling_ip_avp", "$avp(s:signaling_ip)")
+...
+        </programlisting>
+      </example>
+    </section>
+
+    <section>
+    <title><varname>canonical_uri_avp</varname> (string)</title>
+      <para>
+        Specification of the AVP which holds an optional application defined
+        canonical request URI. When this is set, it will be used as the
+        destination when computing the call price, otherwise the request URI
+        will be used. This is useful when the username of the ruri needs to
+        have a different, canonical form in the rating engine computation
+        than it has in the ruri.
+      </para>
+
+      <para>
+        <emphasis>
+          Default value is <quote>$avp(s:can_uri)</quote>.
+        </emphasis>
+      </para>
+
+      <example>
+      <title>Setting the <varname>canonical_uri_avp</varname> parameter</title>
+        <programlisting format="linespecific">
+...
+modparam("call_control", "canonical_uri_avp", "$avp(s:can_uri)")
+...
+        </programlisting>
+      </example>
+    </section>
+
+    <section>
+    <title><varname>diverter_avp_id</varname> (string)</title>
+      <para>
+        Specification of the id of an integer AVP which holds an optional
+        application defined diverter SIP URI. When this is set, it will be
+        used by the rating engine as the billing party when finding the rates
+        to apply to a given call, otherwise, the caller's URI taken from the
+        From field will be used. When set, this AVP should contain a value in
+        the form <quote>user@domain</quote> (no sip: prefix should be used).
+      </para>
+      <para>
+        This is useful when a destination diverts a call, thus becoming the
+        new caller. In this case the billing party is the diverter and this
+        AVP should be set to it, to allow the rating engine to pick the right
+        rates for the call. For example, if A calls B and B diverts all its
+        calls unconditionally to C, then the diverter AVP should the set to
+        B's URI, because B is the billing party in the call not A after the
+        call was diverted.
+      </para>
+
+      <para>
+        <emphasis>
+          Default value is <quote>805</quote>.
+        </emphasis>
+      </para>
+
+      <example>
+      <title>Setting the <varname>diverter_avp_id</varname> parameter</title>
+        <programlisting format="linespecific">
+...
+modparam("call_control", "diverter_avp_id", 805)
+
+route {
+  ...
+  # [email protected] is paying for this call
+  $avp(i:805) = "sip:[email protected]";
+  ...
+}
+...
+        </programlisting>
+      </example>
+    </section>
+  </section>
+
+  <section>
+  <title>Exported Functions</title>
+    <section>
+    <title><function moreinfo="none">call_control()</function></title>
+      <para>
+        Trigger the use of callcontrol for the dialog started by the INVITE
+        for which this function is called (the function should only be called
+        for the first INVITE of a call). Further in-dialog requests will be
+        processed automatically using internal bindings into the dialog state
+        machine, allowing callcontrol to update its internal state as the
+        dialog progresses, without any other intervention from the script.
+      </para>
+
+      <para>
+        This function should be called right before the message is sent out
+        using t_relay(), when all the request uri modifications are over and
+        a final destination has been determined.
+      </para>
+
+      <para>This function has the following return codes:</para>
+      <para>
+        <itemizedlist>
+        <listitem><para>
+          +2 - call has no limit
+        </para></listitem>
+        <listitem><para>
+          +1 - call has limit and is traced by callcontrol
+        </para></listitem>
+        <listitem><para>
+          -1 - not enough credit to make the call
+        </para></listitem>
+        <listitem><para>
+          -2 - call is locked by another call in progress
+        </para></listitem>
+        <listitem><para>
+          -5 - internal error (message parsing, communication, ...)
+        </para></listitem>
+        </itemizedlist>
+      </para>
+
+      <para>
+        This function can be used from REQUEST_ROUTE.
+      </para>
+
+      <example>
+      <title>Using the <function>call_control</function> function</title>
+        <programlisting format="linespecific">
+
+...
+if (is_avp_set("$avp(i:805)")) {
+    # the diverter AVP is set, use it as billing party
+    $avp(s:billing_party_domain) = $(avp(i:805){uri.domain});
+} else {
+    $avp(s:billing_party_domain) = $fd;
+}
+
+if (method==INVITE &amp;&amp; !has_totag() &amp;&amp;
+    is_domain_local("$avp(s:billing_party_domain)")) {
+    call_control();
+    switch ($retcode) {
+    case 2:
+        # Call with no limit
+    case 1:
+        # Call has limit and is under callcontrol management
+        break;
+    case -1:
+        # Not enough credit (prepaid call)
+        sl_send_reply("402", "Not enough credit");
+        exit;
+        break;
+    case -2:
+        # Locked by another call in progress (prepaid call)
+        sl_send_reply("403", "Call locked by another call in progress");
+        exit;
+        break;
+    default:
+        # Internal error (message parsing, communication, ...)
+        if (PREPAID_ACCOUNT) {
+            xlog("Call control: internal server error\n");
+            sl_send_reply("500", "Internal server error");
+            exit;
+        } else {
+            xlog("L_WARN", "Cannot set time limit for postpaid call\n");
+        }
+    }
+}
+t_relay();
+...
+        </programlisting>
+      </example>
+    </section>
+  </section>
+
+</chapter>
+

+ 0 - 0
modules_k/call_control/doc/call_control_faq.xml