local-def: dispatch some definitions
[src/app-framework-binder.git] / include / local-def.h
1 /*
2    local-def.h -- provide a REST/HTTP interface
3
4    Copyright (C) 2015, Fulup Ar Foll
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20 */
21 #ifndef LOCAL_DEF_H
22 #define LOCAL_DEF_H
23
24 #ifndef _GNU_SOURCE
25   #define _GNU_SOURCE
26 #endif
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <errno.h>
34 #include <termios.h>
35 #include <sys/ioctl.h>
36 #include <sys/signal.h>
37 #include <sys/types.h>
38 #include <time.h>
39 #include <json.h>
40 #include <microhttpd.h>
41 #include <magic.h>
42 #include <setjmp.h>
43 #include <signal.h>
44 #include <uuid/uuid.h>
45
46
47
48 /* other definitions --------------------------------------------------- */
49
50 // Note: because of a bug in libmagic MAGIC_DB NULL should not be used for default
51 #define OPA_INDEX "index.html"
52 #define MAX_ALIAS 10           // max number of aliases
53 #define COOKIE_NAME   "afb-session"
54
55
56 #define DEFLT_CNTX_TIMEOUT  3600   // default Client Connection Timeout
57 #define DEFLT_API_TIMEOUT   0      // default Plugin API Timeout [0=NoLimit for Debug Only]
58 #define DEFLT_API_TIMEOUT   0      // default Plugin API Timeout
59 #define DEFLT_CACHE_TIMEOUT 100000 // default Static File Chache [Client Side Cache 100000~=1day]
60 #define DEFLT_AUTH_TOKEN    NULL   // expect for debug should == NULL
61 #define DEFLT_HTTP_TIMEOUT  15     // Max MibMicroHttp timeout
62 #define AFB_MAX_PLUGINS     20     // Max number of plugins for a given binder
63
64 typedef int BOOL;
65 #ifndef FALSE
66   #define FALSE 0
67 #endif
68 #ifndef TRUE
69   #define TRUE 1
70 #endif
71
72 #define PUBLIC
73 #define STATIC    static
74 #define FAILED    -1
75
76 #define AUDIO_BUFFER "/tmp/buf"
77
78 extern int verbose;  // this is the only global variable
79
80 // Plugin Type
81 typedef enum  {AFB_PLUGIN_JSON=123456789, AFB_PLUGIN_JSCRIPT=987654321,  AFB_PLUGIN_RAW=987123546} AFB_pluginE;
82
83 // prebuild json error are constructed in config.c
84 typedef enum  { AFB_FALSE, AFB_TRUE, AFB_FATAL, AFB_FAIL, AFB_WARNING, AFB_EMPTY, AFB_SUCCESS, AFB_DONE, AFB_UNAUTH} AFB_error;
85
86 extern char *ERROR_LABEL[];
87 #define ERROR_LABEL_DEF {"false", "true", "fatal", "fail", "warning", "empty", "success"}
88
89 #define BANNER "<html><head><title>Application Framework Binder</title></head><body>Application Framework </body></html>"
90 #define JSON_CONTENT  "application/json"
91 #define FORM_CONTENT "multipart/form-data"
92 #define MAX_POST_SIZE  4096   // maximum size for POST data
93 #define CTX_NBCLIENTS   10   // allow a default of 10 authenticated clients
94
95
96 typedef json_object* (*AFB_apiCB)();
97 typedef void (*AFB_freeCtxCB)(void*, void*, char*);
98
99 // Error code are requested through function to manage json usage count
100 typedef struct {
101   int   level;
102   char* label;
103   json_object *json;
104 } AFB_errorT;
105
106 typedef enum  {AFB_POST_NONE=0, AFB_POST_JSON, AFB_POST_FORM, AFB_POST_EMPTY} AFB_PostType;
107 typedef enum  {AFB_MODE_LOCAL=0, AFB_MODE_REMOTE, AFB_MODE_GLOBAL} AFB_Mode;
108
109 // Post Upload File Handle
110 typedef struct {
111    int   fd; 
112    char *path; 
113    int  errcode;
114    json_object* jresp;
115 } AFB_PostCtx;
116
117 typedef  struct {
118     int  len;   // post element size
119     char *data; // post data in raw format
120     AFB_PostType type; // Json type
121 } AFB_PostRequest;
122   
123 // Post handler
124 typedef struct {
125   void*  ctx;               // Application context
126   int    len;               // current len for post
127   int    uid;               // post uid for debug
128   AFB_PostType type;        // JSON or FORM
129   AFB_apiCB  completeCB;    // callback when post is completed
130   char   *privatebuf;       // use internally to keep track or partial buffer
131   struct MHD_PostProcessor *pp; // iterator handle
132 } AFB_PostHandle;
133
134 typedef struct {
135     enum MHD_ValueKind kind; // kind type of the value
136     const char *key;         // key 0-terminated key for the value
137     const char *filename;    // filename of the uploaded file, NULL if not known
138     const char *mimetype;    // content_type mime-type of the data, NULL if not known
139     const char *encoding;    // transfer_encoding encoding of the data, NULL if not known
140     const char *data;        // data pointer to size bytes of data at the specified offset
141     uint64_t   offset;       // offset of data in the overall value
142     size_t     len;          // number of bytes in data available
143 } AFB_PostItem;
144
145 typedef struct {
146   char  path[512];
147   int   fd;
148 } AFB_staticfile;
149
150 typedef struct {
151   char  *url;
152   char  *path;
153   size_t len;
154 } AFB_aliasdir;
155
156 // Command line structure hold cli --command + help text
157 typedef struct {
158   int  val;        // command number within application
159   int  has_arg;    // command number within application
160   char *name;      // command as used in --xxxx cli
161   char *help;      // help text
162 } AFB_options;
163
164 // main config structure
165 typedef struct {
166   char *logname;           // logfile path for info & error log
167   char *console;           // console device name (can be a file or a tty)
168   int  localhostOnly;
169   int   httpdPort;
170   char *ldpaths;           // list of plugins directories
171   char *rootdir;           // base dir for httpd file download
172   char *rootbase;          // Angular HTML5 base URL
173   char *rootapi;           // Base URL for REST APIs
174   char *pidfile;           // where to store pid when running background
175   char *sessiondir;        // where to store mixer session files
176   char *configfile;        // where to store configuration on gateway exit
177   char *setuid;            // downgrade uid to username
178   char *token;             // initial authentication token [default NULL no session]
179   int  cacheTimeout;
180   int  apiTimeout;
181   int  cntxTimeout;        // Client Session Context timeout
182   int  pluginCount;        // loaded plugins count
183   AFB_Mode mode;           // mode of listening
184   AFB_aliasdir *aliasdir;  // alias mapping for icons,apps,...
185 } AFB_config;
186
187 typedef struct {
188      char    *msg;
189      size_t  len;
190 } AFB_redirect_msg;
191
192 // Enum for Session/Token/Authentication middleware
193 typedef enum  {AFB_SESSION_NONE, AFB_SESSION_CREATE, AFB_SESSION_CLOSE, AFB_SESSION_RENEW, AFB_SESSION_CHECK} AFB_sessionE;
194
195 // API definition
196 typedef struct {
197   char *name;
198   AFB_sessionE session;
199   AFB_apiCB callback;
200   char *info;
201 } AFB_restapi;
202
203 // Plugin definition
204 typedef struct {
205   AFB_pluginE type;  
206   char *info;
207   char *prefix;
208   size_t prefixlen;
209   json_object *jtype;
210   AFB_restapi *apis;
211   void *handle;
212   int  ctxCount;
213   AFB_freeCtxCB freeCtxCB;  // callback to free application context [null for standard free]
214 } AFB_plugin;
215
216
217 // User Client Session Context
218 typedef struct {
219   char uuid[37];        // long term authentication of remote client
220   char token[37];       // short term authentication of remote client
221   time_t timeStamp;     // last time token was refresh
222   int   restfull;       // client does not use cookie
223   void **contexts;      // application specific context [one per plugin]]
224   AFB_plugin **plugins; // we need plugins reference to cleanup session outside of call context
225 } AFB_clientCtx;
226
227 // MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "value");
228 typedef struct {
229   const char *uuid;
230   const char *url;
231   char *prefix;              // plugin convivial name
232   char *api;
233   AFB_PostRequest *post;
234   json_object *jresp;
235   void *context;             // Hold Client Context when using session
236   void *handle;              // provide callback and easy access to plugin
237   int  restfull;             // request is resfull [uuid token provided]
238   int  errcode;              // http error code
239   sigjmp_buf checkPluginCall; // context save for timeout set/longjmp
240   AFB_config *config;         // plugin may need access to config
241   struct MHD_Connection *connection;
242   AFB_plugin **plugins;
243 } AFB_request;
244
245
246 typedef struct {
247   AFB_config  *config;   // pointer to current config
248   // List of commands to execute
249   int  killPrevious;
250   int  background;        // run in backround mode
251   int  foreground;        // run in forground mode
252   int  configsave;        // Save config on disk on start
253   char *cacheTimeout;     // http require timeout to be a string
254   void *httpd;            // anonymous structure for httpd handler
255   int  fakemod;           // respond to GET/POST request without interacting with sndboard
256   int  forceexit;         // when autoconfig from script force exit before starting server
257   int  readyfd;           // a #fd to signal when ready to serve
258   AFB_plugin **plugins;   // pointer to REST/API plugins 
259   magic_t  magic;         // Mime type file magic lib
260   sigjmp_buf restartCkpt; // context save for restart set/longjmp
261 } AFB_session;
262
263
264
265 #include "proto-def.h"
266
267 #endif /* LOCAL_DEF_H */