aboutsummaryrefslogtreecommitdiffstats
path: root/ctl-lib/ctl-lua.c
blob: 2aaaabbd172a6b3b1bd2dc56bf5b260daec325c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
/*
 * Copyright (C) 2018 "IoT.bzh"
 * Author Sebastien Douheret <sebastien@iot.bzh>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package xdsserver

import (
	"fmt"

	"gerrit.automotivelinux.org/gerrit/src/xds/xds-server.git/lib/xsapiv1"
	"github.com/syncthing/syncthing/lib/sync"
)

// Terminals Represent a XDS terminals
type Terminals struct {
	*Context
	terms map[string]*ITERMINAL
}

// Mutex to make add/delete atomic
var tmMutex = sync.NewMutex()

// TerminalsConstructor Create a new instance of Model Terminal
func TerminalsConstructor(ctx *Context) *Terminals {
	return &Terminals{
		Context: ctx,
		terms:   make(map[string]*ITERMINAL),
	}
}

// New Create a new terminal
func (t *Terminals) New(cfg xsapiv1.TerminalConfig, targetID string) (*xsapiv1.TerminalConfig, error) {

	tmMutex.Lock()
	defer tmMutex.Unlock()

	var newT ITERMINAL

	// For now, only SSH term is supported
	switch cfg.Type {
	case xsapiv1.TypeTermSSH:
		newT = NewTermSSH(t.Context, cfg, targetID)
	default:
		return nil, fmt.Errorf("terminal type not set")
	}

	termCfg := newT.GetConfig()

	t.terms[termCfg.ID] = &newT

	termCfg.Status = xsapiv1.StatusTermEnable

	// Notify terminal add
	if err := t.events.Emit(xsapiv1.EVTTargetTerminalAdd, &termCfg, ""); err != nil {
		t.Log.Errorf("WS Emit EVTTargetTerminalAdd : %v", err)
	}

	return &termCfg, nil
}

// Free a specific terminal
func (t *Terminals) Free(id string) (*xsapiv1.TerminalConfig, error) {

	tmMutex.Lock()
	defer tmMutex.Unlock()

	tc := t.Get(id)
	if tc == nil {
		return nil, fmt.Errorf("Unknown id")
	}

	if _, err := (*tc).Close(); err != nil {
		return nil, err
	}

	resTerm := (*tc).GetConfig()

	delete(t.terms, id)

	// Notify terminal state change or add
	if err := t.events.Emit(xsapiv1.EVTTargetTerminalRemove, &resTerm, ""); err != nil {
		t.Log.Errorf("WS Emit EVTTargetTerminalRemove : %v", err)
	}

	return &resTerm, nil
}

// Get returns the terminal config or nil if not existing
func (t *Terminals) Get(id string) *ITERMINAL {
	if id == "" {
		return nil
	}
	tc, exist := t.terms[id]
	if !exist {
		return nil
	}
	return tc
}

// GetConfigArr returns the config of all terminals as an array
func (t *Terminals) GetConfigArr() []xsapiv1.TerminalConfig {
	tmMutex.Lock()
	defer tmMutex.Unlock()

	return t.getConfigArrUnsafe()
}

// getConfigArrUnsafe Same as GetConfigArr without mutex protection
func (t *Terminals) getConfigArrUnsafe() []xsapiv1.TerminalConfig {
	conf := []xsapiv1.TerminalConfig{}
	for _, v := range t.terms {
		conf = append(conf, (*v).GetConfig())
	}
	return conf
}

// Open adds a new terminal
func (t *Terminals) Open(id string, sess *ClientSession) (*xsapiv1.TerminalConfig, error) {
	tc := t.Get(id)
	if tc == nil {
		return nil, fmt.Errorf("Unknown id")
	}

	if sess.IOSocket == nil {
		return nil, fmt.Errorf("Websocket not established")
	}

	term, err := (*tc).Open(sess.IOSocket, sess.ID)

	// Notify term state change
	if errEmit := t.events.Emit(xsapiv1.EVTTargetTerminalStateChange, &term, sess.ID); errEmit != nil {
		t.Log.Errorf("WS Emit EVTTargetTerminalStateChange : %v", errEmit)
	}

	return term, err
}

// Close a specific terminal
func (t *Terminals) Close(id string, sess *ClientSession) (*xsapiv1.TerminalConfig, error) {
	tc := t.Get(id)
	if tc == nil {
		return nil, fmt.Errorf("Unknown id")
	}

	term, err := (*tc).Close()

	// Notify term state change
	if errEmit := t.events.Emit(xsapiv1.EVTTargetTerminalStateChange, &term, sess.ID); errEmit != nil {
		t.Log.Errorf("WS Emit EVTTargetTerminalStateChange : %v", errEmit)
	}

	return term, err
}

// Resize a specific terminal
func (t *Terminals) Resize(id string, cols, rows uint16, sess *ClientSession) (*xsapiv1.TerminalConfig, error) {
	tmMutex.Lock()
	defer tmMutex.Unlock()

	tc := t.Get(id)
	if tc == nil {
		return nil, fmt.Errorf("Unknown id")
	}

	term, err := (*tc).Resize(cols, rows)

	// Notify term state change
	if errEmit := t.events.Emit(xsapiv1.EVTTargetTerminalStateChange, &term, sess.ID); errEmit != nil {
		t.Log.Errorf("WS Emit EVTTargetTerminalStateChange : %v", errEmit)
	}

	return term, err
}

// Signal Send a Signal a specific terminal
func (t *Terminals) Signal(id, sigName string) error {
	tmMutex.Lock()
	defer tmMutex.Unlock()

	tc := t.Get(id)
	if tc == nil {
		return fmt.Errorf("Unknown id")
	}
	return (*tc).Signal(sigName)
}
id='n1100' href='#n1100'>1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
/*
 * Copyright (C) 2016 "IoT.bzh"
 * Author Fulup Ar Foll <fulup@iot.bzh>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ref:
 *  (manual) https://www.lua.org/manual/5.3/manual.html
 *  (lua->C) http://www.troubleshooters.com/codecorn/lua/lua_c_calls_lua.htm#_Anatomy_of_a_Lua_Call
 *  (lua/C Var) http://acamara.es/blog/2012/08/passing-variables-from-lua-5-2-to-c-and-vice-versa/
 *  (Lua/C Lib)https://john.nachtimwald.com/2014/07/12/wrapping-a-c-library-in-lua/
 *  (Lua/C Table) https://gist.github.com/SONIC3D/10388137
 *  (Lua/C Nested table) https://stackoverflow.com/questions/45699144/lua-nested-table-from-lua-to-c
 *  (Lua/C Wrapper) https://stackoverflow.com/questions/45699950/lua-passing-handle-to-function-created-with-newlib
 *
 */

