Patch from Scott McKellar:
[OpenSRF.git] / src / gateway / osrf_json_gateway.c
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>
8 #include <sys/time.h>
9 #include <sys/resource.h>
10 #include <unistd.h>
11 #include <strings.h>
12
13
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
20
21 #define GATEWAY_DEFAULT_CONFIG "/openils/conf/opensrf_core.xml"
22
23
24 /* our config structure */
25 typedef struct { 
26         char* configfile;  /* our bootstrap config file */
27 } osrf_json_gateway_config;
28
29 typedef struct { 
30         int legacyJSON;
31 } osrf_json_gateway_dir_config;
32
33
34 module AP_MODULE_DECLARE_DATA osrf_json_gateway_module;
35
36 char* osrf_json_default_locale = "en-US";
37 char* osrf_json_gateway_config_file = NULL;
38 int bootstrapped = 0;
39 int numserved = 0;
40 osrfStringArray* allowedServices = NULL;
41
42 static const char* osrf_json_gateway_set_default_locale(cmd_parms *parms, void *config, const char *arg) {
43         if (arg)
44                 osrf_json_default_locale = (char*) arg;
45         return NULL;
46 }
47
48 static const char* osrf_json_gateway_set_config(cmd_parms *parms, void *config, const char *arg) {
49         osrf_json_gateway_config  *cfg;
50         cfg = ap_get_module_config(parms->server->module_config, &osrf_json_gateway_module);
51         cfg->configfile = (char*) arg;
52         osrf_json_gateway_config_file = (char*) arg;
53         return NULL;
54 }
55
56 static const char* osrf_json_gateway_set_json_proto(cmd_parms *parms, void *config, const char *arg) {
57         osrf_json_gateway_dir_config* cfg = (osrf_json_gateway_dir_config*) config;
58         cfg->legacyJSON = (!strcasecmp((char*) arg, "false")) ? 0 : 1;
59         return NULL;
60 }
61
62 /* tell apache about our commands */
63 static const command_rec osrf_json_gateway_cmds[] = {
64         AP_INIT_TAKE1( GATEWAY_CONFIG, osrf_json_gateway_set_config, 
65                         NULL, RSRC_CONF, "osrf json gateway config file"),
66         AP_INIT_TAKE1( DEFAULT_LOCALE, osrf_json_gateway_set_default_locale, 
67                         NULL, RSRC_CONF, "osrf json gateway default locale"),
68         AP_INIT_TAKE1( JSON_PROTOCOL, osrf_json_gateway_set_json_proto,
69                         NULL, ACCESS_CONF, "osrf json gateway config file"),
70         {NULL}
71 };
72
73 /* build the config object */
74 static void* osrf_json_gateway_create_config( apr_pool_t* p, server_rec* s) {
75         osrf_json_gateway_config* cfg = (osrf_json_gateway_config*) 
76                         apr_palloc(p, sizeof(osrf_json_gateway_config));
77         cfg->configfile = GATEWAY_DEFAULT_CONFIG;
78         return (void*) cfg;
79 }
80
81 static void* osrf_json_gateway_create_dir_config( apr_pool_t* p, char* dir) {
82         osrf_json_gateway_dir_config* cfg = (osrf_json_gateway_dir_config*) 
83                         apr_palloc(p, sizeof(osrf_json_gateway_dir_config));
84         cfg->legacyJSON = GATEWAY_USE_LEGACY_JSON;
85         return (void*) cfg;
86 }
87
88
89 static void osrf_json_gateway_child_init(apr_pool_t *p, server_rec *s) {
90
91         char* cfg = osrf_json_gateway_config_file;
92         char buf[32];
93         int t = time(NULL);
94         snprintf(buf, sizeof(buf), "%d", t);
95
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);
99                 return;
100         }
101
102         bootstrapped = 1;
103         allowedServices = osrfNewStringArray(8);
104         osrfLogInfo(OSRF_LOG_MARK, "Bootstrapping gateway child for requests");
105         osrfConfigGetValueList( NULL, allowedServices, "/services/service" );
106
107         int i;
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));
111         }
112 }
113
114 static int osrf_json_gateway_method_handler (request_rec *r) {
115
116         /* make sure we're needed first thing*/
117         if (strcmp(r->handler, MODULE_NAME )) return DECLINED;
118
119
120         osrf_json_gateway_dir_config* dir_conf =  
121                 ap_get_module_config(r->per_dir_config, &osrf_json_gateway_module);
122
123
124         /* provide 2 different JSON parsers and serializers to support legacy JSON */
125         jsonObject* (*parseJSONFunc) (const char*) = legacy_jsonParseString;
126         char* (*jsonToStringFunc) (const jsonObject*) = legacy_jsonObjectToJSON;
127
128         if(dir_conf->legacyJSON) {
129                 ap_log_rerror( APLOG_MARK, APLOG_INFO, 0, r, "Using legacy JSON");
130
131         } else {
132                 ap_log_rerror( APLOG_MARK, APLOG_INFO, 0, r, "Not using legacy JSON");
133                 parseJSONFunc = jsonParseString;
134                 jsonToStringFunc = jsonObjectToJSON;
135         }
136
137
138         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: entered request handler");
139
140         /* verify we are connected */
141         if( !bootstrapped || !osrfSystemGetTransportClient()) {
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 */
145                 exit(1);
146         }
147
148         osrfLogSetAppname("osrf_json_gw");
149
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' */
157         int   isXML             = 0;
158         int   api_level         = 1;
159
160         r->allowed |= (AP_METHOD_BIT << M_GET);
161         r->allowed |= (AP_METHOD_BIT << M_POST);
162
163         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: parsing URL params");
164         osrfStringArray* mparams        = NULL;
165         osrfStringArray* 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 */
173
174         if(format == NULL)
175                 format = strdup( "json" );
176         if(input_format == NULL)
177                 input_format = strdup( format );
178
179         /* set the user defined timeout value */
180         int timeout = 60;
181         char* tout = apacheGetFirstParamValue( params, "timeout" ); /* request timeout in seconds */
182         if( tout ) {
183                 timeout = atoi(tout);
184                 osrfLogDebug(OSRF_LOG_MARK, "Client supplied timeout of %d", timeout);
185                 free( tout );
186         }
187
188         if (a_l) {
189                 api_level = atoi(a_l);
190                 free( a_l );
191         }
192
193         if (!strcasecmp(format, "xml")) {
194                 isXML = 1;
195                 ap_set_content_type(r, "application/xml");
196         } else {
197                 ap_set_content_type(r, "text/plain");
198         }
199
200         free( format );
201         int ret = OK;
202
203         /* ----------------------------------------------------------------- */
204         /* Grab the requested locale using the Accept-Language header*/
205
206
207         if ( !param_locale ) {
208                 if ( apr_table_get(r->headers_in, "X-OpenSRF-Language") ) {
209                         param_locale = strdup( apr_table_get(r->headers_in, "X-OpenSRF-Language") );
210                 } else if ( apr_table_get(r->headers_in, "Accept-Language") ) {
211                         param_locale = strdup( apr_table_get(r->headers_in, "Accept-Language") );
212                 }
213         }
214
215
216         if (param_locale) {
217                 growing_buffer* osrf_locale_buf = buffer_init(16);      
218                 if (index(param_locale, ',')) {
219                         int ind = index(param_locale, ',') - param_locale;
220                         int i;
221                         for ( i = 0; i < ind && i < 128; i++ )
222                                 buffer_add_char( osrf_locale_buf, param_locale[i] );
223                 } else {
224                         buffer_add( osrf_locale_buf, param_locale );
225                 }
226
227                 free(param_locale);
228                 osrf_locale = buffer_release( osrf_locale_buf );
229         } else {
230                 osrf_locale = strdup( osrf_json_default_locale );
231         }
232         /* ----------------------------------------------------------------- */
233
234
235         if(!(service && method) || 
236                 !osrfStringArrayContains(allowedServices, service)) {
237
238                 osrfLogError(OSRF_LOG_MARK, 
239                         "Service [%s] not found or not allowed", service);
240                 ret = HTTP_NOT_FOUND;
241
242         } else {
243
244                 /* This will log all heaers to the apache error log 
245                 const apr_array_header_t* arr = apr_table_elts(r->headers_in);
246                 const void* ptr;
247
248                 while( (ptr = apr_array_pop(arr)) ) {
249                         apr_table_entry_t* e = (apr_table_entry_t*) ptr;
250                         fprintf(stderr, "Table entry: %s : %s\n", e->key, e->val );
251                 }
252                 fflush(stderr);
253                 */
254
255                 osrfAppSession* session = osrfAppSessionClientInit(service);
256                 osrf_app_session_set_locale(session, osrf_locale);
257
258                 double starttime = get_timestamp_millis();
259                 int req_id = -1;
260
261                 if(!strcasecmp(input_format, "json")) {
262                         jsonObject * arr = jsonNewObject(NULL);
263
264                         char* str;
265                         int i = 0;
266
267                         while( (str = osrfStringArrayGetString(mparams, i++)) ) 
268                                 jsonObjectPush(arr, parseJSONFunc(str));
269
270                         req_id = osrfAppSessionMakeRequest( session, arr, method, api_level, NULL );
271                         jsonObjectFree(arr);
272                 } else {
273
274                         /**
275                         * If we receive XML method params, convert each param to a JSON object
276                         * and pass the array of JSON object params to the method */
277                         if(!strcasecmp(input_format, "xml")) {
278                                 jsonObject* jsonParams = jsonNewObject(NULL);
279
280                                 char* str;
281                                 int i = 0;
282                                 while( (str = osrfStringArrayGetString(mparams, i++)) ) {
283                                         jsonObjectPush(jsonParams, jsonXMLToJSONObject(str));
284                                 }
285
286                                 req_id = osrfAppSessionMakeRequest( session, jsonParams, method, api_level, NULL );
287                                 jsonObjectFree(jsonParams);
288                         }
289                 }
290
291
292                 if( req_id == -1 ) {
293                         osrfLogError(OSRF_LOG_MARK, "I am unable to communicate with opensrf..going away...");
294                         osrfAppSessionFree(session);
295                         /* we don't want to spawn an intense re-forking storm 
296                          * if there is no jabber server.. so give it some time before we die */
297                         usleep( 100000 ); /* 100 milliseconds */
298                         exit(1);
299                 }
300
301
302                 /* ----------------------------------------------------------------- */
303                 /* log all requests to the activity log */
304                 const char* authtoken = apr_table_get(r->headers_in, "X-OILS-Authtoken");
305                 if(!authtoken) authtoken = "";
306                 growing_buffer* act = buffer_init(128); 
307                 buffer_fadd(act, "[%s] [%s] %s %s", r->connection->remote_ip, authtoken, service, method );
308                 char* str; int i = 0;
309                 while( (str = osrfStringArrayGetString(mparams, i++)) ) {
310                         if( i == 1 ) {
311                                 OSRF_BUFFER_ADD(act, " ");
312                                 OSRF_BUFFER_ADD(act, str);
313                         } else {
314                                 OSRF_BUFFER_ADD(act, ", ");
315                                 OSRF_BUFFER_ADD(act, str);
316                         }
317                 }
318
319                 osrfLogActivity( OSRF_LOG_MARK, act->buf );
320                 buffer_free(act);
321                 /* ----------------------------------------------------------------- */
322
323
324                 osrfMessage* omsg = NULL;
325
326                 int statuscode = 200;
327
328                 /* kick off the object */
329                 if (isXML)
330                         ap_rputs("<response xmlns=\"http://opensrf.org/-/namespaces/gateway/v1\"><payload>", r);
331                 else
332                         ap_rputs("{\"payload\":[", r);
333
334                 int morethan1           = 0;
335                 char* statusname        = NULL;
336                 char* statustext        = NULL;
337                 char* output            = NULL;
338
339                 while((omsg = osrfAppSessionRequestRecv( session, req_id, timeout ))) {
340         
341                         statuscode = omsg->status_code;
342                         jsonObject* res;        
343
344                         if( ( res = osrfMessageGetResult(omsg)) ) {
345
346                                 if (isXML) {
347                                         output = jsonObjectToXML( res );
348                                 } else {
349                                         output = jsonToStringFunc( res );
350                                         if( morethan1 ) ap_rputs(",", r); /* comma between JSON array items */
351                                 }
352                                 ap_rputs(output, r);
353                                 free(output);
354                                 morethan1 = 1;
355                 
356                         } else {
357         
358                                 if( statuscode > 299 ) { /* the request returned a low level error */
359                                         statusname = omsg->status_name ? strdup(omsg->status_name) : strdup("Unknown Error");
360                                         statustext = omsg->status_text ? strdup(omsg->status_text) : strdup("No Error Message");
361                                         osrfLogError( OSRF_LOG_MARK,  "Gateway received error: %s", statustext );
362                                 }
363                         }
364         
365                         osrfMessageFree(omsg);
366                         if(statusname) break;
367                 }
368
369                 double duration = get_timestamp_millis() - starttime;
370                 osrfLogDebug(OSRF_LOG_MARK, "gateway request took %f seconds", duration);
371
372
373                 if (isXML)
374                         ap_rputs("</payload>", r);
375                 else
376                         ap_rputs("]",r); /* finish off the payload array */
377
378                 if(statusname) {
379
380                         /* add a debug field if the request died */
381                         ap_log_rerror( APLOG_MARK, APLOG_INFO, 0, r, 
382                                         "OpenSRF JSON Request returned error: %s -> %s", statusname, statustext );
383                         int l = strlen(statusname) + strlen(statustext) + 32;
384                         char buf[l];
385
386                         if (isXML)
387                                 snprintf( buf, sizeof(buf), "<debug>\"%s : %s\"</debug>", statusname, statustext );
388
389                         else {
390                                 char bb[l];
391                                 snprintf(bb, sizeof(bb),  "%s : %s", statusname, statustext);
392                                 jsonObject* tmp = jsonNewObject(bb);
393                                 char* j = jsonToStringFunc(tmp);
394                                 snprintf( buf, sizeof(buf), ",\"debug\": %s", j);
395                                 free(j);
396                                 jsonObjectFree(tmp);
397                         }
398
399                         ap_rputs(buf, r);
400
401                         free(statusname);
402                         free(statustext);
403                 }
404
405                 /* insert the status code */
406                 char buf[32];
407
408                 if (isXML)
409                         snprintf(buf, sizeof(buf), "<status>%d</status>", statuscode );
410                 else
411                         snprintf(buf, sizeof(buf), ",\"status\":%d", statuscode );
412
413                 ap_rputs( buf, r );
414
415                 if (isXML)
416                         ap_rputs("</response>", r);
417                 else
418                         ap_rputs( "}", r ); /* finish off the object */
419
420                 osrfAppSessionFree(session);
421         }
422
423         osrfLogInfo(OSRF_LOG_MARK, "Completed processing service=%s, method=%s", service, method);
424         osrfStringArrayFree(params);
425         osrfStringArrayFree(mparams);
426         free( osrf_locale );
427         free( input_format );
428         free( method );
429         free( service );
430
431         osrfLogDebug(OSRF_LOG_MARK, "Gateway served %d requests", ++numserved);
432         osrfLogClearXid();
433
434         return ret;
435 }
436
437
438
439 static void osrf_json_gateway_register_hooks (apr_pool_t *p) {
440         ap_hook_handler(osrf_json_gateway_method_handler, NULL, NULL, APR_HOOK_MIDDLE);
441         ap_hook_child_init(osrf_json_gateway_child_init,NULL,NULL,APR_HOOK_MIDDLE);
442 }
443
444
445 module AP_MODULE_DECLARE_DATA osrf_json_gateway_module = {
446         STANDARD20_MODULE_STUFF,
447         osrf_json_gateway_create_dir_config,
448         NULL,
449         osrf_json_gateway_create_config,
450         NULL,
451         osrf_json_gateway_cmds,
452         osrf_json_gateway_register_hooks,
453 };
454
455
456
457