1 #include "apachetools.h"
2 #include "opensrf/osrf_app_session.h"
3 #include "opensrf/osrf_system.h"
4 #include "opensrf/osrfConfig.h"
5 #include <opensrf/osrf_json.h>
6 #include <opensrf/osrf_json_xml.h>
7 #include <opensrf/osrf_legacy_json.h>
9 #include <sys/resource.h>
14 #define MODULE_NAME "osrf_json_gateway_module"
15 #define GATEWAY_CONFIG "OSRFGatewayConfig"
16 #define DEFAULT_LOCALE "OSRFDefaultLocale"
17 #define CONFIG_CONTEXT "gateway"
18 #define JSON_PROTOCOL "OSRFGatewayLegacyJSON"
19 #define GATEWAY_USE_LEGACY_JSON 1
21 #define GATEWAY_DEFAULT_CONFIG "/openils/conf/opensrf_core.xml"
24 /* our config structure */
26 char* configfile; /* our bootstrap config file */
27 } osrf_json_gateway_config;
31 } osrf_json_gateway_dir_config;
34 module AP_MODULE_DECLARE_DATA osrf_json_gateway_module;
36 char* osrf_json_default_locale = "en-US";
37 char* osrf_json_gateway_config_file = NULL;
40 osrfStringArray* allowedServices = NULL;
42 static const char* osrf_json_gateway_set_default_locale(cmd_parms *parms, void *config, const char *arg) {
43 osrf_json_default_locale = (char*) arg;
47 static const char* osrf_json_gateway_set_config(cmd_parms *parms, void *config, const char *arg) {
48 osrf_json_gateway_config *cfg;
49 cfg = ap_get_module_config(parms->server->module_config, &osrf_json_gateway_module);
50 cfg->configfile = (char*) arg;
51 osrf_json_gateway_config_file = (char*) arg;
55 static const char* osrf_json_gateway_set_json_proto(cmd_parms *parms, void *config, const char *arg) {
56 osrf_json_gateway_dir_config* cfg = (osrf_json_gateway_dir_config*) config;
57 cfg->legacyJSON = (!strcasecmp((char*) arg, "false")) ? 0 : 1;
61 /* tell apache about our commands */
62 static const command_rec osrf_json_gateway_cmds[] = {
63 AP_INIT_TAKE1( GATEWAY_CONFIG, osrf_json_gateway_set_config,
64 NULL, RSRC_CONF, "osrf json gateway config file"),
65 AP_INIT_TAKE1( DEFAULT_LOCALE, osrf_json_gateway_set_default_locale,
66 NULL, RSRC_CONF, "osrf json gateway default locale"),
67 AP_INIT_TAKE1( JSON_PROTOCOL, osrf_json_gateway_set_json_proto,
68 NULL, ACCESS_CONF, "osrf json gateway config file"),
72 /* build the config object */
73 static void* osrf_json_gateway_create_config( apr_pool_t* p, server_rec* s) {
74 osrf_json_gateway_config* cfg = (osrf_json_gateway_config*)
75 apr_palloc(p, sizeof(osrf_json_gateway_config));
76 cfg->configfile = GATEWAY_DEFAULT_CONFIG;
80 static void* osrf_json_gateway_create_dir_config( apr_pool_t* p, char* dir) {
81 osrf_json_gateway_dir_config* cfg = (osrf_json_gateway_dir_config*)
82 apr_palloc(p, sizeof(osrf_json_gateway_dir_config));
83 cfg->legacyJSON = GATEWAY_USE_LEGACY_JSON;
88 static void osrf_json_gateway_child_init(apr_pool_t *p, server_rec *s) {
90 char* cfg = osrf_json_gateway_config_file;
94 snprintf(buf, 32, "%d", t);
96 if( ! osrfSystemBootstrapClientResc( cfg, CONFIG_CONTEXT, buf ) ) {
97 ap_log_error( APLOG_MARK, APLOG_ERR, 0, s,
98 "Unable to Bootstrap OpenSRF Client with config %s..", cfg);
103 allowedServices = osrfNewStringArray(8);
104 osrfLogInfo(OSRF_LOG_MARK, "Bootstrapping gateway child for requests");
105 osrfConfigGetValueList( NULL, allowedServices, "/services/service" );
108 for( i = 0; i < allowedServices->size; i++ ) {
109 ap_log_error( APLOG_MARK, APLOG_DEBUG, 0, s,
110 "allowed service: %s\n", osrfStringArrayGetString(allowedServices, i));
114 static int osrf_json_gateway_method_handler (request_rec *r) {
116 /* make sure we're needed first thing*/
117 if (strcmp(r->handler, MODULE_NAME )) return DECLINED;
120 osrf_json_gateway_dir_config* dir_conf =
121 ap_get_module_config(r->per_dir_config, &osrf_json_gateway_module);
124 /* provide 2 different JSON parsers and serializers to support legacy JSON */
125 jsonObject* (*parseJSONFunc) (char*) = legacy_jsonParseString;
126 char* (*jsonToStringFunc) (const jsonObject*) = legacy_jsonObjectToJSON;
128 if(dir_conf->legacyJSON) {
129 ap_log_rerror( APLOG_MARK, APLOG_INFO, 0, r, "Using legacy JSON");
132 ap_log_rerror( APLOG_MARK, APLOG_INFO, 0, r, "Not using legacy JSON");
133 parseJSONFunc = jsonParseString;
134 jsonToStringFunc = jsonObjectToJSON;
138 osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: entered request handler");
140 /* verify we are connected */
141 if( !bootstrapped || !osrf_system_get_transport_client()) {
142 ap_log_rerror( APLOG_MARK, APLOG_ERR, 0, r, "Cannot process request "
143 "because the OpenSRF JSON gateway has not been bootstrapped...");
144 usleep( 100000 ); /* 100 milliseconds */
148 osrfLogSetAppname("osrf_json_gw");
150 char* osrf_locale = NULL;
151 char* param_locale = NULL; /* locale for this call */
152 char* service = NULL; /* service to connect to */
153 char* method = NULL; /* method to perform */
154 char* format = NULL; /* method to perform */
155 char* a_l = NULL; /* request api level */
156 char* input_format = NULL; /* POST data format, defaults to 'format' */
160 r->allowed |= (AP_METHOD_BIT << M_GET);
161 r->allowed |= (AP_METHOD_BIT << M_POST);
163 osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: parsing URL params");
164 string_array* mparams = NULL;
165 string_array* params = apacheParseParms(r); /* free me */
166 param_locale = apacheGetFirstParamValue( params, "locale" );
167 service = apacheGetFirstParamValue( params, "service" );
168 method = apacheGetFirstParamValue( params, "method" );
169 format = apacheGetFirstParamValue( params, "format" );
170 input_format = apacheGetFirstParamValue( params, "input_format" );
171 a_l = apacheGetFirstParamValue( params, "api_level" );
172 mparams = apacheGetParamValues( params, "param" ); /* free me */
176 if(input_format == NULL)
177 input_format = format;
179 /* set the user defined timeout value */
181 char* tout = apacheGetFirstParamValue( params, "timeout" ); /* request timeout in seconds */
183 timeout = atoi(tout);
184 osrfLogDebug(OSRF_LOG_MARK, "Client supplied timeout of %d", timeout);
188 api_level = atoi(a_l);
190 if (!strcasecmp(format, "xml")) {
192 ap_set_content_type(r, "application/xml");
194 ap_set_content_type(r, "text/plain");
199 /* ----------------------------------------------------------------- */
200 /* Grab the requested locale using the Accept-Language header*/
203 if ( !param_locale ) {
204 if ( apr_table_get(r->headers_in, "X-OpenSRF-Language") ) {
205 param_locale = strdup( apr_table_get(r->headers_in, "X-OpenSRF-Language") );
206 } else if ( apr_table_get(r->headers_in, "Accept-Language") ) {
207 param_locale = strdup( apr_table_get(r->headers_in, "Accept-Language") );
213 growing_buffer* osrf_locale_buf = buffer_init(16);
214 if (index(param_locale, ',')) {
215 int ind = index(param_locale, ',') - param_locale;
217 for ( i = 0; i < ind - 1 && i < 128; i++ )
218 buffer_add_char( osrf_locale_buf, param_locale[i] );
220 buffer_add( osrf_locale_buf, param_locale );
224 osrf_locale = buffer_release( osrf_locale_buf );
226 osrf_locale = strdup( osrf_json_default_locale );
228 /* ----------------------------------------------------------------- */
231 if(!(service && method) ||
232 !osrfStringArrayContains(allowedServices, service)) {
234 osrfLogError(OSRF_LOG_MARK,
235 "Service [%s] not found or not allowed", service);
236 ret = HTTP_NOT_FOUND;
240 /* This will log all heaers to the apache error log
241 const apr_array_header_t* arr = apr_table_elts(r->headers_in);
244 while( (ptr = apr_array_pop(arr)) ) {
245 apr_table_entry_t* e = (apr_table_entry_t*) ptr;
246 fprintf(stderr, "Table entry: %s : %s\n", e->key, e->val );
251 osrfAppSession* session = osrf_app_client_session_init(service);
252 osrf_app_session_set_locale(session, osrf_locale);
254 double starttime = get_timestamp_millis();
257 if(!strcasecmp(input_format, "json")) {
258 jsonObject * arr = jsonNewObject(NULL);
263 while( (str = osrfStringArrayGetString(mparams, i++)) )
264 jsonObjectPush(arr, parseJSONFunc(str));
266 req_id = osrf_app_session_make_req( session, arr, method, api_level, NULL );
270 * If we receive XML method params, convert each param to a JSON object
271 * and pass the array of JSON object params to the method */
272 if(!strcasecmp(input_format, "xml")) {
273 jsonObject* jsonParams = jsonNewObject(NULL);
277 while( (str = osrfStringArrayGetString(mparams, i++)) ) {
278 jsonObjectPush(jsonParams, jsonXMLToJSONObject(str));
281 req_id = osrf_app_session_make_req( session, jsonParams, method, api_level, NULL );
282 jsonObjectFree(jsonParams);
288 osrfLogError(OSRF_LOG_MARK, "I am unable to communcate with opensrf..going away...");
289 /* we don't want to spawn an intense re-forking storm
290 * if there is no jabber server.. so give it some time before we die */
291 usleep( 100000 ); /* 100 milliseconds */
296 /* ----------------------------------------------------------------- */
297 /* log all requests to the activity log */
298 const char* authtoken = apr_table_get(r->headers_in, "X-OILS-Authtoken");
299 if(!authtoken) authtoken = "";
300 growing_buffer* act = buffer_init(128);
301 buffer_fadd(act, "[%s] [%s] %s %s", r->connection->remote_ip, authtoken, service, method );
302 char* str; int i = 0;
303 while( (str = osrfStringArrayGetString(mparams, i++)) ) {
305 OSRF_BUFFER_ADD(act, " ");
306 OSRF_BUFFER_ADD(act, str);
308 OSRF_BUFFER_ADD(act, ", ");
309 OSRF_BUFFER_ADD(act, str);
313 osrfLogActivity( OSRF_LOG_MARK, act->buf );
315 /* ----------------------------------------------------------------- */
318 osrf_message* omsg = NULL;
320 int statuscode = 200;
322 /* kick off the object */
324 ap_rputs("<response xmlns=\"http://opensrf.org/-/namespaces/gateway/v1\"><payload>", r);
326 ap_rputs("{\"payload\":[", r);
329 char* statusname = NULL;
330 char* statustext = NULL;
333 while((omsg = osrfAppSessionRequestRecv( session, req_id, timeout ))) {
335 statuscode = omsg->status_code;
338 if( ( res = osrfMessageGetResult(omsg)) ) {
341 output = jsonObjectToXML( res );
343 output = jsonToStringFunc( res );
344 if( morethan1 ) ap_rputs(",", r); /* comma between JSON array items */
352 if( statuscode > 299 ) { /* the request returned a low level error */
353 statusname = omsg->status_name ? strdup(omsg->status_name) : strdup("Unknown Error");
354 statustext = omsg->status_text ? strdup(omsg->status_text) : strdup("No Error Message");
355 osrfLogError( OSRF_LOG_MARK, "Gateway received error: %s", statustext );
359 osrf_message_free(omsg);
360 if(statusname) break;
363 double duration = get_timestamp_millis() - starttime;
364 osrfLogDebug(OSRF_LOG_MARK, "gateway request took %f seconds", duration);
368 ap_rputs("</payload>", r);
370 ap_rputs("]",r); /* finish off the payload array */
374 /* add a debug field if the request died */
375 ap_log_rerror( APLOG_MARK, APLOG_INFO, 0, r,
376 "OpenSRF JSON Request returned error: %s -> %s", statusname, statustext );
377 int l = strlen(statusname) + strlen(statustext) + 32;
382 snprintf( buf, l, "<debug>\"%s : %s\"</debug>", statusname, statustext );
387 snprintf(bb, l, "%s : %s", statusname, statustext);
388 jsonObject* tmp = jsonNewObject(bb);
389 char* j = jsonToStringFunc(tmp);
390 snprintf( buf, l, ",\"debug\": %s", j);
401 /* insert the status code */
406 snprintf(buf, 32, "<status>%d</status>", statuscode );
408 snprintf(buf, 32, ",\"status\":%d", statuscode );
413 ap_rputs("</response>", r);
415 ap_rputs( "}", r ); /* finish off the object */
417 osrf_app_session_destroy(session);
420 osrfLogInfo(OSRF_LOG_MARK, "Completed processing service=%s, method=%s", service, method);
422 string_array_destroy(params);
423 string_array_destroy(mparams);
425 osrfLogDebug(OSRF_LOG_MARK, "Gateway served %d requests", ++numserved);
433 static void osrf_json_gateway_register_hooks (apr_pool_t *p) {
434 ap_hook_handler(osrf_json_gateway_method_handler, NULL, NULL, APR_HOOK_MIDDLE);
435 ap_hook_child_init(osrf_json_gateway_child_init,NULL,NULL,APR_HOOK_MIDDLE);
439 module AP_MODULE_DECLARE_DATA osrf_json_gateway_module = {
440 STANDARD20_MODULE_STUFF,
441 osrf_json_gateway_create_dir_config,
443 osrf_json_gateway_create_config,
445 osrf_json_gateway_cmds,
446 osrf_json_gateway_register_hooks,