#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <sys/time.h>

#include "ctl-config.h"

#define LUA_FIST_ARG 2  // when using luaL_newlib calllback receive libtable as 1st arg
#define LUA_MSG_MAX_LENGTH 512
#define JSON_ERROR (json_object*)-1


static  lua_State* luaState;

#ifndef CTX_MAGIC
 static int CTX_MAGIC;
#endif

#ifndef TIMER_MAGIC
 static int TIMER_MAGIC;
#endif

typedef struct {
    char *name;
    int  count;
    AFB_EventT event;
} LuaAfbEvent;

typedef struct {
    int ctxMagic;
    CtlSourceT *source;
} LuaAfbSourceT;

typedef struct {
  const char *callback;
  json_object *context;
  CtlSourceT *source;
} LuaCbHandleT;



/*
 * Note(Fulup): I fail to use luaL_setmetatable and replaced it with a simple opaque
 * handle while waiting for someone smarter than me to find a better solution
 *  https://stackoverflow.com/questions/45596493/lua-using-lua-newuserdata-from-lua-pcall
 */

STATIC CtlSourceT *LuaSourcePop (lua_State *luaState, int index) {
  LuaAfbSourceT *afbSource;
  luaL_checktype(luaState, index, LUA_TLIGHTUSERDATA);
  afbSource = (LuaAfbSourceT *) lua_touserdata(luaState, index);
  if (afbSource == NULL || afbSource->ctxMagic != CTX_MAGIC) {
      luaL_error(luaState, "(Hoops) Invalid source handle");
      return NULL;
  }
  return afbSource->source;
}

STATIC LuaAfbSourceT *LuaSourcePush (lua_State *luaState, CtlSourceT *source) {
  LuaAfbSourceT *afbSource = (LuaAfbSourceT *)calloc(1, sizeof(LuaAfbSourceT));
  if (!afbSource) {
      AFB_ApiError(source->api, "LuaSourcePush fail to allocate user data context");
      return NULL;
  }
  
  lua_pushlightuserdata(luaState, afbSource);
  afbSource->ctxMagic=CTX_MAGIC;
  afbSource->source= source;
  return afbSource;
}

// Push a json structure on the stack as a LUA table
STATIC int LuaPushArgument (CtlSourceT *source, json_object *argsJ) {

    //AFB_NOTICE("LuaPushArgument argsJ=%s", json_object_get_string(argsJ));

    json_type jtype= json_object_get_type(argsJ);
    switch (jtype) {
        case json_type_object: {
            lua_newtable (luaState);
            json_object_object_foreach (argsJ, key, val) {
                int done = LuaPushArgument (source, val);
                if (done) {
                    lua_setfield(luaState,-2, key);
                }
            }
            break;
        }
        case json_type_array: {
            int length= json_object_array_length(argsJ);
            lua_newtable (luaState);
            for (int idx=0; idx < length; idx ++) {
                json_object *val=json_object_array_get_idx(argsJ, idx);
                LuaPushArgument (source, val);
                lua_seti (luaState,-2, idx);
            }
            break;
        }
        case json_type_int:
            lua_pushinteger(luaState, json_object_get_int(argsJ));
            break;
        case json_type_string:
            lua_pushstring(luaState, json_object_get_string(argsJ));
            break;
        case json_type_boolean:
            lua_pushboolean(luaState, json_object_get_boolean(argsJ));
            break;
        case json_type_double:
            lua_pushnumber(luaState, json_object_get_double(argsJ));
            break;
        case json_type_null:
            AFB_ApiWarning(source->api, "LuaPushArgument: NULL object type %s", json_object_get_string(argsJ));
            return 0;
            break;

        default:
            AFB_ApiError(source->api, "LuaPushArgument: unsupported Json object type %s", json_object_get_string(argsJ));
            return 0;
    }
    return 1;
}

STATIC  json_object *LuaPopOneArg (CtlSourceT *source, lua_State* luaState, int idx);

// Move a table from Internal Lua representation to Json one
// Numeric table are transformed in json array, string one in object
// Mix numeric/string key are not supported
STATIC json_object *LuaTableToJson (CtlSourceT *source, lua_State* luaState, int index) {
    #define LUA_KEY_INDEX -2
    #define LUA_VALUE_INDEX -1

    int idx;
    int tableType;
    json_object *tableJ= NULL;

    lua_pushnil(luaState); // 1st key
    if (index < 0) index--;
    for (idx=1; lua_next(luaState, index) != 0; idx++) {

        // uses 'key' (at index -2) and 'value' (at index -1)
        if (lua_type(luaState,LUA_KEY_INDEX) == LUA_TSTRING) {

            if (!tableJ) {
                tableJ= json_object_new_object();
                tableType=LUA_TSTRING;
            } else if (tableType != LUA_TSTRING){
                AFB_ApiError(source->api, "MIX Lua Table with key string/numeric not supported");
                return NULL;
            }

            const char *key= lua_tostring(luaState, LUA_KEY_INDEX);
            json_object *argJ= LuaPopOneArg(source, luaState, LUA_VALUE_INDEX);
            json_object_object_add(tableJ, key, argJ);

        } else {
            if (!tableJ) {
                tableJ= json_object_new_array();
                tableType=LUA_TNUMBER;
            } else if(tableType != LUA_TNUMBER) {
                AFB_ApiError(source->api, "MIX Lua Table with key numeric/string not supported");
                return NULL;
            }

            json_object *argJ= LuaPopOneArg(source, luaState, LUA_VALUE_INDEX);
            json_object_array_add(tableJ, argJ);
        }


        lua_pop(luaState, 1); // removes 'value'; keeps 'key' for next iteration
    }

    // Query is empty free empty json object
    if (idx == 1) {
        json_object_put(tableJ);
        return NULL;
    }
    return tableJ;
}

