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