]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/gateway/mod_ils_gateway.c
added the ability to bypass JSON parsing for adding request parameters.
[OpenSRF.git] / 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/generic_utils.h"
34 #include "opensrf/osrf_message.h"
35 #include "opensrf/osrf_app_session.h"
36 #include "opensrf/string_array.h"
37 #include "md5.h"
38
39 /*
40  * This function is registered as a handler for HTTP methods and will
41   * therefore be invoked for all GET requests (and others).  Regardless
42    * of the request type, this function simply sends a message to
43  * STDERR (which httpd redirects to logs/error_log).  A real module
44   * would do *alot* more at this point.
45    */
46 #define MODULE_NAME "ils_gateway_module"
47
48 struct session_list_struct {
49         //char* service;
50         osrf_app_session* session;
51         struct session_list_struct* next;
52         int serve_count;
53 };
54 typedef struct session_list_struct session_list;
55
56 /* the global session cache */
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 /* find a session in the list */
93 /* if(update) we add 1 to the serve_count */
94 static osrf_app_session* find_session( char* service, int update ) {
95
96         session_list* item = the_list;
97         while(item) {
98
99                 if(!strcmp(item->session->remote_service,service)) {
100                         if(update) { 
101                                 if( item->serve_count++ > 20 ) {
102                                         debug_handler("Disconnected session on 20 requests => %s", service);
103                                         osrf_app_session_disconnect(item->session);
104                                         del_session(service);
105                                         return NULL;
106                                         //item->serve_count = 0;
107                                 }
108                         }
109                         debug_handler("Found session for %s in gateway cache", service);
110                         return item->session;
111                 }
112
113                 item = item->next;
114         }
115         return NULL;
116 }
117
118 /* add a session to the list */
119 static void add_session( char* service, osrf_app_session* session ) {
120
121         if(!session) return;
122
123         if(find_session(service,0))
124                 return;
125
126         debug_handler("Add session for %s to the cache", service );
127
128         session_list* new_item = (session_list*) safe_malloc(sizeof(session_list));
129         new_item->session = session;
130         //new_item->service = service;
131         new_item->serve_count = 0;
132
133         if(the_list) {
134                 session_list* second = the_list->next;
135                 the_list = new_item;
136                 new_item->next = second;
137         } else {
138                 the_list = new_item;
139         }
140 }
141
142 static void mod_ils_gateway_child_init(apr_pool_t *p, server_rec *s) {
143         if( ! osrf_system_bootstrap_client( 
144                 "/pines/cvs/ILS/OpenSRF/src/gateway/gateway.xml") ) { /* config option */
145         }
146
147         /* we don't want to waste time parsing json that we're not going to look at*/
148         osrf_message_set_json_parse_result(0);
149         osrf_message_set_json_parse_params(0);
150         fprintf(stderr, "Bootstrapping %d\n", getpid() );
151         fflush(stderr);
152 }
153
154 static int mod_ils_gateway_method_handler (request_rec *r) {
155
156
157         /* make sure we're needed first thing*/
158         if (strcmp(r->handler, MODULE_NAME )) 
159                 return DECLINED;
160
161
162         apr_pool_t *p = r->pool;        /* memory pool */
163         char* arg = r->args;                    /* url query string */
164
165         char* service                                   = NULL; /* service to connect to */
166         char* method                                    = NULL; /* method to perform */
167
168         json* 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[1024];
200                 memset(body,0,1024);
201                 buffer = buffer_init(1024);
202
203                 while(ap_get_client_block(r, body, 1024)) {
204                         buffer_add( buffer, body );
205                         memset(body,0,1024);
206                 }
207
208                 if(arg && arg[0]) {
209                         tmp_buf = buffer_init(1024);
210                         buffer_add(tmp_buf,arg);
211                         buffer_add(tmp_buf,buffer->buf);
212                         arg = (char*) apr_pstrdup(p, tmp_buf->buf);
213                         buffer_free(tmp_buf);
214                 } else {
215                         arg = (char*) apr_pstrdup(p, buffer->buf);
216                 }
217                 buffer_free(buffer);
218
219         } 
220
221
222         if( ! arg || !arg[0] ) { /* we received no request */
223                 warning_handler("No Args");
224                 return OK;
225         }
226
227         r->allowed |= (AP_METHOD_BIT << M_GET);
228         r->allowed |= (AP_METHOD_BIT << M_POST);
229
230         
231         char* argcopy = (char*) apr_pstrdup(p, arg);
232
233         while( argcopy && (val = ap_getword(p, &argcopy, '&'))) {
234
235                 key = ap_getword(r->pool,&val, '=');
236                 if(!key || !key[0])
237                         break;
238
239                 ap_unescape_url((char*)key);
240                 ap_unescape_url((char*)val);
241
242                 if(!strcmp(key,"service")) 
243                         service = val;
244
245                 if(!strcmp(key,"method"))
246                         method = val;
247
248                 if(!strcmp(key,"__param"))
249                         string_array_add(sarray, val);
250
251         }
252
253         info_handler("Performing(%d):  service %s | method %s | \n",
254                         getpid(), service, method );
255
256         int k;
257         for( k = 0; k!= sarray->size; k++ ) {
258                 info_handler( "param %s", string_array_get_string(sarray,k));
259         }
260
261         osrf_app_session* session = find_session(service,1);
262
263         if(!session) {
264                 debug_handler("building new session for %s", service );
265                 session = osrf_app_client_session_init(service);
266                 add_session(service, session);
267         }
268
269         debug_handler("MOD session service: %s", session->remote_service );
270
271
272         /* connect to the remote service */
273         if(!osrf_app_session_connect(session)) {
274                 exception = json_object_new_object();
275                 json_object_object_add( exception, "is_err", json_object_new_int(1));
276                 json_object_object_add( exception, 
277                                 "err_msg", json_object_new_string("Unable to connect to remote service"));
278
279                 ap_rputs(json_object_to_json_string(exception), r );
280                 json_object_put(exception);
281                 return OK;
282         }
283
284         int req_id = osrf_app_session_make_request( session, NULL, method, 1, sarray );
285         string_array_destroy(sarray);
286
287         osrf_message* omsg = NULL;
288
289         growing_buffer* result_data = buffer_init(256);
290         buffer_add(result_data, "[");
291
292         /* gather result data */
293         while((omsg = osrf_app_session_request_recv( session, req_id, 30 ))) {
294
295                 if( omsg->result_string ) {
296                         buffer_add(result_data, omsg->result_string);
297                         buffer_add( result_data, ",");
298
299                 } else {
300
301
302                         /* build the exception information */
303                         growing_buffer* exc_buffer = buffer_init(256);
304                         buffer_add( exc_buffer, "\nReceived Exception:\nName: " );
305                         buffer_add( exc_buffer, omsg->status_name );
306                         buffer_add( exc_buffer, "\nStatus: " );
307                         buffer_add( exc_buffer, omsg->status_text );
308                         buffer_add( exc_buffer, "\nStatus: " );
309                         char code[16];
310                         memset(code, 0, 16);
311                         sprintf( code, "%d", omsg->status_code );
312                         buffer_add( exc_buffer, code );
313
314                         /* build the exception object */
315                         exception = json_object_new_object();
316                         json_object_object_add( exception, "is_err", json_object_new_int(1));
317                         json_object_object_add( exception, 
318                                         "err_msg", json_object_new_string(exc_buffer->buf));
319
320                         warning_handler("*** Looks like we got a "
321                                         "server exception\n%s", exc_buffer->buf );
322
323                         buffer_free(exc_buffer);
324                         osrf_message_free(omsg);
325                         break;
326                 }
327
328                 osrf_message_free(omsg);
329                 omsg = NULL;
330         }
331
332         /* remove trailing comma */
333         if( result_data->buf[strlen(result_data->buf)-1] == ',') {
334                 result_data->buf[strlen(result_data->buf)-1] = '\0';
335                 result_data->n_used--;
336         }
337
338         buffer_add(result_data,"]");
339
340         char* content = NULL;
341
342         /* round up our data */
343         if(exception) {
344                 content = strdup(json_object_to_json_string(exception));
345                 json_object_put(exception);
346         } else 
347                 content = buffer_data(result_data); 
348         
349
350         buffer_free(result_data);
351
352         if(content) {
353                 ap_rputs(content,r);
354                 free(content);
355         } 
356
357         osrf_app_session_request_finish( session, req_id );
358
359         return OK;
360
361 }
362
363 /*
364  * This function is a callback and it declares what other functions
365   * should be called for request processing and configuration requests.
366    * This callback function declares the Handlers for other events.  */
367 static void mod_ils_gateway_register_hooks (apr_pool_t *p) {
368 // I think this is the call to make to register a handler for method calls (GET PUT et. al.).
369 // We will ask to be last so that the comment has a higher tendency to
370 // go at the end.
371         ap_hook_handler(mod_ils_gateway_method_handler, NULL, NULL, APR_HOOK_MIDDLE);
372         ap_hook_child_init(mod_ils_gateway_child_init,NULL,NULL,APR_HOOK_MIDDLE);
373 }
374
375 /*
376  * Declare and populate the module's data structure.  The
377   * name of this structure ('tut1_module') is important - it
378    * must match the name of the module.  This structure is the
379  * only "glue" between the httpd core and the module.
380   */
381
382 module AP_MODULE_DECLARE_DATA ils_gateway_module =
383 {
384 STANDARD20_MODULE_STUFF,
385 NULL,
386 NULL,
387 NULL,
388 NULL,
389 NULL,
390 mod_ils_gateway_register_hooks,
391 };
392