STATIC  json_object *LuaPopOneArg (CtlSourceT *source, lua_State* luaState, int idx) {
    json_object *value=NULL;

    int luaType = lua_type(luaState, idx);
    switch(luaType)  {
        case LUA_TNUMBER: {
            lua_Number number= lua_tonumber(luaState, idx);;
            int nombre = (int)number; // evil trick to determine wether n fits in an integer. (stolen from ltcl.c)
            if (number == nombre) {
                value= json_object_new_int((int)number);
            } else {
                value= json_object_new_double(number);
            }
            break;
        }
        case LUA_TBOOLEAN:
            value=  json_object_new_boolean(lua_toboolean(luaState, idx));
            break;
        case LUA_TSTRING:
           value=  json_object_new_string(lua_tostring(luaState, idx));
            break;
        case LUA_TTABLE:
            value= LuaTableToJson(source, luaState, idx);
            break;
        case LUA_TNIL:
            value=json_object_new_string("nil") ;
            break;
        case LUA_TUSERDATA:
            value=json_object_new_int64((int64_t)lua_touserdata(luaState, idx)); // store userdata as int !!!
            break;

        default:
            AFB_ApiNotice (source->api, "LuaPopOneArg: script returned Unknown/Unsupported idx=%d type:%d/%s", idx, luaType, lua_typename(luaState, luaType));
            value=NULL;
    }

    return value;
}

static json_object *LuaPopArgs (CtlSourceT *source, lua_State* luaState, int start) {
    json_object *responseJ;

    int stop = lua_gettop(luaState);
    if(stop-start <0) return NULL;

    // start at 2 because we are using a function array lib
    if (start == stop) {
        responseJ=LuaPopOneArg (source, luaState, start);
    } else {
        // loop on remaining return arguments
        responseJ= json_object_new_array();
        for (int idx=start; idx <= stop; idx++) {
            json_object *argJ=LuaPopOneArg (source, luaState, idx);
            if (!argJ) goto OnErrorExit;
            json_object_array_add(responseJ, argJ);
       }
    }

    return responseJ;

  OnErrorExit:
    return NULL;
}



 /*
  * 'level' is defined by syslog standard:
  *      EMERGENCY         0        System is unusable
  *      ALERT             1        Action must be taken immediately
  *      CRITICAL          2        Critical conditions
  *      ERROR             3        Error conditions
  *      WARNING           4        Warning conditions
  *      NOTICE            5        Normal but significant condition
  *      INFO              6        Informational
  *      DEBUG             7        Debug-level messages
  */
typedef enum {
    AFB_MSG_INFO=6,
    AFB_MSG_WARNING=4,
    AFB_MSG_NOTICE=5,
    AFB_MSG_DEBUG=7,
    AFB_MSG_ERROR=3,
} LuaAfbLevelT;

STATIC int LuaFormatMessage(lua_State* luaState, LuaAfbLevelT level) {
    char *message;
    
    CtlSourceT *source= LuaSourcePop(luaState, LUA_FIST_ARG);
    if (!source) goto OnErrorExit;
\
    
    // if log level low then silently ignore message
#ifdef AFB_BINDING_PREV3
    if(source->api->verbosity < level) return 0; 
#else
    if(afb_get_verbosity() < level) return 0; 
#endif
    
    json_object *responseJ= LuaPopArgs(source, luaState, LUA_FIST_ARG+1);

    if (!responseJ) {
        luaL_error(luaState,"LuaFormatMessage empty message");
        goto OnErrorExit;
    }

    // if we have only on argument just return the value.
    if (json_object_get_type(responseJ)!=json_type_array || json_object_array_length(responseJ) <2) {
        message= (char*)json_object_get_string(responseJ);
        goto PrintMessage;
    }

    // extract format and push all other parameter on the stack
    message = alloca (LUA_MSG_MAX_LENGTH);
    const char *format = json_object_get_string(json_object_array_get_idx(responseJ, 0));

    int arrayIdx=1;
    int targetIdx=0;

    for (int idx=0; format[idx] !='\0'; idx++) {

        if (format[idx]=='%' && format[idx] !='\0') {
            json_object *slotJ= json_object_array_get_idx(responseJ, arrayIdx);
            //if (slotJ) AFB_NOTICE("**** idx=%d slotJ=%s", arrayIdx, json_object_get_string(slotJ));


            switch (format[++idx]) {
                case 'd':
                    if (slotJ) targetIdx += snprintf (&message[targetIdx], LUA_MSG_MAX_LENGTH-targetIdx,"%d", json_object_get_int(slotJ));
                    else  targetIdx += snprintf (&message[targetIdx], LUA_MSG_MAX_LENGTH-targetIdx,"nil");
                    arrayIdx++;
                    break;
                case 'f':
                    if (slotJ) targetIdx += snprintf (&message[targetIdx], LUA_MSG_MAX_LENGTH-targetIdx,"%f", json_object_get_double(slotJ));
                    else  targetIdx += snprintf (&message[targetIdx], LUA_MSG_MAX_LENGTH-targetIdx,"nil");
                    arrayIdx++;
                    break;

                case'%':
                    message[targetIdx]='%';
                    targetIdx++;
                    break;
                    
                case 'A':
                    targetIdx += snprintf (&message[targetIdx], LUA_MSG_MAX_LENGTH-targetIdx,"level: %s", source->label);
                    break;

                case 's':
                default:
                    if (slotJ) targetIdx += snprintf (&message[targetIdx], LUA_MSG_MAX_LENGTH-targetIdx,"%s", json_object_get_string(slotJ));
                    else  targetIdx += snprintf (&message[targetIdx], LUA_MSG_MAX_LENGTH-targetIdx,"nil");
                    arrayIdx++;
                }

        } else {
            if (targetIdx >= LUA_MSG_MAX_LENGTH) {
                AFB_ApiWarning (source->api, "LuaFormatMessage: message[%s] owerverflow LUA_MSG_MAX_LENGTH=%d", format, LUA_MSG_MAX_LENGTH);
                targetIdx --; // move backward for EOL
                break;
            } else {
                message[targetIdx++] = format[idx];
            }
        }
    }
    message[targetIdx]='\0';

PrintMessage:
    // TBD: __file__ and __line__ should match LUA source code                
    AFB_ApiVerbose(source->api, level,__FILE__,__LINE__,source->label, message);
    return 0;  // nothing return to lua

  OnErrorExit: // on argument to return (the error message)
    return 1;
}


