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