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