]> git.evergreen-ils.org Git - working/Evergreen.git/blob - OpenSRF/src/gateway/mod_ils_gateway.c
changes to support the REST gateway
[working/Evergreen.git] / OpenSRF / src / gateway / mod_ils_gateway.c
1 /*
2 Copyright 2002 Kevin O'Donnell
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17 */
18
19 /*
20  * Include the core server components.
21   */
22 #include "httpd.h"
23 #include "http_config.h"
24 #include "http_core.h"
25 #include "http_protocol.h"
26 #include "apr_compat.h"
27 #include "apr_strings.h"
28
29
30
31 /* our stuff */
32 #include "opensrf/transport_client.h"
33 #include "opensrf/osrf_message.h"
34 #include "opensrf/osrf_app_session.h"
35 #include "opensrf/string_array.h"
36 #include "md5.h"
37 #include "objson/object.h"
38 #include "objson/json_parser.h"
39
40 #ifdef RESTGATEWAY
41 #include "rest_xml.h"
42 #endif
43
44 /*
45  * This function is registered as a handler for HTTP methods and will
46   * therefore be invoked for all GET requests (and others).  Regardless
47    * of the request type, this function simply sends a message to
48  * STDERR (which httpd redirects to logs/error_log).  A real module
49   * would do *alot* more at this point.
50    */
51 #define MODULE_NAME "ils_gateway_module"
52
53 /*
54 struct session_list_struct {
55         osrf_app_session* session;
56         struct session_list_struct* next;
57         int serve_count;
58 };
59 typedef struct session_list_struct session_list;
60
61 static session_list* the_list = NULL;
62
63 static void del_session( char* service ) {
64         if(!service || ! the_list)
65                 return;
66         
67         debug_handler("In del_sesion for %s", service );
68         session_list* prev = the_list;
69         session_list* item = prev->next;
70
71         if(!strcmp(prev->session->remote_service, service)) {
72                 info_handler("Removing gateway session for %s", service );
73                 the_list = item;
74                 osrf_app_session_destroy(prev->session);
75                 free(prev);
76                 return;
77         }
78
79         while(item) {
80                 if( !strcmp(item->session->remote_service, service)) {
81                         info_handler("Removing gateway session for %s", service );
82                         prev->next = item->next;
83                         osrf_app_session_destroy(item->session);
84                         free(item);
85                         return;
86                 }
87                 prev = item;
88                 item = item->next;
89         }
90
91         warning_handler("Attempt to remove gateway session "
92                         "that does not exist: %s", service );
93
94 }
95
96 // if(update) we add 1 to the serve_count 
97 static osrf_app_session* find_session( char* service, int update ) {
98
99         session_list* item = the_list;
100         while(item) {
101
102                 if(!strcmp(item->session->remote_service,service)) {
103                         if(update) { 
104                                 if( item->serve_count++ > 20 ) {
105                                         debug_handler("Disconnected session on 20 requests => %s", service);
106                                         osrf_app_session_disconnect(item->session);
107                                         del_session(service);
108                                         return NULL;
109                                         //item->serve_count = 0;
110                                 }
111                         }
112                         debug_handler("Found session for %s in gateway cache", service);
113                         return item->session;
114                 }
115
116                 item = item->next;
117         }
118         return NULL;
119 }
120
121 static void add_session( char* service, osrf_app_session* session ) {
122
123         if(!session) return;
124
125         if(find_session(service,0))
126                 return;
127
128         debug_handler("Add session for %s to the cache", service );
129
130         session_list* new_item = (session_list*) safe_malloc(sizeof(session_list));
131         new_item->session = session;
132         //new_item->service = service;
133         new_item->serve_count = 0;
134
135         if(the_list) {
136                 session_list* second = the_list->next;
137                 the_list = new_item;
138                 new_item->next = second;
139         } else {
140                 the_list = new_item;
141         }
142 }
143 */
144
145 static void mod_ils_gateway_child_init(apr_pool_t *p, server_rec *s) {
146         if( ! osrf_system_bootstrap_client( "/openils/conf/gateway.xml") ) { 
147                 fatal_handler("Unable to load gateway config file...");
148         }
149
150         /* we don't want to waste time parsing json that we're not going to look at*/
151         osrf_message_set_json_parse_result(0);
152         osrf_message_set_json_parse_params(0);
153         fprintf(stderr, "Bootstrapping %d\n", getpid() );
154         fflush(stderr);
155 }
156
157 static int mod_ils_gateway_method_handler (request_rec *r) {
158
159
160         /* make sure we're needed first thing*/
161         if (strcmp(r->handler, MODULE_NAME )) 
162                 return DECLINED;
163
164
165         apr_pool_t *p = r->pool;        /* memory pool */
166         char* arg = r->args;                    /* url query string */
167
168         char* service                                   = NULL; /* service to connect to */
169         char* method                                    = NULL; /* method to perform */
170
171         //json* exception                               = NULL; /* returned in error conditions */
172         object* exception                               = NULL; /* returned in error conditions */
173         string_array* sarray                    = init_string_array(12); /* method parameters */
174
175         growing_buffer* buffer          = NULL; /* POST data */
176         growing_buffer* tmp_buf         = NULL; /* temp buffer */
177
178         char* key                                               = NULL; /* query item name */
179         char* val                                               = NULL; /* query item value */
180
181
182
183         /* verify we are connected */
184         if(!osrf_system_get_transport_client()) {
185                 fatal_handler("Bootstrap Failed, no transport client");
186                 return HTTP_INTERNAL_SERVER_ERROR;
187         }
188
189         /* set content type to text/plain for passing around JSON objects */
190         ap_set_content_type(r, "text/plain");
191
192
193
194         /* gather the post args and append them to the url query string */
195         if( !strcmp(r->method,"POST") ) {
196
197                 ap_setup_client_block(r,REQUEST_CHUNKED_DECHUNK);
198
199                 if(! ap_should_client_block(r)) {
200                         warning_handler("No Post Body");
201                 }
202
203                 char body[1025];
204                 memset(body,0,1025);
205                 buffer = buffer_init(1025);
206
207                 while(ap_get_client_block(r, body, 1024)) {
208                         debug_handler("Apache read POST block data: %s\n", body);
209                         buffer_add( buffer, body );
210                         memset(body,0,1025);
211                 }
212
213                 if(arg && arg[0]) {
214                         tmp_buf = buffer_init(1024);
215                         buffer_add(tmp_buf,arg);
216                         buffer_add(tmp_buf,buffer->buf);
217                         arg = (char*) apr_pstrdup(p, tmp_buf->buf);
218                         buffer_free(tmp_buf);
219                 } else {
220                         arg = (char*) apr_pstrdup(p, buffer->buf);
221                 }
222                 buffer_free(buffer);
223
224         } 
225
226         debug_handler("params args are %s", arg);
227
228
229         if( ! arg || !arg[0] ) { /* we received no request */
230                 warning_handler("No Args");
231                 return OK;
232         }
233
234         r->allowed |= (AP_METHOD_BIT << M_GET);
235         r->allowed |= (AP_METHOD_BIT << M_POST);
236
237         
238         //char* argcopy = (char*) apr_pstrdup(p, arg);
239
240         //while( argcopy && (val = ap_getword(p, (const char**) &argcopy, '&'))) {
241         while( arg && (val = ap_getword(p, (const char**) &arg, '&'))) {
242
243                 //const char* val2 = val;
244
245                 key = ap_getword(r->pool, (const char**) &val, '=');
246                 if(!key || !key[0])
247                         break;
248
249                 ap_unescape_url((char*)key);
250                 ap_unescape_url((char*)val);
251
252                 if(!strcmp(key,"service")) 
253                         service = val;
254
255                 if(!strcmp(key,"method"))
256                         method = val;
257
258                 if(!strcmp(key,"param"))
259                         string_array_add(sarray, val);
260
261         }
262
263         info_handler("Performing(%d):  service %s | method %s | \n",
264                         getpid(), service, method );
265
266         int k;
267         for( k = 0; k!= sarray->size; k++ ) {
268                 info_handler( "param %s", string_array_get_string(sarray,k));
269         }
270
271         /*
272         osrf_app_session* session = find_session(service,1);
273
274         if(!session) {
275                 debug_handler("building new session for %s", service );
276                 session = osrf_app_client_session_init(service);
277                 add_session(service, session);
278         }
279         */
280
281         osrf_app_session* session = osrf_app_client_session_init(service);
282
283         debug_handler("MOD session service: %s", session->remote_service );
284
285
286         /* connect to the remote service */
287         /*
288         if(!osrf_app_session_connect(session)) {
289                 exception = json_object_new_object();
290                 json_object_object_add( exception, "is_err", json_object_new_int(1));
291                 json_object_object_add( exception, 
292                                 "err_msg", json_object_new_string("Unable to connect to remote service"));
293
294                 ap_rputs(json_object_to_json_string(exception), r );
295                 json_object_put(exception);
296                 return OK;
297         }
298         */
299
300         int req_id = osrf_app_session_make_req( session, NULL, method, 1, sarray );
301         string_array_destroy(sarray);
302
303         osrf_message* omsg = NULL;
304
305         growing_buffer* result_data = buffer_init(256);
306         buffer_add(result_data, "[");
307
308         /* gather result data */
309         while((omsg = osrf_app_session_request_recv( session, req_id, 60 ))) {
310
311                 if( omsg->result_string ) {
312                         buffer_add(result_data, omsg->result_string);
313                         buffer_add( result_data, ",");
314
315                 } else {
316
317
318                         /* build the exception information */
319                         growing_buffer* exc_buffer = buffer_init(256);
320                         buffer_add( exc_buffer, "\nReceived Exception:\nName: " );
321                         buffer_add( exc_buffer, omsg->status_name );
322                         buffer_add( exc_buffer, "\nStatus: " );
323                         buffer_add( exc_buffer, omsg->status_text );
324                         buffer_add( exc_buffer, "\nStatus: " );
325
326                         char code[16];
327                         memset(code, 0, 16);
328                         sprintf( code, "%d", omsg->status_code );
329                         buffer_add( exc_buffer, code );
330
331                         /* build the exception object */
332                         /*
333                         exception = json_object_new_object();
334                         json_object_object_add( exception, "is_err", json_object_new_int(1));
335                         json_object_object_add( exception, 
336                                         "err_msg", json_object_new_string(exc_buffer->buf));
337                                         */
338
339                         exception = json_parse_string("{}");
340                         exception->add_key(exception, "is_err", json_parse_string("1"));
341                         exception->add_key(exception, "err_msg", new_object(exc_buffer->buf) );
342
343                         warning_handler("*** Looks like we got a "
344                                         "server exception\n%s", exc_buffer->buf );
345
346                         buffer_free(exc_buffer);
347                         osrf_message_free(omsg);
348                         break;
349                 }
350
351                 osrf_message_free(omsg);
352                 omsg = NULL;
353         }
354
355         /* remove trailing comma */
356         if( result_data->buf[strlen(result_data->buf)-1] == ',') {
357                 result_data->buf[strlen(result_data->buf)-1] = '\0';
358                 result_data->n_used--;
359         }
360
361         buffer_add(result_data,"]");
362
363         char* content = NULL;
364
365         /* round up our data */
366         if(exception) {
367                 //content = strdup(json_object_to_json_string(exception));
368                 //json_object_put(exception);
369                 content = strdup(exception->to_json(exception));
370                 free_object(exception);
371         } else {
372 #ifdef RESTGATEWAY
373                 content = json_string_to_xml( buffer_data(result_data) );
374 #else
375                 content = buffer_data(result_data); 
376 #endif
377         }
378         
379
380         buffer_free(result_data);
381
382         if(content) {
383                 debug_handler( "APACHE writing data to web client: %s", content );
384                 ap_rputs(content,r);
385                 free(content);
386         } 
387
388         osrf_app_session_request_finish( session, req_id );
389         debug_handler("gateway process message successfully");
390
391
392         osrf_app_session_destroy(session);
393         return OK;
394
395 }
396
397 /*
398  * This function is a callback and it declares what other functions
399   * should be called for request processing and configuration requests.
400    * This callback function declares the Handlers for other events.  */
401 static void mod_ils_gateway_register_hooks (apr_pool_t *p) {
402 // I think this is the call to make to register a handler for method calls (GET PUT et. al.).
403 // We will ask to be last so that the comment has a higher tendency to
404 // go at the end.
405         ap_hook_handler(mod_ils_gateway_method_handler, NULL, NULL, APR_HOOK_MIDDLE);
406         ap_hook_child_init(mod_ils_gateway_child_init,NULL,NULL,APR_HOOK_MIDDLE);
407 }
408
409 /*
410  * Declare and populate the module's data structure.  The
411   * name of this structure ('tut1_module') is important - it
412    * must match the name of the module.  This structure is the
413  * only "glue" between the httpd core and the module.
414   */
415
416 module AP_MODULE_DECLARE_DATA ils_gateway_module =
417 {
418 STANDARD20_MODULE_STUFF,
419 NULL,
420 NULL,
421 NULL,
422 NULL,
423 NULL,
424 mod_ils_gateway_register_hooks,
425 };
426