STATIC int LuaPrintInfo(lua_State* luaState) {
    int err=LuaFormatMessage (luaState, AFB_MSG_INFO);
    return err;
}

STATIC int LuaPrintError(lua_State* luaState) {
    int err=LuaFormatMessage (luaState, AFB_MSG_DEBUG);
    return err; // no value return
}

STATIC int LuaPrintWarning(lua_State* luaState) {
    int err=LuaFormatMessage (luaState, AFB_MSG_WARNING);
    return err;
}

STATIC int LuaPrintNotice(lua_State* luaState) {
    int err=LuaFormatMessage (luaState, AFB_MSG_NOTICE);
    return err;
}

STATIC int LuaPrintDebug(lua_State* luaState) {
    int err=LuaFormatMessage (luaState, AFB_MSG_ERROR);
    return err;
}

STATIC int LuaAfbSuccess(lua_State* luaState) {
    CtlSourceT *source= LuaSourcePop(luaState, LUA_FIST_ARG);
    if (!source) goto OnErrorExit;

    // ignore context argument
    json_object *responseJ= LuaPopArgs(source, luaState, LUA_FIST_ARG+1);
    if (responseJ == JSON_ERROR) return 1;

    AFB_ReqSucess (source->request, responseJ, NULL);

    return 0;

 OnErrorExit:
        lua_error(luaState);
        return 1;
}

STATIC int LuaAfbFail(lua_State* luaState) {
    CtlSourceT *source= LuaSourcePop(luaState, LUA_FIST_ARG);
    if (!source) goto OnErrorExit;

    json_object *responseJ= LuaPopArgs(source, luaState, LUA_FIST_ARG+1);
    if (responseJ == JSON_ERROR) return 1;

    AFB_ReqFail(source->request, source->label, json_object_get_string(responseJ));

    return 0;

 OnErrorExit:
        lua_error(luaState);
        return 1;
}

STATIC void LuaAfbServiceCB(void *handle, int iserror, struct json_object *responseJ, AFB_ApiT apiHandle) {
    LuaCbHandleT *handleCb= (LuaCbHandleT*)handle;
    int count=1;

    lua_getglobal(luaState, handleCb->callback);

    // push error status & response
    lua_pushboolean(luaState, iserror);
    count+= LuaPushArgument(handleCb->source, responseJ);
    count+= LuaPushArgument(handleCb->source, handleCb->context);

    int err=lua_pcall(luaState, count, LUA_MULTRET, 0);
    if (err) {
        AFB_ApiError(apiHandle, "LUA-SERICE-CB:FAIL response=%s err=%s", json_object_get_string(responseJ), lua_tostring(luaState,-1) );
    }

    free (handleCb);
}


STATIC int LuaAfbService(lua_State* luaState) {
    int count = lua_gettop(luaState);

    CtlSourceT *source= LuaSourcePop(luaState, LUA_FIST_ARG);
    if (!source) {
        lua_pushliteral (luaState, "LuaAfbService-Fail Invalid request handle");
        goto OnErrorExit;
    }
    
    // note: argument start at 2 because of AFB: table
    if (count <6 || !lua_isstring(luaState, 3) || !lua_isstring(luaState, 4) || !lua_istable(luaState, 5) || !lua_isstring(luaState, 6)) {
        lua_pushliteral (luaState, "ERROR: syntax AFB:service(api, verb, {[Lua Table]})");
        goto OnErrorExit;
    }

    // get api/verb+query
    const char *api = lua_tostring(luaState,3);
    const char *verb= lua_tostring(luaState,4);
    json_object *queryJ= LuaTableToJson(source, luaState, 5);
    if (queryJ == JSON_ERROR) return 1;

    LuaCbHandleT *handleCb = calloc (1, sizeof(LuaCbHandleT));
    handleCb->callback= lua_tostring(luaState, 6);
    handleCb->context =  LuaPopArgs(source, luaState, 7);

    AFB_ServiceCall(source->api, api, verb, queryJ, LuaAfbServiceCB, handleCb);

    return 0; // no value return

  OnErrorExit:
        lua_error(luaState);
        return 1;
}

STATIC int LuaAfbServiceSync(lua_State* luaState) {
    int count = lua_gettop(luaState);
    json_object *responseJ;

    CtlSourceT *source= LuaSourcePop(luaState, LUA_FIST_ARG);
    if (!source) {
        lua_pushliteral (luaState, "LuaAfbServiceSync-Fail Invalid request handle");
        goto OnErrorExit;
    }
    
    // note: argument start at 2 because of AFB: table
    if (count <4 || !lua_isstring(luaState, 3) || !lua_isstring(luaState, 4) || !lua_istable(luaState, 5)) {
        lua_pushliteral (luaState, "ERROR: syntax AFB:servsync(api, verb, {[Lua Table]})");
        goto OnErrorExit;
    }

    
    // get source/api/verb+query
    const char *api = lua_tostring(luaState,LUA_FIST_ARG+2);
    const char *verb= lua_tostring(luaState,LUA_FIST_ARG+3);
    json_object *queryJ= LuaTableToJson(source, luaState, LUA_FIST_ARG+4);

    int iserror=AFB_ServiceSync(source->api, api, verb, queryJ, &responseJ);

    // push error status & response
    count=1; lua_pushboolean(luaState, iserror);
    count+= LuaPushArgument(source, responseJ);

    return count; // return count values

  OnErrorExit:
        lua_error(luaState);
        return 1;
}

