call_control.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. /* $Id$
  2. *
  3. * Copyright (C) 2005-2008 Dan Pascu
  4. *
  5. * This file is part of Kamailio, a free SIP server.
  6. *
  7. * Kamailio is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version
  11. *
  12. * Kamailio is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  20. *
  21. */
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <unistd.h>
  25. #include <string.h>
  26. #include <time.h>
  27. #include <ctype.h>
  28. #include <errno.h>
  29. #include <assert.h>
  30. #include <sys/time.h>
  31. #include <sys/types.h>
  32. #include <sys/socket.h>
  33. #include <sys/select.h>
  34. #include <sys/un.h>
  35. #include "../../sr_module.h"
  36. #include "../../mem/mem.h"
  37. #include "../../dprint.h"
  38. #include "../../str.h"
  39. #include "../../pvar.h"
  40. #include "../../ut.h"
  41. #include "../../script_cb.h"
  42. #include "../../parser/digest/digest.h"
  43. #include "../../parser/parse_from.h"
  44. #include "../dialog/dlg_load.h"
  45. #include "../dialog/dlg_hash.h"
  46. MODULE_VERSION
  47. #define FL_USE_CALL_CONTROL (1<<28) // use call control for a dialog
  48. #if defined(__GNUC__) && !defined(__STRICT_ANSI__)
  49. # define INLINE inline
  50. #else
  51. # define INLINE
  52. #endif
  53. #define CANONICAL_URI_AVP_SPEC "$avp(s:can_uri)"
  54. #define SIGNALING_IP_AVP_SPEC "$avp(s:signaling_ip)"
  55. #define SIP_APPLICATION_AVP_SPEC "$avp(s:sip_application)"
  56. // Although `AF_LOCAL' is mandated by POSIX.1g, `AF_UNIX' is portable to
  57. // more systems. `AF_UNIX' was the traditional name stemming from BSD, so
  58. // even most POSIX systems support it. It is also the name of choice in
  59. // the Unix98 specification. So if there's no AF_LOCAL fallback to AF_UNIX
  60. #ifndef AF_LOCAL
  61. # define AF_LOCAL AF_UNIX
  62. #endif
  63. // Solaris does not have the MSG_NOSIGNAL flag for the send(2) syscall
  64. #ifndef MSG_NOSIGNAL
  65. # define MSG_NOSIGNAL 0
  66. #endif
  67. typedef int Bool;
  68. #define True 1
  69. #define False 0
  70. typedef struct AVP_Param {
  71. str spec;
  72. int_str name;
  73. unsigned short type;
  74. } AVP_Param;
  75. typedef struct AVP_List {
  76. pv_spec_p pv;
  77. str name;
  78. struct AVP_List *next;
  79. } AVP_List;
  80. #define RETRY_INTERVAL 10
  81. #define BUFFER_SIZE 8192
  82. typedef struct CallControlSocket {
  83. char *name; // name
  84. int sock; // socket
  85. int timeout; // how many miliseconds to wait for an answer
  86. time_t last_failure; // time of the last failure
  87. char data[BUFFER_SIZE]; // buffer for the answer data
  88. } CallControlSocket;
  89. /* Function prototypes */
  90. static int CallControl(struct sip_msg *msg, char *str1, char *str2);
  91. static int mod_init(void);
  92. static int child_init(int rank);
  93. static void destroy(void);
  94. static int postprocess_request(struct sip_msg *, unsigned int, void *);
  95. int parse_param_init(unsigned int type, void *val);
  96. int parse_param_start(unsigned int type, void *val);
  97. int parse_param_stop(unsigned int type, void *val);
  98. /* Local global variables */
  99. static CallControlSocket callcontrol_socket = {
  100. "/var/run/callcontrol/socket", // name
  101. -1, // sock
  102. 500, // timeout in 500 miliseconds if there is no answer
  103. 0, // time of the last failure
  104. "" // data
  105. };
  106. static int disable = False;
  107. static int diverter_avp_id = 805;
  108. /* The AVP where the canonical URI is stored (if defined) */
  109. static AVP_Param canonical_uri_avp = {str_init(CANONICAL_URI_AVP_SPEC), {0}, 0};
  110. /* The AVP where the caller signaling IP is stored (if defined) */
  111. static AVP_Param signaling_ip_avp = {str_init(SIGNALING_IP_AVP_SPEC), {0}, 0};
  112. /* The AVP where the SIP application type is stored (if defined) */
  113. static AVP_Param sip_application_avp = {str_init(SIP_APPLICATION_AVP_SPEC), {0}, 0};
  114. struct dlg_binds dlg_api;
  115. static int dialog_flag = -1;
  116. AVP_List *cc_init_avps = NULL, *cc_start_avps = NULL, *cc_stop_avps = NULL;
  117. pv_elem_t *model;
  118. static cmd_export_t commands[] = {
  119. {"call_control", (cmd_function)CallControl, 0, 0, 0, REQUEST_ROUTE },
  120. {0, 0, 0, 0, 0, 0}
  121. };
  122. static param_export_t parameters[] = {
  123. {"init", STR_PARAM | USE_FUNC_PARAM, parse_param_init},
  124. {"start", STR_PARAM | USE_FUNC_PARAM, parse_param_start},
  125. {"stop", STR_PARAM | USE_FUNC_PARAM, parse_param_stop},
  126. {"disable", INT_PARAM, &disable},
  127. {"socket_name", STR_PARAM, &(callcontrol_socket.name)},
  128. {"socket_timeout", INT_PARAM, &(callcontrol_socket.timeout)},
  129. {"diverter_avp_id", INT_PARAM, &diverter_avp_id},
  130. {"canonical_uri_avp", STR_PARAM, &(canonical_uri_avp.spec.s)},
  131. {"signaling_ip_avp", STR_PARAM, &(signaling_ip_avp.spec.s)},
  132. {"sip_application_avp", STR_PARAM, &(sip_application_avp.spec.s)},
  133. {0, 0, 0}
  134. };
  135. struct module_exports exports = {
  136. "call_control", // module name
  137. DEFAULT_DLFLAGS, // dlopen flags
  138. commands, // exported functions
  139. parameters, // exported parameters
  140. NULL, // exported statistics
  141. NULL, // exported MI functions
  142. NULL, // exported pseudo-variables
  143. NULL, // extra processes
  144. mod_init, // module init function (before fork. kids will inherit)
  145. NULL, // reply processing function
  146. destroy, // destroy function
  147. child_init // child init function
  148. };
  149. typedef enum CallControlAction {
  150. CAInitialize = 1,
  151. CAStart,
  152. CAStop
  153. } CallControlAction;
  154. typedef struct Contact {
  155. str username;
  156. str ip;
  157. str port;
  158. } Contact;
  159. typedef struct DialogID {
  160. unsigned int h_entry;
  161. unsigned int h_id;
  162. } DialogID;
  163. typedef struct CallInfo {
  164. CallControlAction action;
  165. DialogID dialog_id;
  166. str ruri;
  167. str diverter;
  168. str source_ip;
  169. str callid;
  170. str from;
  171. str from_tag;
  172. str sip_application;
  173. } CallInfo;
  174. #define CHECK_COND(cond) \
  175. if ((cond) == 0) { \
  176. LM_ERR("malformed modparam\n"); \
  177. return -1; \
  178. }
  179. #define CHECK_ALLOC(p) \
  180. if (!(p)) { \
  181. LM_ERR("no memory left\n"); \
  182. return -1; \
  183. }
  184. void
  185. destroy_list(AVP_List *list) {
  186. AVP_List *cur, *next;
  187. cur = list;
  188. while (cur) {
  189. next = cur->next;
  190. pkg_free(cur);
  191. cur = next;
  192. }
  193. }
  194. int
  195. parse_param(void *val, AVP_List** avps) {
  196. char *p;
  197. str s, content;
  198. AVP_List *mp = NULL;
  199. //LM_DBG("%.*s\n", content.len, content.s);
  200. content.s = (char*) val;
  201. content.len = strlen(content.s);
  202. p = (char*) pkg_malloc (content.len + 1);
  203. CHECK_ALLOC(p);
  204. p[content.len] = '\0';
  205. memcpy(p, content.s, content.len);
  206. for (;*p != '\0';) {
  207. mp = (AVP_List*) pkg_malloc (sizeof(AVP_List));
  208. CHECK_ALLOC(mp);
  209. mp->next = *avps;
  210. mp->pv = (pv_spec_p) pkg_malloc (sizeof(pv_spec_t));
  211. CHECK_ALLOC(mp->pv);
  212. for (; isspace(*p); p++);
  213. CHECK_COND(*p != '\0');
  214. mp->name.s = p;
  215. for(; isgraph(*p) && *p != '='; p++)
  216. CHECK_COND(*p != '\0');
  217. mp->name.len = p - mp->name.s;
  218. for (; isspace(*p); p++);
  219. CHECK_COND(*p != '\0' && *p == '=');
  220. p++;
  221. //LM_DBG("%.*s\n", mp->name.len, mp->name.s);
  222. for (; isspace(*p); p++);
  223. CHECK_COND(*p != '\0' && *p == '$');
  224. s.s = p;
  225. s.len = strlen(p);
  226. p = pv_parse_spec(&s, mp->pv);
  227. for (; isspace(*p); p++);
  228. *avps = mp;
  229. }
  230. return 0;
  231. }
  232. int
  233. parse_param_init(unsigned int type, void *val) {
  234. if (parse_param(val, &cc_init_avps) == -1)
  235. return E_CFG;
  236. return 0;
  237. }
  238. int
  239. parse_param_start(unsigned int type, void *val) {
  240. if (parse_param(val, &cc_start_avps) == -1)
  241. return E_CFG;
  242. return 0;
  243. }
  244. int
  245. parse_param_stop(unsigned int type, void *val) {
  246. if (parse_param(val, &cc_stop_avps) == -1)
  247. return E_CFG;
  248. return 0;
  249. }
  250. // Functions dealing with strings
  251. //
  252. // returns string with whitespace trimmed from left end
  253. static inline void
  254. ltrim(str *string)
  255. {
  256. while (string->len>0 && isspace((int)*(string->s))) {
  257. string->len--;
  258. string->s++;
  259. }
  260. }
  261. // returns string with whitespace trimmed from right end
  262. static inline void
  263. rtrim(str *string)
  264. {
  265. char *ptr;
  266. ptr = string->s + string->len - 1;
  267. while (string->len>0 && (*ptr==0 || isspace((int)*ptr))) {
  268. string->len--;
  269. ptr--;
  270. }
  271. }
  272. // returns string with whitespace trimmed from both ends
  273. static inline void
  274. trim(str *string)
  275. {
  276. ltrim(string);
  277. rtrim(string);
  278. }
  279. // Message checking and parsing
  280. //
  281. static Bool
  282. has_to_tag(struct sip_msg *msg)
  283. {
  284. str tag;
  285. if (!msg->to) {
  286. if (parse_headers(msg, HDR_TO_F, 0)==-1) {
  287. LOG(L_ERR, "cannot parse 'To' header\n");
  288. return False;
  289. }
  290. if (!msg->to) {
  291. LOG(L_ERR, "missing 'To' header\n");
  292. return False;
  293. }
  294. }
  295. tag = get_to(msg)->tag_value;
  296. if (tag.s==NULL || tag.len==0) {
  297. return False;
  298. }
  299. return True;
  300. }
  301. // Get canonical request URI
  302. static str
  303. get_canonical_request_uri(struct sip_msg* msg)
  304. {
  305. int_str value;
  306. if (!search_first_avp(canonical_uri_avp.type | AVP_VAL_STR,
  307. canonical_uri_avp.name, &value, NULL) ||
  308. value.s.s==NULL || value.s.len==0) {
  309. return *GET_RURI(msg);
  310. }
  311. return value.s;
  312. }
  313. // Get caller signaling IP
  314. static str
  315. get_signaling_ip(struct sip_msg* msg)
  316. {
  317. int_str value;
  318. if (!search_first_avp(signaling_ip_avp.type | AVP_VAL_STR,
  319. signaling_ip_avp.name, &value, NULL) ||
  320. !value.s.s || value.s.len==0) {
  321. value.s.s = ip_addr2a(&msg->rcv.src_ip);
  322. value.s.len = strlen(value.s.s);
  323. }
  324. return value.s;
  325. }
  326. // Get SIP application type
  327. static str
  328. get_sip_application(struct sip_msg* msg)
  329. {
  330. int_str value;
  331. if (!search_first_avp(sip_application_avp.type | AVP_VAL_STR,
  332. sip_application_avp.name, &value, NULL) ||
  333. !value.s.s || value.s.len==0) {
  334. value.s.s = "audio";
  335. value.s.len = strlen(value.s.s);
  336. }
  337. return value.s;
  338. }
  339. static str
  340. get_diverter(struct sip_msg *msg)
  341. {
  342. struct hdr_field *header;
  343. dig_cred_t *credentials;
  344. int_str avpname, avpvalue;
  345. static str diverter;
  346. diverter.s = "None";
  347. diverter.len = 4;
  348. avpname.n = diverter_avp_id;
  349. if (search_first_avp(AVP_VAL_STR, avpname, &avpvalue, NULL)) {
  350. // have a diverted call
  351. diverter = avpvalue.s;
  352. } else {
  353. get_authorized_cred(msg->proxy_auth, &header);
  354. if (header) {
  355. credentials = &((auth_body_t*)(header->parsed))->digest;
  356. } else {
  357. if (parse_headers(msg, HDR_PROXYAUTH_F, 0) == -1) {
  358. LOG(L_ERR, "cannot parse Proxy-Authorization header\n");
  359. return diverter;
  360. }
  361. if (!msg->proxy_auth)
  362. return diverter;
  363. if (parse_credentials(msg->proxy_auth) != 0) {
  364. LOG(L_ERR, "cannot parse credentials\n");
  365. return diverter;
  366. }
  367. credentials = &((auth_body_t*)(msg->proxy_auth->parsed))->digest;
  368. }
  369. if (credentials->username.user.len > 0 &&
  370. credentials->username.domain.len > 0 &&
  371. credentials->realm.len == 0 &&
  372. credentials->nonce.len == 0 &&
  373. credentials->response.len == 0) {
  374. // this is a call diverted from the failure route
  375. // and sent back to proxy with append_pa_hf()
  376. diverter = credentials->username.whole;
  377. }
  378. }
  379. return diverter;
  380. }
  381. static CallInfo*
  382. get_call_info(struct sip_msg *msg, CallControlAction action)
  383. {
  384. static CallInfo call_info;
  385. int headers;
  386. memset(&call_info, 0, sizeof(struct CallInfo));
  387. switch (action) {
  388. case CAInitialize:
  389. headers = HDR_CALLID_F|HDR_FROM_F;
  390. break;
  391. case CAStart:
  392. case CAStop:
  393. headers = HDR_CALLID_F;
  394. break;
  395. default:
  396. // Invalid action. Should never get here.
  397. assert(False);
  398. return NULL;
  399. }
  400. if (parse_headers(msg, headers, 0) == -1) {
  401. LOG(L_ERR, "cannot parse required headers\n");
  402. return NULL;
  403. }
  404. if (headers & HDR_CALLID_F) {
  405. if (msg->callid == NULL) {
  406. LOG(L_ERR, "missing Call-ID header\n");
  407. return NULL;
  408. }
  409. call_info.callid = msg->callid->body;
  410. trim(&call_info.callid);
  411. }
  412. if (headers & HDR_FROM_F) {
  413. struct to_body *from; // yeah. suggestive structure name ;)
  414. if (msg->from == NULL) {
  415. LOG(L_ERR, "missing From header\n");
  416. return NULL;
  417. }
  418. if (!msg->from->parsed && parse_from_header(msg)==-1) {
  419. LOG(L_ERR, "cannot parse From header\n");
  420. return NULL;
  421. }
  422. from = get_from(msg);
  423. if (from->body.s==NULL || from->body.len==0) {
  424. LOG(L_ERR, "missing From\n");
  425. return NULL;
  426. }
  427. if (from->tag_value.s==NULL || from->tag_value.len==0) {
  428. LOG(L_ERR, "missing From tag\n");
  429. return NULL;
  430. }
  431. call_info.from = from->body;
  432. call_info.from_tag = from->tag_value;
  433. }
  434. if (action == CAInitialize) {
  435. call_info.ruri = get_canonical_request_uri(msg);
  436. call_info.diverter = get_diverter(msg);
  437. call_info.source_ip = get_signaling_ip(msg);
  438. call_info.sip_application = get_sip_application(msg);
  439. }
  440. call_info.action = action;
  441. return &call_info;
  442. }
  443. static char*
  444. make_custom_request(struct sip_msg *msg, CallInfo *call)
  445. {
  446. static char request[8192];
  447. int len = 0;
  448. AVP_List *al;
  449. pv_value_t pt;
  450. switch (call->action) {
  451. case CAInitialize:
  452. al = cc_init_avps;
  453. break;
  454. case CAStart:
  455. al = cc_start_avps;
  456. break;
  457. case CAStop:
  458. al = cc_stop_avps;
  459. break;
  460. default:
  461. // should never get here, but keep gcc from complaining
  462. assert(False);
  463. return NULL;
  464. }
  465. for (; al; al = al->next) {
  466. pv_get_spec_value(msg, al->pv, &pt);
  467. if (pt.flags & PV_VAL_INT) {
  468. len += snprintf(request + len, sizeof(request),
  469. "%.*s = %d ", al->name.len, al->name.s,
  470. pt.ri);
  471. } else if (pt.flags & PV_VAL_STR) {
  472. len += snprintf(request + len, sizeof(request),
  473. "%.*s = %.*s ", al->name.len, al->name.s,
  474. pt.rs.len, pt.rs.s);
  475. }
  476. if (len >= sizeof(request)) {
  477. LM_ERR("callcontrol request is longer than %ld bytes\n", (unsigned long)sizeof(request));
  478. return NULL;
  479. }
  480. }
  481. return request;
  482. }
  483. static char*
  484. make_default_request(CallInfo *call)
  485. {
  486. static char request[8192];
  487. int len;
  488. switch (call->action) {
  489. case CAInitialize:
  490. len = snprintf(request, sizeof(request),
  491. "init\r\n"
  492. "ruri: %.*s\r\n"
  493. "diverter: %.*s\r\n"
  494. "sourceip: %.*s\r\n"
  495. "callid: %.*s\r\n"
  496. "from: %.*s\r\n"
  497. "fromtag: %.*s\r\n"
  498. "sip_application: %.*s\r\n"
  499. "\r\n",
  500. call->ruri.len, call->ruri.s,
  501. call->diverter.len, call->diverter.s,
  502. call->source_ip.len, call->source_ip.s,
  503. call->callid.len, call->callid.s,
  504. call->from.len, call->from.s,
  505. call->from_tag.len, call->from_tag.s,
  506. call->sip_application.len, call->sip_application.s);
  507. if (len >= sizeof(request)) {
  508. LOG(L_ERR, "callcontrol request is longer than %ld bytes\n", (unsigned long)sizeof(request));
  509. return NULL;
  510. }
  511. break;
  512. case CAStart:
  513. len = snprintf(request, sizeof(request),
  514. "start\r\n"
  515. "callid: %.*s\r\n"
  516. "dialogid: %d:%d\r\n"
  517. "\r\n",
  518. call->callid.len, call->callid.s,
  519. call->dialog_id.h_entry, call->dialog_id.h_id);
  520. if (len >= sizeof(request)) {
  521. LOG(L_ERR, "callcontrol request is longer than %ld bytes\n", (unsigned long)sizeof(request));
  522. return NULL;
  523. }
  524. break;
  525. case CAStop:
  526. len = snprintf(request, sizeof(request),
  527. "stop\r\n"
  528. "callid: %.*s\r\n"
  529. "\r\n",
  530. call->callid.len, call->callid.s);
  531. if (len >= sizeof(request)) {
  532. LOG(L_ERR, "callcontrol request is longer than %ld bytes\n", (unsigned long)sizeof(request));
  533. return NULL;
  534. }
  535. break;
  536. default:
  537. // should never get here, but keep gcc from complaining
  538. assert(False);
  539. return NULL;
  540. }
  541. return request;
  542. }
  543. // Functions dealing with the external call_control helper
  544. //
  545. static Bool
  546. callcontrol_connect(void)
  547. {
  548. struct sockaddr_un addr;
  549. if (callcontrol_socket.sock >= 0)
  550. return True;
  551. if (callcontrol_socket.last_failure + RETRY_INTERVAL > time(NULL))
  552. return False;
  553. memset(&addr, 0, sizeof(addr));
  554. addr.sun_family = AF_LOCAL;
  555. strncpy(addr.sun_path, callcontrol_socket.name, sizeof(addr.sun_path) - 1);
  556. #ifdef HAVE_SOCKADDR_SA_LEN
  557. addr.sun_len = strlen(addr.sun_path);
  558. #endif
  559. callcontrol_socket.sock = socket(AF_LOCAL, SOCK_STREAM, 0);
  560. if (callcontrol_socket.sock < 0) {
  561. LOG(L_ERR, "can't create socket\n");
  562. callcontrol_socket.last_failure = time(NULL);
  563. return False;
  564. }
  565. if (connect(callcontrol_socket.sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
  566. LOG(L_ERR, "failed to connect to %s: %s\n", callcontrol_socket.name, strerror(errno));
  567. close(callcontrol_socket.sock);
  568. callcontrol_socket.sock = -1;
  569. callcontrol_socket.last_failure = time(NULL);
  570. return False;
  571. }
  572. return True;
  573. }
  574. static void
  575. callcontrol_disconnect(void)
  576. {
  577. if (callcontrol_socket.sock < 0)
  578. return;
  579. close(callcontrol_socket.sock);
  580. callcontrol_socket.sock = -1;
  581. callcontrol_socket.last_failure = time(NULL);
  582. }
  583. static char*
  584. send_command(char *command)
  585. {
  586. int cmd_len, bytes, tries, sent, received, count;
  587. struct timeval timeout;
  588. fd_set rset;
  589. if (!callcontrol_connect())
  590. return NULL;
  591. cmd_len = strlen(command);
  592. for (sent=0, tries=0; sent<cmd_len && tries<3; tries++, sent+=bytes) {
  593. do
  594. bytes = send(callcontrol_socket.sock, command+sent, cmd_len-sent, MSG_DONTWAIT|MSG_NOSIGNAL);
  595. while (bytes == -1 && errno == EINTR);
  596. if (bytes == -1) {
  597. switch (errno) {
  598. case ECONNRESET:
  599. case EPIPE:
  600. callcontrol_disconnect();
  601. callcontrol_socket.last_failure = 0; // we want to reconnect immediately
  602. if (callcontrol_connect()) {
  603. sent = bytes = 0;
  604. continue;
  605. } else {
  606. LOG(L_ERR, "connection with callcontrol did die\n");
  607. }
  608. break;
  609. case EACCES:
  610. LOG(L_ERR, "permission denied sending to %s\n", callcontrol_socket.name);
  611. break;
  612. case EWOULDBLOCK:
  613. // this shouldn't happen as we read back all the answer after a request.
  614. // if it would block, it means there is an error.
  615. LOG(L_ERR, "sending command would block!\n");
  616. break;
  617. default:
  618. LOG(L_ERR, "%d: %s\n", errno, strerror(errno));
  619. break;
  620. }
  621. callcontrol_disconnect();
  622. return NULL;
  623. }
  624. }
  625. if (sent < cmd_len) {
  626. LOG(L_ERR, "couldn't send complete command after 3 tries\n");
  627. callcontrol_disconnect();
  628. return NULL;
  629. }
  630. callcontrol_socket.data[0] = 0;
  631. received = 0;
  632. while (True) {
  633. FD_ZERO(&rset);
  634. FD_SET(callcontrol_socket.sock, &rset);
  635. timeout.tv_sec = callcontrol_socket.timeout / 1000;
  636. timeout.tv_usec = (callcontrol_socket.timeout % 1000) * 1000;
  637. do
  638. count = select(callcontrol_socket.sock + 1, &rset, NULL, NULL, &timeout);
  639. while (count == -1 && errno == EINTR);
  640. if (count == -1) {
  641. LOG(L_ERR, "select failed: %d: %s\n", errno, strerror(errno));
  642. callcontrol_disconnect();
  643. return NULL;
  644. } else if (count == 0) {
  645. LOG(L_ERR, "did timeout waiting for an answer\n");
  646. callcontrol_disconnect();
  647. return NULL;
  648. } else {
  649. do
  650. bytes = recv(callcontrol_socket.sock, callcontrol_socket.data+received, BUFFER_SIZE-1-received, 0);
  651. while (bytes == -1 && errno == EINTR);
  652. if (bytes == -1) {
  653. LOG(L_ERR, "failed to read answer: %d: %s\n", errno, strerror(errno));
  654. callcontrol_disconnect();
  655. return NULL;
  656. } else if (bytes == 0) {
  657. LOG(L_ERR, "connection with callcontrol closed\n");
  658. callcontrol_disconnect();
  659. return NULL;
  660. } else {
  661. callcontrol_socket.data[received+bytes] = 0;
  662. if (strstr(callcontrol_socket.data+received, "\r\n")!=NULL) {
  663. break;
  664. }
  665. received += bytes;
  666. }
  667. }
  668. }
  669. return callcontrol_socket.data;
  670. }
  671. // Call control processing
  672. //
  673. // Return codes:
  674. // 2 - No limit
  675. // 1 - Limited
  676. // -1 - No credit
  677. // -2 - Locked
  678. // -5 - Internal error (message parsing, communication, ...)
  679. static int
  680. call_control_initialize(struct sip_msg *msg)
  681. {
  682. CallInfo *call;
  683. char *message, *result = NULL;
  684. call = get_call_info(msg, CAInitialize);
  685. if (!call) {
  686. LOG(L_ERR, "can't retrieve call info\n");
  687. return -5;
  688. }
  689. if (!cc_init_avps)
  690. message = make_default_request(call);
  691. else
  692. message = make_custom_request(msg, call);
  693. if (!message)
  694. return -5;
  695. result = send_command(message);
  696. if (result==NULL) {
  697. return -5;
  698. } else if (strcasecmp(result, "No limit\r\n")==0) {
  699. return 2;
  700. } else if (strcasecmp(result, "Limited\r\n")==0) {
  701. return 1;
  702. } else if (strcasecmp(result, "No credit\r\n")==0) {
  703. return -1;
  704. } else if (strcasecmp(result, "Locked\r\n")==0) {
  705. return -2;
  706. } else {
  707. return -5;
  708. }
  709. }
  710. // Called during a dialog for start and update requests
  711. //
  712. // Return codes:
  713. // 1 - Ok
  714. // -1 - Session not found
  715. // -5 - Internal error (message parsing, communication, ...)
  716. static int
  717. call_control_start(struct sip_msg *msg, struct dlg_cell *dlg)
  718. {
  719. CallInfo *call;
  720. char *message, *result;
  721. call = get_call_info(msg, CAStart);
  722. if (!call) {
  723. LOG(L_ERR, "can't retrieve call info\n");
  724. return -5;
  725. }
  726. call->dialog_id.h_entry = dlg->h_entry;
  727. call->dialog_id.h_id = dlg->h_id;
  728. if (!cc_start_avps)
  729. message = make_default_request(call);
  730. else
  731. message = make_custom_request(msg, call);
  732. if (!message)
  733. return -5;
  734. result = send_command(message);
  735. if (result==NULL) {
  736. return -5;
  737. } else if (strcasecmp(result, "Ok\r\n")==0) {
  738. return 1;
  739. } else if (strcasecmp(result, "Not found\r\n")==0) {
  740. return -1;
  741. } else {
  742. return -5;
  743. }
  744. }
  745. // Called during a dialog ending to stop callcontrol
  746. //
  747. // Return codes:
  748. // 1 - Ok
  749. // -1 - Session not found
  750. // -5 - Internal error (message parsing, communication, ...)
  751. static int
  752. call_control_stop(struct sip_msg *msg, str callid)
  753. {
  754. CallInfo call;
  755. char *message, *result;
  756. call.action = CAStop;
  757. call.callid = callid;
  758. if (!cc_stop_avps)
  759. message = make_default_request(&call);
  760. else
  761. message = make_custom_request(msg, &call);
  762. if (!message)
  763. return -5;
  764. result = send_command(message);
  765. if (result==NULL) {
  766. return -5;
  767. } else if (strcasecmp(result, "Ok\r\n")==0) {
  768. return 1;
  769. } else if (strcasecmp(result, "Not found\r\n")==0) {
  770. return -1;
  771. } else {
  772. return -5;
  773. }
  774. }
  775. // Dialog callbacks and helpers
  776. //
  777. typedef enum {
  778. CCInactive = 0,
  779. CCActive
  780. } CallControlState;
  781. static void
  782. __dialog_replies(struct dlg_cell *dlg, int type, struct dlg_cb_params *_params)
  783. {
  784. struct sip_msg *reply = _params->rpl;
  785. if (reply!=FAKED_REPLY && reply->REPLY_STATUS==200) {
  786. call_control_start(reply, dlg);
  787. }
  788. }
  789. static void
  790. __dialog_ended(struct dlg_cell *dlg, int type, struct dlg_cb_params *_params)
  791. {
  792. if ((int)(long)*_params->param == CCActive) {
  793. struct sip_msg* msg = _params->rpl;
  794. if( !msg || msg == FAKED_REPLY)
  795. msg = _params->req;
  796. call_control_stop(msg, dlg->callid);
  797. *_params->param = CCInactive;
  798. }
  799. }
  800. static void
  801. __dialog_created(struct dlg_cell *dlg, int type, struct dlg_cb_params *_params)
  802. {
  803. struct sip_msg *request = _params->req;
  804. if (request->REQ_METHOD != METHOD_INVITE)
  805. return;
  806. if ((request->msg_flags & FL_USE_CALL_CONTROL) == 0)
  807. return;
  808. if (dlg_api.register_dlgcb(dlg, DLGCB_RESPONSE_FWDED, __dialog_replies, NULL, NULL) != 0)
  809. LOG(L_ERR, "cannot register callback for dialog confirmation\n");
  810. if (dlg_api.register_dlgcb(dlg, DLGCB_TERMINATED | DLGCB_FAILED | DLGCB_EXPIRED | DLGCB_DESTROY, __dialog_ended, (void*)CCActive, NULL) != 0)
  811. LOG(L_ERR, "cannot register callback for dialog termination\n");
  812. // reset the flag to indicate that the dialog for callcontrol was created
  813. request->msg_flags &= ~FL_USE_CALL_CONTROL;
  814. }
  815. static void
  816. __dialog_loaded(struct dlg_cell *dlg, int type, struct dlg_cb_params *_params)
  817. {
  818. if (dlg_api.register_dlgcb(dlg, DLGCB_RESPONSE_FWDED, __dialog_replies, NULL, NULL) != 0)
  819. LOG(L_ERR, "cannot register callback for dialog confirmation\n");
  820. if (dlg_api.register_dlgcb(dlg, DLGCB_TERMINATED | DLGCB_FAILED | DLGCB_EXPIRED | DLGCB_DESTROY, __dialog_ended, (void*)CCActive, NULL) != 0)
  821. LOG(L_ERR, "cannot register callback for dialog termination\n");
  822. }
  823. // Public API
  824. //
  825. // Return codes:
  826. // 2 - No limit
  827. // 1 - Limited
  828. // -1 - No credit
  829. // -2 - Locked
  830. // -3 - No provider
  831. // -5 - Internal error (message parsing, communication, ...)
  832. static int
  833. CallControl(struct sip_msg *msg, char *str1, char *str2)
  834. {
  835. int result;
  836. if (disable)
  837. return 2;
  838. if (msg->first_line.type!=SIP_REQUEST || msg->REQ_METHOD!=METHOD_INVITE || has_to_tag(msg)) {
  839. LOG(L_WARN, "call_control should only be called for the first INVITE\n");
  840. return -5;
  841. }
  842. result = call_control_initialize(msg);
  843. if (result == 1) {
  844. // A call with a time limit that will be traced by callcontrol
  845. msg->msg_flags |= FL_USE_CALL_CONTROL;
  846. setflag(msg, dialog_flag); // have the dialog module trace this dialog
  847. }
  848. return result;
  849. }
  850. // Module management: initialization/destroy/function-parameter-fixing/...
  851. //
  852. static int
  853. mod_init(void)
  854. {
  855. pv_spec_t avp_spec;
  856. int *param;
  857. modparam_t type;
  858. // initialize the canonical_uri_avp structure
  859. if (canonical_uri_avp.spec.s==NULL || *(canonical_uri_avp.spec.s)==0) {
  860. LOG(L_ERR, "missing/empty canonical_uri_avp parameter. using default.\n");
  861. canonical_uri_avp.spec.s = CANONICAL_URI_AVP_SPEC;
  862. }
  863. canonical_uri_avp.spec.len = strlen(canonical_uri_avp.spec.s);
  864. if (pv_parse_spec(&(canonical_uri_avp.spec), &avp_spec)==0 || avp_spec.type!=PVT_AVP) {
  865. LOG(L_CRIT, "invalid AVP specification for canonical_uri_avp: `%s'\n", canonical_uri_avp.spec.s);
  866. return -1;
  867. }
  868. if (pv_get_avp_name(0, &(avp_spec.pvp), &(canonical_uri_avp.name), &(canonical_uri_avp.type))!=0) {
  869. LOG(L_CRIT, "invalid AVP specification for canonical_uri_avp: `%s'\n", canonical_uri_avp.spec.s);
  870. return -1;
  871. }
  872. // initialize the signaling_ip_avp structure
  873. if (signaling_ip_avp.spec.s==NULL || *(signaling_ip_avp.spec.s)==0) {
  874. LOG(L_ERR, "missing/empty signaling_ip_avp parameter. using default.\n");
  875. signaling_ip_avp.spec.s = SIGNALING_IP_AVP_SPEC;
  876. }
  877. signaling_ip_avp.spec.len = strlen(signaling_ip_avp.spec.s);
  878. if (pv_parse_spec(&(signaling_ip_avp.spec), &avp_spec)==0 || avp_spec.type!=PVT_AVP) {
  879. LOG(L_CRIT, "invalid AVP specification for signaling_ip_avp: `%s'\n", signaling_ip_avp.spec.s);
  880. return -1;
  881. }
  882. if (pv_get_avp_name(0, &(avp_spec.pvp), &(signaling_ip_avp.name), &(signaling_ip_avp.type))!=0) {
  883. LOG(L_CRIT, "invalid AVP specification for signaling_ip_avp: `%s'\n", signaling_ip_avp.spec.s);
  884. return -1;
  885. }
  886. // initialize the sip_application_avp structure
  887. if (sip_application_avp.spec.s==NULL || *(sip_application_avp.spec.s)==0) {
  888. LOG(L_ERR, "missing/empty sip_application_avp parameter. using default.\n");
  889. sip_application_avp.spec.s = SIP_APPLICATION_AVP_SPEC;
  890. }
  891. sip_application_avp.spec.len = strlen(sip_application_avp.spec.s);
  892. if (pv_parse_spec(&(sip_application_avp.spec), &avp_spec)==0 || avp_spec.type!=PVT_AVP) {
  893. LOG(L_CRIT, "invalid AVP specification for sip_application_avp: `%s'\n", sip_application_avp.spec.s);
  894. return -1;
  895. }
  896. if (pv_get_avp_name(0, &(avp_spec.pvp), &(sip_application_avp.name), &(sip_application_avp.type))!=0) {
  897. LOG(L_CRIT, "invalid AVP specification for sip_application_avp: `%s'\n", sip_application_avp.spec.s);
  898. return -1;
  899. }
  900. // bind to the dialog API
  901. if (load_dlg_api(&dlg_api)!=0) {
  902. LOG(L_CRIT, "cannot load the dialog module API\n");
  903. return -1;
  904. }
  905. // load dlg_flag and default_timeout parameters from the dialog module
  906. param = find_param_export(find_module_by_name("dialog"), "dlg_flag", INT_PARAM, &type);
  907. if (!param) {
  908. LOG(L_CRIT, "cannot find dlg_flag parameter in the dialog module\n");
  909. return -1;
  910. }
  911. if (type != INT_PARAM) {
  912. LOG(L_CRIT, "dlg_flag parameter found but with wrong type: %d\n", type);
  913. return -1;
  914. }
  915. dialog_flag = *param;
  916. // register dialog creation callback
  917. if (dlg_api.register_dlgcb(NULL, DLGCB_CREATED, __dialog_created, NULL, NULL) != 0) {
  918. LOG(L_CRIT, "cannot register callback for dialog creation\n");
  919. return -1;
  920. }
  921. // register dialog loading callback
  922. if (dlg_api.register_dlgcb(NULL, DLGCB_LOADED, __dialog_loaded, NULL, NULL) != 0) {
  923. LOG(L_ERR, "cannot register callback for dialogs loaded from the database\n");
  924. }
  925. // register a pre-script callback to automatically enable dialog tracing
  926. if (register_script_cb(postprocess_request, POST_SCRIPT_CB|REQUEST_CB, 0) != 0) {
  927. LOG(L_CRIT, "ERROR:call_control:mod_init: could not register request postprocessing callback\n");
  928. return -1;
  929. }
  930. return 0;
  931. }
  932. static int
  933. child_init(int rank)
  934. {
  935. // initialize the connection to callcontrol if needed
  936. if (!disable)
  937. callcontrol_connect();
  938. return 0;
  939. }
  940. static void
  941. destroy(void) {
  942. if (cc_init_avps)
  943. destroy_list(cc_init_avps);
  944. if (cc_start_avps)
  945. destroy_list(cc_start_avps);
  946. if (cc_stop_avps)
  947. destroy_list(cc_stop_avps);
  948. }
  949. // Postprocess a request after the main script route is done.
  950. //
  951. // After all script processing is done, check if the dialog was actually
  952. // created to take care of call control. If the FL_USE_CALL_CONTROL flag
  953. // is still set, then the dialog creation callback was not called which
  954. // means that there was a failure relaying the message and we have to
  955. // tell the call control application to discard the call, otherwise it
  956. // would remain dangling until it expires.
  957. //
  958. static int
  959. postprocess_request(struct sip_msg *msg, unsigned int flags, void *_param)
  960. {
  961. CallInfo *call;
  962. if ((msg->msg_flags & FL_USE_CALL_CONTROL) == 0)
  963. return 1;
  964. // the FL_USE_CALL_CONTROL flag is still set => the dialog was not created
  965. LOG(L_WARN, "dialog to trace controlled call was not created. discarding callcontrol.");
  966. call = get_call_info(msg, CAStop);
  967. if (!call) {
  968. LOG(L_ERR, "can't retrieve call info\n");
  969. return -1;
  970. }
  971. call_control_stop(msg, call->callid);
  972. return 1;
  973. }