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