STATIC int LuaAfbEventPush(lua_State* luaState) {
    LuaAfbEvent *afbevt;

    CtlSourceT *source= LuaSourcePop(luaState, LUA_FIST_ARG);
    if (!source) {
        lua_pushliteral (luaState, "LuaAfbEventSubscribe-Fail Invalid request handle");
        goto OnErrorExit;
    }
    
    // if no private event handle then use default binding event
    if (!lua_islightuserdata(luaState, LUA_FIST_ARG+1)) {
        lua_pushliteral (luaState, "LuaAfbMakePush-Fail missing event handle");
        goto OnErrorExit;
    }
    
    afbevt = (LuaAfbEvent*) lua_touserdata(luaState, LUA_FIST_ARG+1);
    
    if (!AFB_EventIsValid(afbevt->event)) {
        lua_pushliteral (luaState, "LuaAfbMakePush-Fail invalid event");
        goto OnErrorExit;
    }

    json_object *ctlEventJ= LuaTableToJson(source, luaState, LUA_FIST_ARG+2);
    if (!ctlEventJ) {
        lua_pushliteral (luaState, "LuaAfbEventPush-Syntax is AFB:signal ([evtHandle], {lua table})");
        goto OnErrorExit;
    }

    int done = AFB_EventPush(afbevt->event, ctlEventJ);
    if (!done) {
        lua_pushliteral (luaState, "LuaAfbEventPush-Fail No Subscriber to event");
        AFB_ApiError(source->api, "LuaAfbEventPush-Fail name subscriber event=%s count=%d", afbevt->name, afbevt->count);
        goto OnErrorExit;
    }
    afbevt->count++;
    return 0;

OnErrorExit:
        lua_error(luaState);
        return 1;
}

STATIC int LuaAfbEventSubscribe(lua_State* luaState) {
    LuaAfbEvent *afbevt;

    CtlSourceT *source= LuaSourcePop(luaState, LUA_FIST_ARG);
    if (!source) {
        lua_pushliteral (luaState, "LuaAfbEventSubscribe-Fail Invalid request handle");
        goto OnErrorExit;
    }

    // if no private event handle then use default binding event
    if (!lua_islightuserdata(luaState, LUA_FIST_ARG+1)) {
        lua_pushliteral (luaState, "LuaAfbMakePush-Fail missing event handle");
        goto OnErrorExit;
    }
    
    afbevt = (LuaAfbEvent*) lua_touserdata(luaState, LUA_FIST_ARG+1);

    if (!AFB_EventIsValid(afbevt->event)) {
        lua_pushliteral (luaState, "LuaAfbMakePush-Fail invalid event handle");
        goto OnErrorExit;
    }

    int err = AFB_ReqSubscribe(source->request, afbevt->event);
    if (err) {
        lua_pushliteral (luaState, "LuaAfbEventSubscribe-Fail No Subscriber to event");
        AFB_ApiError(source->api, "LuaAfbEventPush-Fail name subscriber event=%s count=%d", afbevt->name, afbevt->count);
        goto OnErrorExit;
    }
    afbevt->count++;
    return 0;

  OnErrorExit:
        lua_error(luaState);
        return 1;
}

STATIC int LuaAfbEventMake(lua_State* luaState) {
    int count = lua_gettop(luaState);
    LuaAfbEvent *afbevt=calloc(1,sizeof(LuaAfbEvent));

    CtlSourceT *source= LuaSourcePop(luaState, LUA_FIST_ARG);
    if (!source) {
        lua_pushliteral (luaState, "LuaAfbEventMake-Fail Invalid request handle");
        goto OnErrorExit;
    }

    if (count != LUA_FIST_ARG+1 || !lua_isstring(luaState, LUA_FIST_ARG+1)) {
        lua_pushliteral (luaState, "LuaAfbEventMake-Syntax is evtHandle= AFB:event ('myEventName')");
        goto OnErrorExit;
    }

    // event name should be the only argument
    afbevt->name= strdup (lua_tostring(luaState,LUA_FIST_ARG+1));

    // create a new binder event
    afbevt->event = AFB_EventMake(source->api, afbevt->name);
    if (!AFB_EventIsValid(afbevt->event)) {
        AFB_ApiError (source->api,"Fail to CreateEvent evtname=%s",  afbevt->name);
        lua_pushliteral (luaState, "LuaAfbEventMake-Fail to Create Binder event");
        goto OnErrorExit;
    }

    // push event handler as a LUA opaque handle
    lua_pushlightuserdata(luaState, afbevt);
    return 1;

  OnErrorExit:
        lua_error(luaState);
        return 1;
}

STATIC int LuaAfbGetLabel (lua_State* luaState) {

    CtlSourceT *source= LuaSourcePop(luaState, LUA_FIST_ARG);
    if (!source) {
        lua_pushliteral (luaState, "LuaAfbEventSubscribe-Fail Invalid request handle");
        goto OnErrorExit;
    }
    
    // extract and return afbSource from timer handle
    lua_pushstring(luaState, source->label);

    return 1; // return argument

OnErrorExit:
    return 0;
}

// Function call from LUA when lua2c plugin L2C is used
PUBLIC int Lua2cWrapper(void* luaHandle, char *funcname, Lua2cFunctionT callback) {
    lua_State* luaState = (lua_State*)luaHandle;
    json_object *responseJ=NULL;
    
    CtlSourceT *source= LuaSourcePop(luaState, LUA_FIST_ARG);

    json_object *argsJ= LuaPopArgs(source, luaState, LUA_FIST_ARG+1);
    int err= (*callback) (source, argsJ, &responseJ);

    // push error code and eventual response to LUA
    int count=1;
    lua_pushinteger (luaState, err);
    if (!responseJ) count += LuaPushArgument (source, responseJ);
    
    return count;
}

