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