]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/gateway/osrf_json_gateway.c
sending authtoken in request header and logging to activity log
[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 "objson/object.h"
6 #include "objson/json2xml.h"
7 #include <sys/time.h>
8 #include <sys/resource.h>
9
10
11 #define MODULE_NAME "osrf_json_gateway_module"
12 #define GATEWAY_CONFIG "OSRFGatewayConfig"
13 #define CONFIG_CONTEXT "gateway"
14
15 #define GATEWAY_DEFAULT_CONFIG "/openils/conf/opensrf_core.xml"
16
17
18 /* our config structure */
19 typedef struct { 
20         char* configfile;  /* our bootstrap config file */
21 } osrf_json_gateway_config;
22
23 module AP_MODULE_DECLARE_DATA osrf_json_gateway_module;
24
25 char* osrf_json_gateway_config_file = NULL;
26 int bootstrapped = 0;
27 int numserved = 0;
28 osrfStringArray* allowedServices = NULL;
29
30 static const char* osrf_json_gateway_set_config(cmd_parms *parms, void *config, const char *arg) {
31         osrf_json_gateway_config  *cfg;
32         cfg = ap_get_module_config(parms->server->module_config, &osrf_json_gateway_module);
33         cfg->configfile = (char*) arg;
34         osrf_json_gateway_config_file = (char*) arg;
35         return NULL;
36 }
37
38 /* tell apache about our commands */
39 static const command_rec osrf_json_gateway_cmds[] = {
40         AP_INIT_TAKE1( GATEWAY_CONFIG, osrf_json_gateway_set_config, 
41                         NULL, RSRC_CONF, "osrf json gateway config file"),
42         {NULL}
43 };
44
45 /* build the config object */
46 static void* osrf_json_gateway_create_config( apr_pool_t* p, server_rec* s) {
47         osrf_json_gateway_config* cfg = (osrf_json_gateway_config*) 
48                         apr_palloc(p, sizeof(osrf_json_gateway_config));
49         cfg->configfile = GATEWAY_DEFAULT_CONFIG;
50         return (void*) cfg;
51 }
52
53
54 static void osrf_json_gateway_child_init(apr_pool_t *p, server_rec *s) {
55
56         char* cfg = osrf_json_gateway_config_file;
57         char buf[32];
58         memset(buf, 0x0, 32);
59         int t = time(NULL);
60         snprintf(buf, 32, "%d", t);
61
62         if( ! osrfSystemBootstrapClientResc( cfg, CONFIG_CONTEXT, buf ) ) {
63                 ap_log_error( APLOG_MARK, APLOG_ERR, 0, s, 
64                         "Unable to Bootstrap OpenSRF Client with config %s..", cfg);
65                 return;
66         }
67
68         bootstrapped = 1;
69         allowedServices = osrfNewStringArray(8);
70         osrfLogInfo(OSRF_LOG_MARK, "Bootstrapping gateway child for requests");
71         osrfConfigGetValueList( NULL, allowedServices, "/services/service" );
72
73         int i;
74         for( i = 0; i < allowedServices->size; i++ ) {
75                 ap_log_error( APLOG_MARK, APLOG_DEBUG, 0, s, 
76                         "allowed service: %s\n", osrfStringArrayGetString(allowedServices, i));
77         }
78 }
79
80 static int osrf_json_gateway_method_handler (request_rec *r) {
81
82         /* make sure we're needed first thing*/
83         if (strcmp(r->handler, MODULE_NAME )) return DECLINED;
84
85         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: entered request handler");
86
87         /* verify we are connected */
88         if( !bootstrapped || !osrf_system_get_transport_client()) {
89                 ap_log_rerror( APLOG_MARK, APLOG_ERR, 0, r, "Cannot process request "
90                                 "because the OpenSRF JSON gateway has not been bootstrapped...");
91                 return HTTP_INTERNAL_SERVER_ERROR;
92         }
93
94         osrfLogSetAppname("osrf_json_gw");
95
96         char* service           = NULL; /* service to connect to */
97         char* method            = NULL; /* method to perform */
98         char* format            = NULL; /* method to perform */
99         char* a_l                       = NULL; /* request api level */
100         int   isXML                     = 0;
101         int   api_level = 1;
102
103         r->allowed |= (AP_METHOD_BIT << M_GET);
104         r->allowed |= (AP_METHOD_BIT << M_POST);
105
106         osrfLogDebug(OSRF_LOG_MARK, "osrf gateway: parsing URL params");
107         string_array* mparams   = NULL;
108         string_array* params            = apacheParseParms(r); /* free me */
109         service         = apacheGetFirstParamValue( params, "service" );
110         method          = apacheGetFirstParamValue( params, "method" ); 
111         format          = apacheGetFirstParamValue( params, "format" ); 
112         a_l                     = apacheGetFirstParamValue( params, "api_level" ); 
113         mparams         = apacheGetParamValues( params, "param" ); /* free me */
114
115         if (a_l)
116                 api_level = atoi(a_l);
117
118         if (format && !strcasecmp(format, "xml" )) {
119                 isXML = 1;
120                 ap_set_content_type(r, "application/xml");
121         } else {
122                 ap_set_content_type(r, "text/plain");
123         }
124
125         int ret = OK;
126
127         if(!(service && method) || 
128                 !osrfStringArrayContains(allowedServices, service)) {
129
130                 osrfLogError(OSRF_LOG_MARK, 
131                         "Service [%s] not found or not allowed", service);
132                 ret = HTTP_NOT_FOUND;
133
134         } else {
135
136                 /* This will log all heaers to the apache error log 
137                 const apr_array_header_t* arr = apr_table_elts(r->headers_in);
138                 const void* ptr;
139
140                 while( (ptr = apr_array_pop(arr)) ) {
141                         apr_table_entry_t* e = (apr_table_entry_t*) ptr;
142                         fprintf(stderr, "Table entry: %s : %s\n", e->key, e->val );
143                 }
144                 fflush(stderr);
145                 */
146
147
148                 /* ----------------------------------------------------------------- */
149                 /* log all requests to the activity log */
150                 const char* authtoken = apr_table_get(r->headers_in, "X-OILS-Authtoken");
151                 if(!authtoken) authtoken = "";
152                 growing_buffer* act = buffer_init(128); 
153                 buffer_fadd(act, "[%s] [%s] %s %s", r->connection->remote_ip, authtoken, service, method );
154                 char* str; int i = 0;
155                 while( (str = osrfStringArrayGetString(mparams, i++)) ) 
156                         if( i == 1 ) buffer_fadd(act, " %s", str);
157                         else buffer_fadd(act, ", %s", str);
158
159                 osrfLogActivity( OSRF_LOG_MARK, act->buf );
160                 buffer_free(act);
161                 /* ----------------------------------------------------------------- */
162
163                 osrfAppSession* session = osrf_app_client_session_init(service);
164
165                 double starttime = get_timestamp_millis();
166                 int req_id = osrf_app_session_make_req( session, NULL, method, api_level, mparams );
167                 osrf_message* omsg = NULL;
168
169                 int statuscode = 200;
170
171                 /* kick off the object */
172                 if (isXML)
173                         ap_rputs("<response xmlns=\"http://opensrf.org/-/namespaces/gateway/v1\"><payload>", r);
174                 else
175                         ap_rputs("{\"payload\":[", r);
176
177                 int morethan1           = 0;
178                 char* statusname        = NULL;
179                 char* statustext        = NULL;
180                 char* output            = NULL;
181
182                 while((omsg = osrfAppSessionRequestRecv( session, req_id, 60 ))) {
183         
184                         statuscode = omsg->status_code;
185                         jsonObject* res;        
186
187                         if( ( res = osrfMessageGetResult(omsg)) ) {
188
189                                 if (isXML) {
190                                         output = jsonObjectToXML( res );
191                                 } else {
192                                         output = jsonObjectToJSON( res );
193                                         if( morethan1 ) ap_rputs(",", r); /* comma between JSON array items */
194                                 }
195                                 ap_rputs(output, r);
196                                 free(output);
197                                 morethan1 = 1;
198                 
199                         } else {
200         
201                                 if( statuscode > 299 ) { /* the request returned a low level error */
202                                         statusname = omsg->status_name ? strdup(omsg->status_name) : strdup("Unknown Error");
203                                         statustext = omsg->status_text ? strdup(omsg->status_text) : strdup("No Error Message");
204                                         osrfLogError( OSRF_LOG_MARK,  "Gateway received error: %s", statustext );
205                                 }
206                         }
207         
208                         osrf_message_free(omsg);
209                         if(statusname) break;
210                 }
211
212                 double duration = get_timestamp_millis() - starttime;
213                 osrfLogDebug(OSRF_LOG_MARK, "gateway request took %lf seconds", duration);
214
215
216                 if (isXML)
217                         ap_rputs("</payload>", r);
218                 else
219                         ap_rputs("]",r); /* finish off the payload array */
220
221                 if(statusname) {
222
223                         /* add a debug field if the request died */
224                         ap_log_rerror( APLOG_MARK, APLOG_INFO, 0, r, 
225                                         "OpenSRF JSON Request returned error: %s -> %s", statusname, statustext );
226                         int l = strlen(statusname) + strlen(statustext) + 32;
227                         char buf[l];
228                         bzero(buf,l);
229
230                         if (isXML)
231                                 snprintf( buf, l, "<debug>\"%s : %s\"</debug>", statusname, statustext );
232
233                         else {
234                                 char bb[l];
235                                 bzero(bb, l);
236                                 snprintf(bb, l,  "%s : %s", statusname, statustext);
237                                 jsonObject* tmp = jsonNewObject(bb);
238                                 char* j = jsonObjectToJSON(tmp);
239                                 snprintf( buf, l, ",\"debug\": %s", j);
240                                 free(j);
241                                 jsonObjectFree(tmp);
242                         }
243
244                         ap_rputs(buf, r);
245
246                         free(statusname);
247                         free(statustext);
248                 }
249
250                 /* insert the status code */
251                 char buf[32];
252                 bzero(buf,32);
253
254                 if (isXML)
255                         snprintf(buf, 32, "<status>%d</status>", statuscode );
256                 else
257                         snprintf(buf, 32, ",\"status\":%d", statuscode );
258
259                 ap_rputs( buf, r );
260
261                 if (isXML)
262                         ap_rputs("</response>", r);
263                 else
264                         ap_rputs( "}", r ); /* finish off the object */
265
266                 osrf_app_session_destroy(session);
267         }
268
269         osrfLogInfo(OSRF_LOG_MARK, "Completed processing service=%s, method=%s", service, method);
270         string_array_destroy(params);
271         string_array_destroy(mparams);
272
273         osrfLogDebug(OSRF_LOG_MARK, "Gateway served %d requests", ++numserved);
274
275         return ret;
276 }
277
278
279
280 static void osrf_json_gateway_register_hooks (apr_pool_t *p) {
281         ap_hook_handler(osrf_json_gateway_method_handler, NULL, NULL, APR_HOOK_MIDDLE);
282         ap_hook_child_init(osrf_json_gateway_child_init,NULL,NULL,APR_HOOK_MIDDLE);
283 }
284
285
286 module AP_MODULE_DECLARE_DATA osrf_json_gateway_module = {
287         STANDARD20_MODULE_STUFF,
288         NULL,
289         NULL,
290         osrf_json_gateway_create_config,
291         NULL,
292         osrf_json_gateway_cmds,
293         osrf_json_gateway_register_hooks,
294 };
295
296
297
298