// Call a Lua function from a control action
PUBLIC int LuaCallFunc (CtlSourceT *source, CtlActionT *action, json_object *queryJ) {

    int err, count;

    json_object* argsJ  = action->argsJ;
    const char*  func   = action->exec.lua.funcname;

    // load function (should exist in CONTROL_PATH_LUA
    lua_getglobal(luaState, func);

    // push source on the stack
    count=1;
    // Push AFB client context on the stack
    LuaAfbSourceT *afbSource= LuaSourcePush(luaState, source);
    if (!afbSource) goto OnErrorExit;

    // push argsJ on the stack
    if (!argsJ) {
        lua_pushnil(luaState); count++;
    } else {
        count+= LuaPushArgument (source, argsJ);
    }

    // push queryJ on the stack
    if (!queryJ) {
        lua_pushnil(luaState);
        count++;
    } else {
        count+= LuaPushArgument (source, queryJ);
    }

    // effectively exec LUA script code
    err=lua_pcall(luaState, count, 1, 0);
    if (err)  {
        AFB_ApiError(source->api, "LuaCallFunc Fail calling %s error=%s", func, lua_tostring(luaState,-1));
        goto OnErrorExit;
    }

    // return LUA script value
    int rc= (int)lua_tointeger(luaState, -1);
    return rc;

  OnErrorExit:
    return -1;
}


// Execute LUA code from received API request
STATIC void LuaDoAction (LuaDoActionT action, AFB_ReqT request) {

    int err, count=0;
    CtlSourceT *source = alloca(sizeof(CtlSourceT));
    source->request = request;

    json_object* queryJ = AFB_ReqJson(request);
    

    switch (action) {

        case LUA_DOSTRING: {
            const char *script = json_object_get_string(queryJ);
            err=luaL_loadstring(luaState, script);
            if (err) {
                AFB_ApiError(source->api, "LUA-DO-COMPILE:FAIL String=%s err=%s", script, lua_tostring(luaState,-1) );
                goto OnErrorExit;
            }
            // Push AFB client context on the stack
            LuaAfbSourceT *afbSource= LuaSourcePush(luaState, source);
            if (!afbSource) goto OnErrorExit;

            break;
        }

        case LUA_DOCALL: {
            const char *func;
            json_object *argsJ=NULL;

            err= wrap_json_unpack (queryJ, "{s:s, s?o !}", "target", &func, "args", &argsJ);
            if (err) {
                AFB_ApiError(source->api, "LUA-DOCALL-SYNTAX missing target|args query=%s", json_object_get_string(queryJ));
                goto OnErrorExit;
            }

            // load function (should exist in CONTROL_PATH_LUA
            lua_getglobal(luaState, func);

            // Push AFB client context on the stack
            LuaAfbSourceT *afbSource= LuaSourcePush(luaState, source);
            if (!afbSource) goto OnErrorExit;

            // push query on the stack
            if (!argsJ) {
                lua_pushnil(luaState);
                count++;
            } else {
                count+= LuaPushArgument (source, argsJ);
            }

            break;
        }

        case LUA_DOSCRIPT: {   // Fulup need to fix argument passing
            char *filename; char*fullpath;
            char luaScriptPath[CONTROL_MAXPATH_LEN];
            int index;

            // scan luascript search path once
            static json_object *luaScriptPathJ =NULL;

            // extract value from query
            const char *target=NULL,*func=NULL;
            json_object *argsJ=NULL;
            err= wrap_json_unpack (queryJ, "{s:s,s?s,s?s,s?o !}","target", &target,"path",&luaScriptPathJ,"function",&func,"args",&argsJ);
            if (err) {
                AFB_ApiError(source->api, "LUA-DOSCRIPT-SYNTAX:missing target|[path]|[function]|[args] query=%s", json_object_get_string(queryJ));
                goto OnErrorExit;
            }

            // search for filename=script in CONTROL_LUA_PATH
            if (!luaScriptPathJ)  {
                strncpy(luaScriptPath,CONTROL_DOSCRIPT_PRE, sizeof(luaScriptPath));
                strncat(luaScriptPath,"-", sizeof(luaScriptPath));
                strncat(luaScriptPath,target, sizeof(luaScriptPath));
                luaScriptPathJ= ScanForConfig(CONTROL_LUA_PATH , CTL_SCAN_RECURSIVE,luaScriptPath,".lua");
            }
            for (index=0; index < json_object_array_length(luaScriptPathJ); index++) {
                json_object *entryJ=json_object_array_get_idx(luaScriptPathJ, index);

                err= wrap_json_unpack (entryJ, "{s:s, s:s !}", "fullpath",  &fullpath,"filename", &filename);
                if (err) {
                    AFB_ApiError(source->api, "LUA-DOSCRIPT-SCAN:HOOPs invalid config file path = %s", json_object_get_string(entryJ));
                    goto OnErrorExit;
                }

                if (index > 0) AFB_ApiWarning(source->api, "LUA-DOSCRIPT-SCAN:Ignore second script=%s path=%s", filename, fullpath);
                else {
                    strncpy (luaScriptPath, fullpath, sizeof(luaScriptPath));
                    strncat (luaScriptPath, "/", sizeof(luaScriptPath));
                    strncat (luaScriptPath, filename, sizeof(luaScriptPath));
                }
            }

            err= luaL_loadfile(luaState, luaScriptPath);
            if (err) {
                AFB_ApiError(source->api, "LUA-DOSCRIPT HOOPs Error in LUA loading scripts=%s err=%s", luaScriptPath, lua_tostring(luaState,-1));
                goto OnErrorExit;
            }

            // script was loaded we need to parse to make it executable
            err=lua_pcall(luaState, 0, 0, 0);
            if (err) {
                AFB_ApiError(source->api, "LUA-DOSCRIPT:FAIL to load %s", luaScriptPath);
                goto OnErrorExit;
            }

            // if no func name given try to deduct from filename
            if (!func && (func=(char*)GetMidleName(filename))!=NULL) {
                strncpy(luaScriptPath,"_", sizeof(luaScriptPath));
                strncat(luaScriptPath,func, sizeof(luaScriptPath));
                func=luaScriptPath;
            }
            if (!func) {
                AFB_ApiError(source->api, "LUA-DOSCRIPT:FAIL to deduct funcname from %s", filename);
                goto OnErrorExit;
            }

            // load function (should exist in CONTROL_PATH_LUA
            lua_getglobal(luaState, func);

            // Push AFB client context on the stack
            LuaAfbSourceT *afbSource= LuaSourcePush(luaState, source);
            if (!afbSource) goto OnErrorExit;

            // push function arguments
            if (!argsJ) {
                lua_pushnil(luaState);
                count++;
            } else {
                count+= LuaPushArgument(source, argsJ);
            }

            break;
        }

        default:
            AFB_ApiError(source->api, "LUA-DOSCRIPT-ACTION unknown query=%s", json_object_get_string(queryJ));
            goto OnErrorExit;
    }

    // effectively exec LUA code (afb_reply/fail done later from callback)
    err=lua_pcall(luaState, count+1, 0, 0);
    if (err) {
        AFB_ApiError(source->api, "LUA-DO-EXEC:FAIL query=%s err=%s", json_object_get_string(queryJ), lua_tostring(luaState,-1));
        goto OnErrorExit;
    }
    return;

 OnErrorExit:
    AFB_ReqFail(request,"LUA:ERROR", lua_tostring(luaState,-1));
    return;
}

