]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/libopensrf/osrf_application.c
LP#1666706: add --with-websockets-port configure option
[OpenSRF.git] / src / libopensrf / osrf_application.c
1 #include <opensrf/osrf_application.h>
2
3 /**
4         @file osrf_application.c
5         @brief Load and manage shared object libraries.
6
7         Maintain a registry of applications, using an osrfHash keyed on application name,
8
9         For each application, load a shared object library so that we can call
10         application-specific functions dynamically.  In order to map method names to the
11         corresponding functions (i.e. symbol names in the library), maintain a registry of
12         methods, using an osrfHash keyed on method name.
13 */
14
15 // The following macro is commented out because it ia no longer used.
16
17 // Used internally to make sure the method description provided is OK
18 /*
19 #define OSRF_METHOD_VERIFY_DESCRIPTION(app, d) \
20         if(!app) return -1; \
21         if(!d) return -1;\
22         if(!d->name) { \
23                 osrfLogError( OSRF_LOG_MARK,  "No method name provided in description" ), \
24                 return -1; \
25 } \
26         if(!d->symbol) { \
27                 osrfLogError( OSRF_LOG_MARK, "No method symbol provided in description" ), \
28                 return -1; \
29 } \
30         if(!d->notes) \
31                 d->notes = ""; \
32         if(!d->paramNotes) \
33                 d->paramNotes = "";\
34         if(!d->returnNotes) \
35                 d->returnNotes = "";
36 */
37
38 /**
39         @name Well known method names
40         @brief These methods are automatically implemented for every application.
41 */
42 /*@{*/
43 #define OSRF_SYSMETHOD_INTROSPECT               "opensrf.system.method"
44 #define OSRF_SYSMETHOD_INTROSPECT_ATOMIC        "opensrf.system.method.atomic"
45 #define OSRF_SYSMETHOD_INTROSPECT_ALL           "opensrf.system.method.all"
46 #define OSRF_SYSMETHOD_INTROSPECT_ALL_ATOMIC    "opensrf.system.method.all.atomic"
47 #define OSRF_SYSMETHOD_ECHO                     "opensrf.system.echo"
48 #define OSRF_SYSMETHOD_ECHO_ATOMIC              "opensrf.system.echo.atomic"
49 /*@}*/
50
51 /**
52         @name Method options
53         @brief Macros that get OR'd together to form method options.
54
55         These options are in addition to the ones stipulated by the caller of
56         osrfRegisterMethod(), and are not externally visible.
57 */
58 /*@{*/
59 /**
60         @brief  Marks a method as a system method.
61
62         System methods are implemented by generic functions, called via static linkage.  They
63         are not loaded or executed from shared objects.
64 */
65 #define OSRF_METHOD_SYSTEM          1
66 /**
67         @brief  Combines all responses into a single RESULT message.
68
69         For a @em non-atomic method, the server returns each response to the client in a
70         separate RESULT message.  It sends a STATUS message at the end to signify the end of the
71         message stream.
72
73         For an @em atomic method, the server buffers all responses until the method returns,
74         and then sends them all at once in a single RESULT message (followed by a STATUS message).
75         Each individual response is encoded as an entry in a JSON array.  This buffering is
76         transparent to the function that implements the method.
77
78         Atomic methods incur less networking overhead than non-atomic methods, at the risk of
79         creating excessively large RESULT messages.  The HTTP gateway requires the atomic versions
80         of streaming methods because of the stateless nature of the HTTP protocol.
81
82         If OSRF_METHOD_STREAMING is set for a method, the application generates both an atomic
83         and a non-atomic method, whose names are identical except that the atomic one carries a
84         suffix of ".atomic".
85 */
86 #define OSRF_METHOD_ATOMIC          4
87 /*@}*/
88
89 /**
90         @brief Represent an Application.
91 */
92 typedef struct {
93         void* handle;               /**< Handle to the shared object library. */
94         osrfHash* methods;          /**< Registry of method names. */
95         void (*onExit) (void);      /**< Exit handler for the application. */
96 } osrfApplication;
97
98 static void register_method( osrfApplication* app, const char* methodName,
99         const char* symbolName, const char* notes, int argc, int options, void * user_data );
100 static osrfMethod* build_method( const char* methodName, const char* symbolName,
101         const char* notes, int argc, int options, void* );
102 static void osrfAppSetOnExit(osrfApplication* app, const char* appName);
103 static void register_system_methods( osrfApplication* app );
104 static inline osrfApplication* _osrfAppFindApplication( const char* name );
105 static inline osrfMethod* osrfAppFindMethod( osrfApplication* app, const char* methodName );
106 static int _osrfAppRespond( osrfMethodContext* context, const jsonObject* data, int complete );
107 static int _osrfAppPostProcess( osrfMethodContext* context, int retcode );
108 static int _osrfAppRunSystemMethod(osrfMethodContext* context);
109 static void _osrfAppSetIntrospectMethod( osrfMethodContext* ctx, const osrfMethod* method,
110         jsonObject* resp );
111 static int osrfAppIntrospect( osrfMethodContext* ctx );
112 static int osrfAppIntrospectAll( osrfMethodContext* ctx );
113 static int osrfAppEcho( osrfMethodContext* ctx );
114 static void osrfMethodFree( char* name, void* p );
115 static void osrfAppFree( char* name, void* p );
116
117 /**
118         @brief Registry of applications.
119
120         The key of the hash is the application name, and the associated data is an osrfApplication.
121 */
122 static osrfHash* _osrfAppHash = NULL;
123
124 /**
125         @brief Register an application.
126         @param appName Name of the application.
127         @param soFile Name of the shared object file to be loaded for this application.
128         @return Zero if successful, or -1 upon error.
129
130         Open the shared object file and call its osrfAppInitialize() function, if it has one.
131         Register the standard system methods for it.  Arrange for the application name to
132         appear in subsequent log messages.
133 */
134 int osrfAppRegisterApplication( const char* appName, const char* soFile ) {
135         if( !appName || ! soFile ) return -1;
136         char* error;
137
138         osrfLogSetAppname( appName );
139
140         if( !_osrfAppHash ) {
141                 _osrfAppHash = osrfNewHash();
142                 osrfHashSetCallback( _osrfAppHash, osrfAppFree );
143         }
144
145         osrfLogInfo( OSRF_LOG_MARK, "Registering application %s with file %s", appName, soFile );
146
147         // Open the shared object.
148         void* handle = dlopen( soFile, RTLD_NOW );
149         if( ! handle ) {
150                 const char* msg = dlerror();
151                 osrfLogError( OSRF_LOG_MARK, "Failed to dlopen library file %s: %s", soFile, msg );
152                 return -1;
153         }
154
155         // Construct the osrfApplication.
156         osrfApplication* app = safe_malloc(sizeof(osrfApplication));
157         app->handle = handle;
158         app->methods = osrfNewHash();
159         osrfHashSetCallback( app->methods, osrfMethodFree );
160         app->onExit = NULL;
161
162         // Add the newly-constructed app to the list.
163         osrfHashSet( _osrfAppHash, app, appName );
164
165         // Try to run the initialize method.  Typically it will register one or more
166         // methods of the application.
167         int (*init) (void);
168         *(void **) (&init) = dlsym( handle, "osrfAppInitialize" );
169
170         if( (error = dlerror()) != NULL ) {
171                 osrfLogWarning( OSRF_LOG_MARK,
172                         "! Unable to locate method symbol [osrfAppInitialize] for app %s: %s",
173                         appName, error );
174
175         } else {
176
177                 /* run the method */
178                 int ret;
179                 if( (ret = (*init)()) ) {
180                         osrfLogWarning( OSRF_LOG_MARK, "Application %s returned non-zero value from "
181                                 "'osrfAppInitialize', not registering...", appName );
182                         osrfHashRemove( _osrfAppHash, appName );
183                         return ret;
184                 }
185         }
186
187         register_system_methods( app );
188         osrfLogInfo( OSRF_LOG_MARK, "Application %s registered successfully", appName );
189         osrfAppSetOnExit( app, appName );
190
191         return 0;
192 }
193
194 /**
195         @brief Save a pointer to the application's exit function.
196         @param app Pointer to the osrfApplication.
197         @param appName Application name (used only for log messages).
198
199         Look in the shared object for a symbol named "osrfAppChildExit".  If you find one, save
200         it as a pointer to the application's exit function.  If present, this function will be
201         called when a server's child process (a so-called "drone") is shutting down.
202 */
203 static void osrfAppSetOnExit(osrfApplication* app, const char* appName) {
204         if(!(app && appName)) return;
205
206         /* see if we can run the initialize method */
207         char* error;
208         void (*onExit) (void);
209         *(void **) (&onExit) = dlsym(app->handle, "osrfAppChildExit");
210
211         if( (error = dlerror()) != NULL ) {
212                 osrfLogDebug(OSRF_LOG_MARK, "No exit handler defined for %s", appName);
213                 return;
214         }
215
216         osrfLogInfo(OSRF_LOG_MARK, "registering exit handler for %s", appName);
217         app->onExit = (*onExit);
218 }
219
220 /**
221         @brief Run the application-specific child initialization function for a given application.
222         @param appname Name of the application.
223         @return Zero if successful, or if the application has no child initialization function; -1
224         if the application is not registered, or if the function returns non-zero.
225
226         The child initialization function must be named "osrfAppChildInit" within the shared
227         object library.  It initializes a drone process of a server.
228 */
229 int osrfAppRunChildInit(const char* appname) {
230         osrfApplication* app = _osrfAppFindApplication(appname);
231         if(!app) return -1;
232
233         char* error;
234         int ret;
235         int (*childInit) (void);
236
237         *(void**) (&childInit) = dlsym(app->handle, "osrfAppChildInit");
238
239         if( (error = dlerror()) != NULL ) {
240                 osrfLogInfo( OSRF_LOG_MARK, "No child init defined for app %s : %s", appname, error);
241                 return 0;
242         }
243
244         if( (ret = (*childInit)()) ) {
245                 osrfLogError(OSRF_LOG_MARK, "App %s child init failed", appname);
246                 return -1;
247         }
248
249         osrfLogInfo(OSRF_LOG_MARK, "%s child init succeeded", appname);
250         return 0;
251 }
252
253 /**
254         @brief Call the exit handler for every application that has one.
255
256         Normally a server's child process (a so-called "drone") calls this function just before
257         shutting down.
258 */
259 void osrfAppRunExitCode( void ) {
260         osrfHashIterator* itr = osrfNewHashIterator(_osrfAppHash);
261         osrfApplication* app;
262         while( (app = osrfHashIteratorNext(itr)) ) {
263                 if( app->onExit ) {
264                         osrfLogInfo(OSRF_LOG_MARK, "Running onExit handler for app %s",
265                                 osrfHashIteratorKey(itr) );
266                         app->onExit();
267                 }
268         }
269         osrfHashIteratorFree(itr);
270 }
271
272 /**
273         @brief Register a method for a specified application.
274
275         @param appName Name of the application that implements the method.
276         @param methodName The fully qualified name of the method.
277         @param symbolName The symbol name (function name) that implements the method.
278         @param notes Public documentation for this method.
279         @param argc The minimum number of arguments for the function.
280         @param options Bit switches setting various options.
281         @return Zero on success, or -1 on error.
282
283         Registering a method enables us to call the right function when a client requests a
284         method call.
285
286         The @a options parameter is zero or more of the following macros, OR'd together:
287
288         - OSRF_METHOD_STREAMING     method may return more than one response
289         - OSRF_METHOD_CACHABLE      cache results in memcache
290
291         If the OSRF_METHOD_STREAMING bit is set, also register an ".atomic" version of the method.
292 */
293 int osrfAppRegisterMethod( const char* appName, const char* methodName,
294                 const char* symbolName, const char* notes, int argc, int options ) {
295
296         return osrfAppRegisterExtendedMethod(
297                         appName,
298                         methodName,
299                         symbolName,
300                         notes,
301                         argc,
302                         options,
303                         NULL
304         );
305 }
306
307 /**
308         @brief Register an extended method for a specified application.
309
310         @param appName Name of the application that implements the method.
311         @param methodName The fully qualified name of the method.
312         @param symbolName The symbol name (function name) that implements the method.
313         @param notes Public documentation for this method.
314         @param argc How many arguments this method expects.
315         @param options Bit switches setting various options.
316         @param user_data Opaque pointer to be passed to the dynamically called function.
317         @return Zero if successful, or -1 upon error.
318
319         This function is identical to osrfAppRegisterMethod(), except that it also installs
320         a method-specific opaque pointer.  When we call the corresponding function at
321         run time, this pointer will be available to the function via the method context.
322 */
323 int osrfAppRegisterExtendedMethod( const char* appName, const char* methodName,
324         const char* symbolName, const char* notes, int argc, int options, void * user_data ) {
325
326         if( !appName || ! methodName ) return -1;
327
328         osrfApplication* app = _osrfAppFindApplication(appName);
329         if(!app) {
330                 osrfLogWarning( OSRF_LOG_MARK, "Unable to locate application %s", appName );
331                 return -1;
332         }
333
334         osrfLogDebug( OSRF_LOG_MARK, "Registering method %s for app %s", methodName, appName );
335
336         // Extract the only valid option bits, and ignore the rest.
337         int opts = options & ( OSRF_METHOD_STREAMING | OSRF_METHOD_CACHABLE );
338
339         // Build and install a non-atomic method.
340         register_method(
341                 app, methodName, symbolName, notes, argc, opts, user_data );
342
343         if( opts & OSRF_METHOD_STREAMING ) {
344                 // Build and install an atomic version of the same method.
345                 register_method(
346                         app, methodName, symbolName, notes, argc, opts | OSRF_METHOD_ATOMIC, user_data );
347         }
348
349         return 0;
350 }
351
352 /**
353         @brief Register a single method for a specified application.
354
355         @param appName Pointer to the application that implements the method.
356         @param methodName The fully qualified name of the method.
357         @param symbolName The symbol name (function name) that implements the method.
358         @param notes Public documentation for this method.
359         @param argc How many arguments this method expects.
360         @param options Bit switches setting various options.
361         @param user_data Opaque pointer to be passed to the dynamically called function.
362 */
363 static void register_method( osrfApplication* app, const char* methodName,
364         const char* symbolName, const char* notes, int argc, int options, void * user_data ) {
365
366         if( !app || ! methodName ) return;
367
368         // Build a method and add it to the list of methods
369         osrfMethod* method = build_method(
370                 methodName, symbolName, notes, argc, options, user_data );
371         osrfHashSet( app->methods, method, method->name );
372 }
373
374 /**
375         @brief Allocate and populate an osrfMethod.
376         @param methodName Name of the method.
377         @param symbolName Name of the function that implements the method.
378         @param notes Remarks documenting the method.
379         @param argc Minimum number of arguments to the method.
380         @param options Bit switches setting various options.
381         @param user_data An opaque pointer to be passed in the method context.
382         @return Pointer to the newly allocated osrfMethod.
383
384         If OSRF_METHOD_ATOMIC is set, append ".atomic" to the method name.
385 */
386 static osrfMethod* build_method( const char* methodName, const char* symbolName,
387         const char* notes, int argc, int options, void* user_data ) {
388
389         osrfMethod* method      = safe_malloc(sizeof(osrfMethod));
390
391         if( !methodName )
392                 methodName = "";  // should never happen
393
394         if( options & OSRF_METHOD_ATOMIC ) {
395                 // Append ".atomic" to the name.
396                 char mb[ strlen( methodName ) + 8 ];
397                 sprintf( mb, "%s.atomic", methodName );
398                 method->name        = strdup( mb );
399         } else {
400                 method->name        = strdup(methodName);
401         }
402
403         if(symbolName)
404                 method->symbol      = strdup(symbolName);
405         else
406                 method->symbol      = NULL;
407
408         if(notes)
409                 method->notes       = strdup(notes);
410         else
411                 method->notes       = NULL;
412
413         method->argc            = argc;
414         method->options         = options;
415
416         if(user_data)
417                 method->userData    = user_data;
418
419         method->max_bundle_size = OSRF_MSG_BUNDLE_SIZE;
420     method->max_chunk_size  = OSRF_MSG_CHUNK_SIZE;
421         return method;
422 }
423
424 /**
425         @brief Set the effective output buffer size for a given method.
426         @param appName Name of the application.
427         @param methodName Name of the method.
428         @param max_bundle_size Desired size of the output buffer, in bytes.
429         @return Zero if successful, or -1 if the specified method cannot be found.
430
431         A smaller buffer size may result in a lower latency for the first response, since we don't
432         wait for as many messages to accumulate before flushing the output buffer.  On the other
433         hand a larger buffer size may result in higher throughput due to lower network overhead.
434
435         Since the buffer size is not an absolute limit, it may be set to zero, in which case each
436         output transport message will contain no more than one RESULT message.
437
438         This function has no effect on atomic methods, because all responses are sent in a single
439         message anyway.  Likewise it has no effect on a method that returns only a single response.
440 */
441 int osrfMethodSetBundleSize( const char* appName, const char* methodName, size_t max_bundle_size ) {
442         osrfMethod* method = _osrfAppFindMethod( appName, methodName );
443         if( method ) {
444                 osrfLogInfo( OSRF_LOG_MARK,
445                         "Setting outbuf buffer size to %lu for method %s of application %s",
446                         (unsigned long) max_bundle_size, methodName, appName );
447                 method->max_bundle_size = max_bundle_size;
448                 return 0;
449         } else {
450                 osrfLogWarning( OSRF_LOG_MARK,
451                         "Unable to set outbuf buffer size to %lu for method %s of application %s",
452                         (unsigned long) max_bundle_size, methodName, appName );
453                 return -1;
454         }
455 }
456
457 /**
458         @brief Register all of the system methods for this application.
459         @param app Pointer to the application.
460
461         A client can call these methods the same way it calls application-specific methods,
462         but they are implemented by functions here in this module, not by functions in the
463         shared object.
464 */
465 static void register_system_methods( osrfApplication* app ) {
466
467         if( !app ) return;
468
469         register_method(
470                 app, OSRF_SYSMETHOD_INTROSPECT, NULL,
471                 "Return a list of methods whose names have the same initial "
472                 "substring as that of the provided method name PARAMS( methodNameSubstring )",
473                 1, OSRF_METHOD_SYSTEM | OSRF_METHOD_STREAMING,
474                 NULL );
475
476         register_method(
477                 app, OSRF_SYSMETHOD_INTROSPECT, NULL,
478                 "Return a list of methods whose names have the same initial "
479                 "substring as that of the provided method name PARAMS( methodNameSubstring )",
480                 1, OSRF_METHOD_SYSTEM | OSRF_METHOD_STREAMING | OSRF_METHOD_ATOMIC,
481                 NULL );
482
483         register_method(
484                 app, OSRF_SYSMETHOD_INTROSPECT_ALL, NULL,
485                 "Returns a complete list of methods. PARAMS()",
486                 0, OSRF_METHOD_SYSTEM | OSRF_METHOD_STREAMING,
487                 NULL );
488
489         register_method(
490                 app, OSRF_SYSMETHOD_INTROSPECT_ALL, NULL,
491                 "Returns a complete list of methods. PARAMS()",
492                 0, OSRF_METHOD_SYSTEM | OSRF_METHOD_STREAMING | OSRF_METHOD_ATOMIC,
493                 NULL );
494
495         register_method(
496                 app, OSRF_SYSMETHOD_ECHO, NULL,
497                 "Echos all data sent to the server back to the client. PARAMS([a, b, ...])",
498                 0, OSRF_METHOD_SYSTEM | OSRF_METHOD_STREAMING,
499                 NULL );
500
501         register_method(
502                 app, OSRF_SYSMETHOD_ECHO, NULL,
503                 "Echos all data sent to the server back to the client. PARAMS([a, b, ...])",
504                 0, OSRF_METHOD_SYSTEM | OSRF_METHOD_STREAMING | OSRF_METHOD_ATOMIC,
505                 NULL );
506 }
507
508 /**
509         @brief Look up an application by name in the application registry.
510         @param name The name of the application.
511         @return Pointer to the corresponding osrfApplication if found, or NULL if not.
512 */
513 static inline osrfApplication* _osrfAppFindApplication( const char* name ) {
514         return (osrfApplication*) osrfHashGet(_osrfAppHash, name);
515 }
516
517 /**
518         @brief Look up a method by name for a given application.
519         @param app Pointer to the osrfApplication that owns the method.
520         @param methodName Name of the method to find.
521         @return Pointer to the corresponding osrfMethod if found, or NULL if not.
522 */
523 static inline osrfMethod* osrfAppFindMethod( osrfApplication* app, const char* methodName ) {
524         if( !app ) return NULL;
525         return (osrfMethod*) osrfHashGet( app->methods, methodName );
526 }
527
528 /**
529         @brief Look up a method by name for an application with a given name.
530         @param appName Name of the osrfApplication.
531         @param methodName Name of the method to find.
532         @return Pointer to the corresponding osrfMethod if found, or NULL if not.
533 */
534 osrfMethod* _osrfAppFindMethod( const char* appName, const char* methodName ) {
535         if( !appName ) return NULL;
536         return osrfAppFindMethod( _osrfAppFindApplication(appName), methodName );
537 }
538
539 /**
540         @brief Call the function that implements a specified method.
541         @param appName Name of the application.
542         @param methodName Name of the method.
543         @param ses Pointer to the current application session.
544         @param reqId The request id of the request invoking the method.
545         @param params Pointer to a jsonObject encoding the parameters to the method.
546         @return Zero if successful, or -1 upon failure.
547
548         If we can't find a function corresponding to the method, or if we call it and it returns
549         a negative return code, send a STATUS message to the client to report an exception.
550
551         A return code of -1 means that the @a appName, @a methodName, or @a ses parameter was NULL.
552 */
553 int osrfAppRunMethod( const char* appName, const char* methodName,
554                 osrfAppSession* ses, int reqId, jsonObject* params ) {
555
556         if( !(appName && methodName && ses) ) return -1;
557
558         // Find the application, and then find the method for it
559         osrfApplication* app = _osrfAppFindApplication(appName);
560         if( !app )
561                 return osrfAppRequestRespondException( ses,
562                                 reqId, "Application not found: %s", appName );
563
564         osrfMethod* method = osrfAppFindMethod( app, methodName );
565         if( !method )
566                 return osrfAppRequestRespondException( ses, reqId,
567                                 "Method [%s] not found for service %s", methodName, appName );
568
569         #ifdef OSRF_STRICT_PARAMS
570         if( method->argc > 0 ) {
571                 // Make sure that the client has passed at least the minimum number of arguments.
572                 if(!params || params->type != JSON_ARRAY || params->size < method->argc )
573                         return osrfAppRequestRespondException( ses, reqId,
574                                 "Not enough params for method %s / service %s", methodName, appName );
575         }
576         #endif
577
578         // Build an osrfMethodContext, which we will pass by pointer to the function.
579         osrfMethodContext context;
580
581         context.session = ses;
582         context.method = method;
583         context.params = params;
584         context.request = reqId;
585         context.responses = NULL;
586
587         int retcode = 0;
588
589         if( method->options & OSRF_METHOD_SYSTEM ) {
590                 retcode = _osrfAppRunSystemMethod(&context);
591
592         } else {
593
594                 // Function pointer through which we will call the function dynamically
595                 int (*meth) (osrfMethodContext*);
596
597                 // Open the function that implements the method
598                 meth = dlsym(app->handle, method->symbol);
599
600                 const char* error = dlerror();
601                 if( error != NULL ) {
602                         return osrfAppRequestRespondException( ses, reqId,
603                                 "Unable to execute method [%s] for service %s", methodName, appName );
604                 }
605
606                 // Run it
607                 retcode = meth( &context );
608         }
609
610         if(retcode < 0)
611                 return osrfAppRequestRespondException(
612                                 ses, reqId, "An unknown server error occurred" );
613
614         retcode = _osrfAppPostProcess( &context, retcode );
615
616         if( context.responses )
617                 jsonObjectFree( context.responses );
618         return retcode;
619 }
620
621 /**
622         @brief Either send or enqueue a response to a client.
623         @param ctx Pointer to the current method context.
624         @param data Pointer to the response, in the form of a jsonObject.
625         @return Zero if successful, or -1 upon error.  The only recognized errors are if either
626         the @a context pointer or its method pointer is NULL.
627
628         For an atomic method, add a copy of the response data to a cache within the method
629         context, to be sent later.  Otherwise, send a RESULT message to the client, with the
630         results in @a data.
631
632         Note that, for an atomic method, this function is equivalent to osrfAppRespondComplete():
633         we send the STATUS message after the method returns, and not before.
634 */
635 int osrfAppRespond( osrfMethodContext* ctx, const jsonObject* data ) {
636         return _osrfAppRespond( ctx, data, 0 );
637 }
638
639 /**
640         @brief Either send or enqueue a response to a client, with a completion notice.
641         @param context Pointer to the current method context.
642         @param data Pointer to the response, in the form of a jsonObject.
643         @return Zero if successful, or -1 upon error.  The only recognized errors are if either
644         the @a context pointer or its method pointer is NULL.
645
646         For an atomic method, add a copy of the response data to a cache within the method
647         context, to be sent later.  Otherwise, send a RESULT message to the client, with the
648         results in @a data.  Also send a STATUS message to indicate that the response is complete.
649
650         Note that, for an atomic method, this function is equivalent to osrfAppRespond(): we
651         send the STATUS message after the method returns, and not before.
652 */
653 int osrfAppRespondComplete( osrfMethodContext* context, const jsonObject* data ) {
654         return _osrfAppRespond( context, data, 1 );
655 }
656
657 /**
658         @brief Send any response messages that have accumulated in the output buffer.
659         @param ses Pointer to the current application session.
660         @param outbuf Pointer to the output buffer.
661         @return Zero if successful, or -1 if not.
662
663         Used only by servers to respond to clients.
664 */
665 static int flush_responses( osrfAppSession* ses, growing_buffer* outbuf ) {
666
667         // Collect any inbound traffic on the socket(s).  This doesn't accomplish anything for the
668         // immediate task at hand, but it may help to keep TCP from getting clogged in some cases.
669         osrf_app_session_queue_wait( ses, 0, NULL );
670
671         int rc = 0;
672         if( buffer_length( outbuf ) > 0 ) {    // If there's anything to send...
673                 buffer_add_char( outbuf, ']' );    // Close the JSON array
674                 if( osrfSendTransportPayload( ses, OSRF_BUFFER_C_STR( ses->outbuf ))) {
675                         osrfLogError( OSRF_LOG_MARK, "Unable to flush response buffer" );
676                         rc = -1;
677                 }
678         }
679         buffer_reset( ses->outbuf );
680         return rc;
681 }
682
683 /**
684         @brief Add a message to an output buffer.
685         @param outbuf Pointer to the output buffer.
686         @param msg Pointer to the message to be added, in the form of a JSON string.
687
688         Since the output buffer is in the form of a JSON array, prepend a left bracket to the
689         first message, and a comma to subsequent ones.
690
691         Used only by servers to respond to clients.
692 */
693 static inline void append_msg( growing_buffer* outbuf, const char* msg ) {
694         if( outbuf && msg ) {
695                 char prefix = buffer_length( outbuf ) > 0 ? ',' : '[';
696                 buffer_add_char( outbuf, prefix );
697                 buffer_add( outbuf, msg );
698         }
699 }
700
701 /**
702         @brief Either send or enqueue a response to a client, optionally with a completion notice.
703         @param ctx Pointer to the method context.
704         @param data Pointer to the response, in the form of a jsonObject.
705         @param complete Boolean: if true, we will accompany the RESULT message with a STATUS
706         message indicating that the response is complete.
707         @return Zero if successful, or -1 upon error.
708
709         For an atomic method, add a copy of the response data to a cache within the method
710         context, to be sent later.  In this case the @a complete parameter has no effect,
711         because we'll send the STATUS message later when we send the cached results.
712
713         If the method is not atomic, translate the message into JSON and append it to a buffer,
714         flushing the buffer as needed to avoid overflow.  If @a complete is true, append
715         a STATUS message (as JSON) to the buffer and flush the buffer.
716 */
717 static int _osrfAppRespond( osrfMethodContext* ctx, const jsonObject* data, int complete ) {
718         if(!(ctx && ctx->method)) return -1;
719
720         if( ctx->method->options & OSRF_METHOD_ATOMIC ) {
721                 osrfLogDebug( OSRF_LOG_MARK,
722                         "Adding responses to stash for atomic method %s", ctx->method->name );
723
724                 // If we don't already have one, create a JSON_ARRAY to serve as a cache.
725                 if( ctx->responses == NULL )
726                         ctx->responses = jsonNewObjectType( JSON_ARRAY );
727
728                 // Add a copy of the data object to the cache.
729                 if ( data != NULL )
730                         jsonObjectPush( ctx->responses, jsonObjectClone(data) );
731         } else {
732                 osrfLogDebug( OSRF_LOG_MARK,
733                         "Adding responses to stash for method %s", ctx->method->name );
734
735                 if( data ) {
736             char* data_str = jsonObjectToJSON(data); // free me (below)
737             size_t data_size = strlen(data_str);
738             size_t chunk_size = ctx->method->max_chunk_size;
739
740             if (chunk_size > 0 && chunk_size < data_size) {
741                 // chunking -- response message exceeds max message size.
742                 // break it up into chunks for partial delivery
743
744                                 osrfSendChunkedResult(ctx->session, ctx->request,
745                                                                           data_str, data_size, chunk_size);
746
747             } else {
748
749                 // bundling -- message body (may be) too small for single
750                 // delivery.  prepare message for bundling.
751
752                 // Create an OSRF message
753                 osrfMessage* msg = osrf_message_init( RESULT, ctx->request, 1 );
754                 osrf_message_set_status_info( msg, NULL, "OK", OSRF_STATUS_OK );
755                 osrf_message_set_result( msg, data );
756
757                 // Serialize the OSRF message into JSON text
758                 char* json = jsonObjectToJSON( osrfMessageToJSON( msg ));
759                 osrfMessageFree( msg );
760
761                 // If the new message would overflow the buffer, flush the output buffer first
762                 int len_so_far = buffer_length( ctx->session->outbuf );
763                 if( len_so_far && (strlen( json ) + len_so_far + 3 >= ctx->method->max_bundle_size )) {
764                     if( flush_responses( ctx->session, ctx->session->outbuf ))
765                         return -1;
766                 }
767
768                 // Append the JSON text to the output buffer
769                 append_msg( ctx->session->outbuf, json );
770                 free( json );
771             }
772
773             free(data_str);
774                 }
775
776                 if(complete) {
777                         // Create a STATUS message
778                         osrfMessage* status_msg = osrf_message_init( STATUS, ctx->request, 1 );
779                         osrf_message_set_status_info( status_msg, "osrfConnectStatus", "Request Complete",
780                                 OSRF_STATUS_COMPLETE );
781
782                         // Serialize the STATUS message into JSON text
783                         char* json = jsonObjectToJSON( osrfMessageToJSON( status_msg ));
784                         osrfMessageFree( status_msg );
785
786                         // Add the STATUS message to the output buffer.
787                         // It's short, so don't worry about avoiding overflow.
788                         append_msg( ctx->session->outbuf, json );
789                         free( json );
790
791                         // Flush the output buffer, sending any accumulated messages.
792                         if( flush_responses( ctx->session, ctx->session->outbuf ))
793                                 return -1;
794                 }
795         }
796
797         return 0;
798 }
799
800 /**
801         @brief Finish up the processing of a request.
802         @param ctx Pointer to the method context.
803         @param retcode The return code from the method's function.
804         @return 0 if successfull, or -1 upon error.
805
806         For an atomic method: send whatever responses we have been saving up, together with a
807         STATUS message to say that we're finished.
808
809         For a non-atomic method: if the return code from the method is greater than zero, just
810         send the STATUS message.  If the return code is zero, do nothing; the method presumably
811         sent the STATUS message on its own.
812 */
813 static int _osrfAppPostProcess( osrfMethodContext* ctx, int retcode ) {
814         if(!(ctx && ctx->method)) return -1;
815
816         osrfLogDebug( OSRF_LOG_MARK, "Postprocessing method %s with retcode %d",
817                         ctx->method->name, retcode );
818
819         if(ctx->responses) {
820                 // We have cached atomic responses to return, collected in a JSON ARRAY (we
821                 // haven't sent any responses yet).  Now send them all at once, followed by
822                 // a STATUS message to say that we're finished.
823                 osrfAppRequestRespondComplete( ctx->session, ctx->request, ctx->responses );
824
825         } else {
826                 // We have no cached atomic responses to return, but we may have some
827                 // non-atomic messages waiting in the buffer.
828                 if( retcode > 0 )
829                         // Send a STATUS message to say that we're finished, and to force a
830                         // final flush of the buffer.
831                         osrfAppRespondComplete( ctx, NULL );
832         }
833
834         return 0;
835 }
836
837 /**
838         @brief Send a STATUS message to the client, notifying it of an error.
839         @param ses Pointer to the current application session.
840         @param request Request ID of the request.
841         @param msg A printf-style format string defining an explanatory message to be sent to
842         the client.  Subsequent parameters, if any, will be formatted and inserted into the
843         resulting output string.
844         @return -1 if the @a ses parameter is NULL; otherwise zero.
845 */
846 int osrfAppRequestRespondException( osrfAppSession* ses, int request, const char* msg, ... ) {
847         if(!ses) return -1;
848         if(!msg) msg = "";
849         VA_LIST_TO_STRING(msg);
850         osrfLogWarning( OSRF_LOG_MARK,  "Returning method exception with message: %s", VA_BUF );
851         osrfAppSessionStatus( ses, OSRF_STATUS_NOTFOUND, "osrfMethodException", request,  VA_BUF );
852         return 0;
853 }
854
855 /**
856         @brief Introspect a specified method.
857         @param ctx Pointer to the method context.
858         @param method Pointer to the osrfMethod for the specified method.
859         @param resp Pointer to the jsonObject into which method information will be placed.
860
861         Treating the @a resp object as a JSON_HASH, insert entries for various bits of information
862         about the specified method.
863 */
864 static void _osrfAppSetIntrospectMethod( osrfMethodContext* ctx, const osrfMethod* method,
865                 jsonObject* resp ) {
866         if(!(ctx && resp)) return;
867
868         jsonObjectSetKey(resp, "api_name",  jsonNewObject(method->name));
869         jsonObjectSetKey(resp, "method",    jsonNewObject(method->symbol));
870         jsonObjectSetKey(resp, "service",   jsonNewObject(ctx->session->remote_service));
871         jsonObjectSetKey(resp, "notes",     jsonNewObject(method->notes));
872         jsonObjectSetKey(resp, "argc",      jsonNewNumberObject(method->argc));
873
874         jsonObjectSetKey(resp, "sysmethod",
875                         jsonNewNumberObject( (method->options & OSRF_METHOD_SYSTEM) ? 1 : 0 ));
876         jsonObjectSetKey(resp, "atomic",
877                         jsonNewNumberObject( (method->options & OSRF_METHOD_ATOMIC) ? 1 : 0 ));
878         jsonObjectSetKey(resp, "cachable",
879                         jsonNewNumberObject( (method->options & OSRF_METHOD_CACHABLE) ? 1 : 0 ));
880 }
881
882 /**
883         @brief Run the requested system method.
884         @param ctx The method context.
885         @return Zero if the method is run successfully; -1 if the method was not run; 1 if the
886         method was run and the application code now needs to send a 'request complete' message.
887
888         A system method is a well known method implemented here for all servers.  Instead of
889         looking in the shared object, branch on the method name and call the corresponding
890         function.
891 */
892 static int _osrfAppRunSystemMethod(osrfMethodContext* ctx) {
893         if( osrfMethodVerifyContext( ctx ) < 0 ) {
894                 osrfLogError( OSRF_LOG_MARK,  "_osrfAppRunSystemMethod: Received invalid method context" );
895                 return -1;
896         }
897
898         if( !strcmp(ctx->method->name, OSRF_SYSMETHOD_INTROSPECT_ALL ) ||
899                         !strcmp(ctx->method->name, OSRF_SYSMETHOD_INTROSPECT_ALL_ATOMIC )) {
900                 return osrfAppIntrospectAll(ctx);
901         }
902
903         if( !strcmp(ctx->method->name, OSRF_SYSMETHOD_INTROSPECT ) ||
904                         !strcmp(ctx->method->name, OSRF_SYSMETHOD_INTROSPECT_ATOMIC )) {
905                 return osrfAppIntrospect(ctx);
906         }
907
908         if( !strcmp(ctx->method->name, OSRF_SYSMETHOD_ECHO ) ||
909                         !strcmp(ctx->method->name, OSRF_SYSMETHOD_ECHO_ATOMIC )) {
910                 return osrfAppEcho(ctx);
911         }
912
913         osrfAppRequestRespondException( ctx->session,
914                         ctx->request, "System method implementation not found");
915
916         return 0;
917 }
918
919 /**
920         @brief Run the introspect method for a specified method or group of methods.
921         @param ctx Pointer to the method context.
922         @return 1 if successful, or if no search target is specified as a parameter; -1 if unable
923         to find a pointer to the application.
924
925         Traverse the list of methods, and report on each one whose name starts with the specified
926         search target.  In effect, the search target ends with an implicit wild card.
927 */
928 static int osrfAppIntrospect( osrfMethodContext* ctx ) {
929
930         // Get the name of the method to introspect
931         const char* methodSubstring = jsonObjectGetString( jsonObjectGetIndex(ctx->params, 0) );
932         if( !methodSubstring )
933                 return 1; /* respond with no methods */
934
935         // Get a pointer to the application
936         osrfApplication* app = _osrfAppFindApplication( ctx->session->remote_service );
937         if( !app )
938                 return -1;   // Oops, no application...
939
940         int len = 0;
941         osrfHashIterator* itr = osrfNewHashIterator(app->methods);
942         osrfMethod* method;
943
944         while( (method = osrfHashIteratorNext(itr)) ) {
945                 if( (len = strlen(methodSubstring)) <= strlen(method->name) ) {
946                         if( !strncmp( method->name, methodSubstring, len) ) {
947                                 jsonObject* resp = jsonNewObject(NULL);
948                                 _osrfAppSetIntrospectMethod( ctx, method, resp );
949                                 osrfAppRespond(ctx, resp);
950                                 jsonObjectFree(resp);
951                         }
952                 }
953         }
954
955         osrfHashIteratorFree(itr);
956         return 1;
957 }
958
959 /**
960         @brief Run the implement_all method.
961         @param ctx Pointer to the method context.
962         @return 1 if successful, or -1 if unable to find a pointer to the application.
963
964         Report on all of the methods of the application.
965 */
966 static int osrfAppIntrospectAll( osrfMethodContext* ctx ) {
967         osrfApplication* app = _osrfAppFindApplication( ctx->session->remote_service );
968
969         if(app) {
970                 osrfHashIterator* itr = osrfNewHashIterator(app->methods);
971                 osrfMethod* method;
972                 while( (method = osrfHashIteratorNext(itr)) ) {
973                         jsonObject* resp = jsonNewObject(NULL);
974                         _osrfAppSetIntrospectMethod( ctx, method, resp );
975                         osrfAppRespond(ctx, resp);
976                         jsonObjectFree(resp);
977                 }
978                 osrfHashIteratorFree(itr);
979                 return 1;
980         } else
981                 return -1;
982 }
983
984 /**
985         @brief Run the echo method.
986         @param ctx Pointer to the method context.
987         @return -1 if the method context is invalid or corrupted; otherwise 1.
988
989         Send the client a copy of each parameter.
990 */
991 static int osrfAppEcho( osrfMethodContext* ctx ) {
992         if( osrfMethodVerifyContext( ctx ) < 0 ) {
993                 osrfLogError( OSRF_LOG_MARK,  "osrfAppEcho: Received invalid method context" );
994                 return -1;
995         }
996
997         int i;
998         for( i = 0; i < ctx->params->size; i++ ) {
999                 const jsonObject* str = jsonObjectGetIndex(ctx->params,i);
1000                 osrfAppRespond(ctx, str);
1001         }
1002         return 1;
1003 }
1004
1005 /**
1006         @brief Perform a series of sanity tests on an osrfMethodContext.
1007         @param ctx Pointer to the osrfMethodContext to be checked.
1008         @return Zero if the osrfMethodContext passes all tests, or -1 if it doesn't.
1009 */
1010 int osrfMethodVerifyContext( osrfMethodContext* ctx )
1011 {
1012         if( !ctx ) {
1013                 osrfLogError( OSRF_LOG_MARK,  "Context is NULL in app request" );
1014                 return -1;
1015         }
1016
1017         if( !ctx->session ) {
1018                 osrfLogError( OSRF_LOG_MARK, "Session is NULL in app request" );
1019                 return -1;
1020         }
1021
1022         if( !ctx->method )
1023         {
1024                 osrfLogError( OSRF_LOG_MARK, "Method is NULL in app request" );
1025                 return -1;
1026         }
1027
1028         if( ctx->method->argc ) {
1029                 if( !ctx->params ) {
1030                         osrfLogError( OSRF_LOG_MARK,
1031                                 "Params is NULL in app request %s", ctx->method->name );
1032                         return -1;
1033                 }
1034                 if( ctx->params->type != JSON_ARRAY ) {
1035                         osrfLogError( OSRF_LOG_MARK,
1036                                 "'params' is not a JSON array for method %s", ctx->method->name );
1037                         return -1;
1038                 }
1039         }
1040
1041         if( !ctx->method->name ) {
1042                 osrfLogError( OSRF_LOG_MARK, "Method name is NULL" );
1043                  return -1;
1044         }
1045
1046         // Log the call, with the method and parameters
1047         char* params_str = jsonObjectToJSON( ctx->params );
1048         if( params_str ) {
1049                 // params_str will at minimum be "[]"
1050                 int i = 0;
1051                 const char* str;
1052                 char* method = ctx->method->name;
1053                 int redact_params = 0;
1054                 while( (str = osrfStringArrayGetString(log_protect_arr, i++)) ) {
1055                         //osrfLogInternal(OSRF_LOG_MARK, "Checking for log protection [%s]", str);
1056                         if(!strncmp(method, str, strlen(str))) {
1057                                 redact_params = 1;
1058                                 break;
1059                         }
1060                 }
1061
1062                 char* params_logged;
1063                 if(redact_params) {
1064                         params_logged = strdup("**PARAMS REDACTED**");
1065                 } else {
1066                         params_str[strlen(params_str) - 1] = '\0'; // drop the trailing ']'
1067                         params_logged = strdup(params_str + 1);
1068                 }
1069                 free( params_str );
1070                 osrfLogInfo( OSRF_LOG_MARK, "CALL: %s %s %s",
1071                         ctx->session->remote_service, ctx->method->name, params_logged);
1072                 free( params_logged );
1073         }
1074         return 0;
1075 }
1076
1077 /**
1078         @brief Free an osrfMethod.
1079         @param name Name of the method (not used).
1080         @param p Void pointer pointing to the osrfMethod.
1081
1082         This function is designed to be installed as a callback for an osrfHash (hence the
1083         unused @a name parameter and the void pointer).
1084 */
1085 static void osrfMethodFree( char* name, void* p ) {
1086         osrfMethod* method = p;
1087         if( method ) {
1088                 free( method->name );
1089                 free( method->symbol );
1090                 free( method->notes );
1091                 free( method );
1092         }
1093 }
1094
1095 /**
1096         @brief Free an osrfApplication
1097         @param name Name of the application (not used).
1098         @param p Void pointer pointing to the osrfApplication.
1099
1100         This function is designed to be installed as a callback for an osrfHash (hence the
1101         unused @a name parameter and the void pointer).
1102 */
1103 static void osrfAppFree( char* name, void* p ) {
1104         osrfApplication* app = p;
1105         if( app ) {
1106                 dlclose( app->handle );
1107                 osrfHashFree( app->methods );
1108                 free( app );
1109         }
1110 }