utils/functions.c
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #include <curl/curl.h>
00026
00027 #include "../../mod_fix.h"
00028 #include "../../pvar.h"
00029 #include "../../route_struct.h"
00030 #include "../../ut.h"
00031 #include "../../mem/mem.h"
00032 #include "../../parser/msg_parser.h"
00033
00034 #include "utils.h"
00035
00036
00037
00038
00039
00040
00041 size_t write_function( void *ptr, size_t size, size_t nmemb, void *stream)
00042 {
00043
00044 char* data;
00045
00046 data = (char*)malloc((size* nmemb) + 1);
00047 if (data == NULL) {
00048 LM_ERR("cannot allocate memory for stream\n");
00049 return CURLE_WRITE_ERROR;
00050 }
00051
00052 memcpy(data, (char*)ptr, size* nmemb);
00053 data[nmemb] = '\0';
00054
00055 *((char**) stream) = data;
00056
00057 return size* nmemb;
00058 }
00059
00060
00061
00062
00063
00064
00065 int http_query(struct sip_msg* _m, char* _url, char* _dst)
00066 {
00067 CURL *curl;
00068 CURLcode res;
00069 str value;
00070 char *url, *at;
00071 char* stream;
00072 long stat;
00073 pv_spec_t *dst;
00074 pv_value_t val;
00075
00076 if (fixup_get_svalue(_m, (gparam_p)_url, &value) != 0) {
00077 LM_ERR("cannot get page value\n");
00078 return -1;
00079 }
00080
00081 curl = curl_easy_init();
00082 if (curl == NULL) {
00083 LM_ERR("failed to initialize curl\n");
00084 return -1;
00085 }
00086
00087 url = pkg_malloc(value.len + 1);
00088 if (url == NULL) {
00089 curl_easy_cleanup(curl);
00090 LM_ERR("cannot allocate pkg memory for url\n");
00091 return -1;
00092 }
00093 memcpy(url, value.s, value.len);
00094 *(url + value.len) = (char)0;
00095 curl_easy_setopt(curl, CURLOPT_URL, url);
00096
00097 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, (long)1);
00098 curl_easy_setopt(curl, CURLOPT_TIMEOUT, (long)http_query_timeout);
00099
00100 stream = NULL;
00101 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_function);
00102 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &stream);
00103
00104 res = curl_easy_perform(curl);
00105 pkg_free(url);
00106 curl_easy_cleanup(curl);
00107
00108 if (res != CURLE_OK) {
00109 LM_ERR("failed to perform curl\n");
00110 return -1;
00111 }
00112
00113 curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &stat);
00114 if ((stat >= 200) && (stat < 400)) {
00115 at = index(stream, (char)10);
00116 if (at == NULL) {
00117 at = stream;
00118 }
00119 val.rs.s = stream;
00120 val.rs.len = at - stream;
00121 val.flags = PV_VAL_STR;
00122 dst = (pv_spec_t *)_dst;
00123 dst->setf(_m, &dst->pvp, (int)EQ_T, &val);
00124 }
00125
00126 return stat;
00127 }