PUBLIC void ctlapi_execlua (AFB_ReqT request) {
    LuaDoAction (LUA_DOSTRING, request);
}

PUBLIC void ctlapi_request (AFB_ReqT request) {
    LuaDoAction (LUA_DOCALL, request);
}

PUBLIC void ctlapi_debuglua (AFB_ReqT request) {
    LuaDoAction (LUA_DOSCRIPT, request);
}


STATIC TimerHandleT *LuaTimerPop (lua_State *luaState, int index) {
  TimerHandleT *timerHandle;
  
  luaL_checktype(luaState, index, LUA_TLIGHTUSERDATA);
  timerHandle = (TimerHandleT *) lua_touserdata(luaState, index);
  
  if (timerHandle == NULL && timerHandle->magic != TIMER_MAGIC) {
      luaL_error(luaState, "Invalid source handle");
      fprintf(stderr, "LuaSourcePop error retrieving afbSource");
      return NULL;
  }
  return timerHandle;
}

STATIC int LuaTimerClear (lua_State* luaState) {

    // retrieve useful information opaque handle
    TimerHandleT *timerHandle = LuaTimerPop(luaState, LUA_FIST_ARG);
    if (!timerHandle) goto OnErrorExit;
    LuaCbHandleT *luaCbHandle = (LuaCbHandleT*) timerHandle->context;

    AFB_ApiNotice (luaCbHandle->source->api,"LuaTimerClear timer=%s", timerHandle->label);
    TimerEvtStop(timerHandle);

    return 0; //happy end

OnErrorExit:
    return 1;
}
STATIC int LuaTimerGet (lua_State* luaState) {

    // retrieve useful information opaque handle
    TimerHandleT *timerHandle = LuaTimerPop(luaState, LUA_FIST_ARG);
    if (!timerHandle) goto OnErrorExit;
    LuaCbHandleT *luaCbHandle = (LuaCbHandleT*) timerHandle->context;
        
    // create response as a JSON object
    json_object *responseJ= json_object_new_object();
    json_object_object_add(responseJ,"label", json_object_new_string(timerHandle->label));
    json_object_object_add(responseJ,"delay", json_object_new_int(timerHandle->delay));
    json_object_object_add(responseJ,"count", json_object_new_int(timerHandle->count));

    // return JSON object as Lua table
    int count=LuaPushArgument(luaCbHandle->source, responseJ);

    // free json object
    json_object_put(responseJ);

    return count; // return argument

OnErrorExit:
    return 0;
}

// Timer Callback

// Set timer
STATIC int LuaTimerSetCB (void *handle) {
    LuaCbHandleT *LuaCbHandle = (LuaCbHandleT*) handle;
    int count;

    // push timer handle and user context on Lua stack
    lua_getglobal(luaState, LuaCbHandle->callback);

    count=1;
    // Push AFB client context on the stack
    LuaAfbSourceT *afbSource= LuaSourcePush(luaState, LuaCbHandle->source);
    if (!afbSource) goto OnErrorExit;

    // Push user Context
    count+= LuaPushArgument(LuaCbHandle->source, LuaCbHandle->context);

    int err=lua_pcall(luaState, count, LUA_MULTRET, 0);
    if (err) {
        printf ("LUA-TIMER-CB:FAIL response=%s err=%s\n", json_object_get_string(LuaCbHandle->context), lua_tostring(luaState,-1));
        AFB_ApiError (LuaCbHandle->source->api,"LUA-TIMER-CB:FAIL response=%s err=%s", json_object_get_string(LuaCbHandle->context), lua_tostring(luaState,-1));
        goto OnErrorExit;
    }

    // get return parameter
    if (!lua_isboolean(luaState, -1)) {
        return (lua_toboolean(luaState, -1));
    }

    return 0;  // By default we are happy

 OnErrorExit:
    return 1;  // stop timer
}

// Free Timer context handle
STATIC int LuaTimerCtxFree(void *handle) {
    LuaCbHandleT *LuaCbHandle = (LuaCbHandleT*) handle;
    
    free (LuaCbHandle->source);
    free (LuaCbHandle);
    
    return 0;
}

STATIC int LuaTimerSet(lua_State* luaState) {
    const char *label=NULL, *info=NULL;
    int delay=0, count=0;
    
    // Get source handle
    CtlSourceT *source= LuaSourcePop(luaState, LUA_FIST_ARG);
    if (!source) goto OnErrorExit;

    json_object *timerJ = LuaPopOneArg(source, luaState, LUA_FIST_ARG+1);
    const char *callback = lua_tostring(luaState, LUA_FIST_ARG + 2);
    json_object *contextJ = LuaPopOneArg(source, luaState, LUA_FIST_ARG + 3);

    if (lua_gettop(luaState) != LUA_FIST_ARG+3 || !timerJ || !callback || !contextJ) {
        lua_pushliteral(luaState, "LuaTimerSet-Syntax timerset (source, timerT, 'callback', contextT)");
        goto OnErrorExit;
    }

    int err = wrap_json_unpack(timerJ, "{ss, s?s si, si !}", "label", &label, "info", &info, "delay", &delay, "count", &count);
    if (err) {
        lua_pushliteral(luaState, "LuaTimerSet-Syntax timerT={label:xxx delay:ms, count:xx}");
        goto OnErrorExit;
    }

    // Allocate handle to store context and callback
    LuaCbHandleT *handleCb = calloc (1, sizeof(LuaCbHandleT));
    handleCb->callback= callback;
    handleCb->context = contextJ;
    handleCb->source  = malloc(sizeof(CtlSourceT));
    memcpy (handleCb->source, source, sizeof(CtlSourceT));  // Fulup need to be free when timer is done
        
    // everything look fine create timer structure
    TimerHandleT *timerHandle = malloc (sizeof (TimerHandleT));
    timerHandle->magic= TIMER_MAGIC;
    timerHandle->delay=delay;
    timerHandle->count=count;
    timerHandle->label=label;
    timerHandle->freeCB=LuaTimerCtxFree;

    // fire timer
    TimerEvtStart (source->api, timerHandle, LuaTimerSetCB, handleCb);
    
    // Fulup finir les timers avec handle

    // return empty error code plus timer handle
    lua_pushnil(luaState);
    lua_pushlightuserdata(luaState, timerHandle);
    return 2;  

OnErrorExit:
    lua_error(luaState);
    return 1; // return error code
}

// Register a new L2c list of LUA user plugin commands
PUBLIC void LuaL2cNewLib(const char *label, luaL_Reg *l2cFunc, int count) {
    // luaL_newlib(luaState, l2cFunc); macro does not work with pointer :(
    luaL_checkversion(luaState);
    lua_createtable(luaState, 0, count+1);
    luaL_setfuncs(luaState,l2cFunc,0);
    lua_setglobal(luaState, label);
}

static const luaL_Reg afbFunction[] = {
    {"timerclear", LuaTimerClear},
    {"timerget"  , LuaTimerGet},
    {"timerset"  , LuaTimerSet},
    {"notice"    , LuaPrintNotice},
    {"info"      , LuaPrintInfo},
    {"warning"   , LuaPrintWarning},
    {"debug"     , LuaPrintDebug},
    {"error"     , LuaPrintError},
    {"servsync"  , LuaAfbServiceSync},
    {"service"   , LuaAfbService},
    {"success"   , LuaAfbSuccess},
    {"fail"      , LuaAfbFail},
    {"subscribe" , LuaAfbEventSubscribe},
    {"evtmake"   , LuaAfbEventMake},
    {"evtpush"   , LuaAfbEventPush},
    {"getlabel"  , LuaAfbGetLabel},

    {NULL, NULL}  /* sentinel */
};

// Load Lua Interpreter
PUBLIC int LuaConfigLoad (AFB_ApiT apiHandle) {
    static int luaLoaded=0;

    // Lua loads only once
    if (luaLoaded) return 0;
    luaLoaded=1;
    
    // open a new LUA interpretor
    luaState = luaL_newstate();
    if (!luaState)  {
        AFB_ApiError(apiHandle, "LUA_INIT: Fail to open lua interpretor");
        goto OnErrorExit;
    }

    // load auxiliary libraries
    luaL_openlibs(luaState);

    // redirect print to AFB_NOTICE
    luaL_newlib(luaState, afbFunction);
    lua_setglobal(luaState, "AFB");
    
    // initialise static magic for context
    #ifndef CTX_MAGIC
        CTX_MAGIC=CtlConfigMagicNew();
    #endif

    #ifndef TIMER_MAGIC
        TIMER_MAGIC=CtlConfigMagicNew();
    #endif
    
    return 0;
    
 OnErrorExit:
    return 1;
}

// Create Binding Event at Init Exec Time
PUBLIC int LuaConfigExec (AFB_ApiT apiHandle) {
    
    int err, index;

    // search for default policy config file
    char fullprefix[CONTROL_MAXPATH_LEN];
    strncpy (fullprefix, CONTROL_CONFIG_PRE "-", sizeof(fullprefix));
    strncat (fullprefix, GetBinderName(), sizeof(fullprefix));
    strncat (fullprefix, "-", sizeof(fullprefix));

    const char *dirList= getenv("CONTROL_LUA_PATH");
    if (!dirList) dirList=CONTROL_LUA_PATH;

    // special case for no lua even when avaliable 
    if (!strcasecmp ("/dev/null", dirList)) {
        return 0;
    }
    
    json_object *luaScriptPathJ = ScanForConfig(dirList , CTL_SCAN_RECURSIVE, fullprefix, "lua");

    // load+exec any file found in LUA search path
    for (index=0; index < json_object_array_length(luaScriptPathJ); index++) {
        json_object *entryJ=json_object_array_get_idx(luaScriptPathJ, index);

        char *filename; char*fullpath;
        err= wrap_json_unpack (entryJ, "{s:s, s:s !}", "fullpath",  &fullpath,"filename", &filename);
        if (err) {
            AFB_ApiError(apiHandle, "LUA-INIT HOOPs invalid config file path = %s", json_object_get_string(entryJ));
            goto OnErrorExit;
        }

        char filepath[CONTROL_MAXPATH_LEN];
        strncpy(filepath, fullpath, sizeof(filepath));
        strncat(filepath, "/", sizeof(filepath));
        strncat(filepath, filename, sizeof(filepath));
        err= luaL_loadfile(luaState, filepath);
        if (err) {
            AFB_ApiError(apiHandle, "LUA-LOAD HOOPs Error in LUA loading scripts=%s err=%s", filepath, lua_tostring(luaState,-1));
            goto OnErrorExit;
        }

        // exec/compil script
        err = lua_pcall(luaState, 0, 0, 0);
        if (err) {
            AFB_ApiError(apiHandle, "LUA-LOAD HOOPs Error in LUA exec scripts=%s err=%s", filepath, lua_tostring(luaState,-1));
            goto OnErrorExit;
        } else {
            AFB_ApiNotice(apiHandle, "LUA-LOAD '%s'", filepath);            
        }
    }

    // no policy config found remove control API from binder
    if (index == 0)  {
        AFB_ApiWarning (apiHandle, "POLICY-INIT:WARNING (setenv CONTROL_LUA_PATH) No LUA '%s*.lua' in '%s'", fullprefix, dirList);
    }

    AFB_ApiDebug (apiHandle, "Audio control-LUA Init Done");
    return 0;

 OnErrorExit:
    return 1;
}