Skip to content

File wsh_shell.c

File List > src > wsh_shell.c

Go to the documentation of this file

  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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#include "wsh_shell.h"

static void WshShell_Stub_ExtClbk(void* pCtx) {
    (void)pCtx;
}

#define WSH_SHELL_USER_IS_AUTH()       (pShell->CurrUser != NULL)
#define WSH_SHELL_TMP_LOGIN_IS_EMPTY() (pShell->TmpAuth.Login[0] == 0)
#define WSH_SHELL_TMP_PASS_IS_EMPTY()  (pShell->TmpAuth.Pass[0] == 0)
#define WSH_SHELL_INTER_CMD_EXISTS()   (pShell->Interact.Handler != NULL)

static void WshShell_InvitationPrint(WshShell_t* pShell) {
    if (!WSH_SHELL_USER_IS_AUTH()) {
        if (WSH_SHELL_TMP_LOGIN_IS_EMPTY()) {
            WSH_SHELL_PRINT_SYS("Login: ");
        } else if (WSH_SHELL_TMP_PASS_IS_EMPTY()) {
            WSH_SHELL_PRINT_SYS("Password: ");
        }

        return;
    }

    WSH_SHELL_PRINT(pShell->PS1);
}

WSH_SHELL_RET_STATE_t WshShell_Init(WshShell_t* pShell, const WshShell_Char_t* pcDevName,
                                    const WshShell_Char_t* pcCustomHeader, WshShellExtCallbacks_t* pExtClbks) {
    WSH_SHELL_ASSERT(pShell && pcDevName);
    if (!pShell || !pcDevName)
        return WSH_SHELL_RET_STATE_ERR_PARAM;

    WSH_SHELL_MEMSET((void*)pShell, 0, sizeof(WshShell_t));

    WshShell_Size_t bufSize = sizeof(pShell->DeviceName);
    WshShell_Size_t len     = WSH_SHELL_STRLEN(pcDevName);
    if (len >= bufSize)
        len = bufSize - 1;

    WSH_SHELL_MEMCPY(pShell->DeviceName, pcDevName, len);
    pShell->DeviceName[len] = '\0';

    pShell->Version = WSH_SHELL_VERSION_STR;

    const WshShell_Size_t numClbks = sizeof(pShell->ExtCallbacks) / sizeof(WshShell_ExtClbk_t);
    WshShell_ExtClbk_t* pClbkArr   = (WshShell_ExtClbk_t*)&pShell->ExtCallbacks;

    if (!pExtClbks) {
        // Fill all with stub
        for (WshShell_Size_t clbk = 0; clbk < numClbks; clbk++) {
            pClbkArr[clbk] = WshShell_Stub_ExtClbk;
        }
    } else {
        // Fill from provided struct
        WshShell_ExtClbk_t* pInputArr = (WshShell_ExtClbk_t*)pExtClbks;
        for (WshShell_Size_t clbk = 0; clbk < numClbks; clbk++) {
            pClbkArr[clbk] = pInputArr[clbk] ? pInputArr[clbk] : WshShell_Stub_ExtClbk;
        }
    }

    const WshShell_Char_t* pBuildType = "release";
#if defined(WSH_SHELL_DEBUG_ENABLE)
    pBuildType = "debug";
#endif

    WSH_SHELL_PRINT("%c", WSH_SHELL_SYM_SOUND);
    WSH_SHELL_PRINT(WSH_SHELL_COLOR_PURPLE);
    WSH_SHELL_PRINT(pcCustomHeader ? pcCustomHeader : WSH_SHELL_HEADER);
    WSH_SHELL_PRINT_SYS("Serial shell service started on %s device\r\n", pShell->DeviceName);
    WSH_SHELL_PRINT_SYS("wsh-shell-v%s (%s), built in %s, at %s, with [%s], on [%s]\r\n", pShell->Version, pBuildType,
                        __DATE__, __TIME__, COMPILER, OS_NAME);
    (void)pBuildType;
    WSH_SHELL_PRINT_SYS(WSH_SHELL_PRESS_ENTER_TO_LOG_IN_STR "\r\n");

    WshShellPromptWait_Attach(&(pShell->PromptWait), WshShellPromptWait_Enter, NULL);

    return WSH_SHELL_RET_STATE_SUCCESS;
}

WshShell_Bool_t WshShell_Auth(WshShell_t* pShell, const WshShell_Char_t* pcLogin, const WshShell_Char_t* pcPass) {
    WSH_SHELL_ASSERT(pShell && pcLogin && pcPass);
    if (!pShell || !pcLogin || !pcPass)
        return false;

    pShell->CurrUser = WshShellUser_FindByCredentials(&(pShell->Users), pcLogin, pcPass);
    if (WSH_SHELL_USER_IS_AUTH()) {
        WshShell_PS1Data_t data = {
            .UserName     = pShell->CurrUser->Login,
            .DevName      = pShell->DeviceName,
            .InterCmdName = WSH_SHELL_INTER_CMD_EXISTS() ? pShell->Interact.CmdName : NULL,
        };
        WshShell_GeneratePS1(pShell->PS1, &data);
        pShell->ExtCallbacks.Auth(NULL);
        WSH_SHELL_PRINT("%c", WSH_SHELL_SYM_SOUND);
    }

    return WSH_SHELL_USER_IS_AUTH();
}

WshShell_Bool_t WshShell_IsAuth(WshShell_t* pShell) {
    WSH_SHELL_ASSERT(pShell);
    if (!pShell)
        return false;

    return (bool)WSH_SHELL_USER_IS_AUTH();
}

void WshShell_DeAuth(WshShell_t* pShell, const WshShell_Char_t* pcReason) {
    WSH_SHELL_ASSERT(pShell && pcReason);
    if (!pShell || !pcReason)
        return;

    pShell->CurrUser = NULL;
    pShell->ExtCallbacks.DeAuth(NULL);
    WshShellHistory_Flush(&(pShell->HistoryIO));

    WSH_SHELL_PRINT("%c", WSH_SHELL_SYM_SOUND);
    WSH_SHELL_PRINT_SYS("Shell deAuthed by `%s`!\r\n", pcReason);
    WSH_SHELL_PRINT_SYS(WSH_SHELL_PRESS_ENTER_TO_LOG_IN_STR "\r\n");

    WshShellPromptWait_Attach(&(pShell->PromptWait), WshShellPromptWait_Enter, NULL);
}

static void WshShell_AuthHandler(WshShell_t* pShell) {
    WshShell_Size_t len = pShell->CommandLine.Len;

    if (WSH_SHELL_TMP_LOGIN_IS_EMPTY()) {
        if (len >= WSH_SHELL_LOGIN_LEN)
            len = WSH_SHELL_LOGIN_LEN - 1;

        WSH_SHELL_MEMCPY(pShell->TmpAuth.Login, pShell->CommandLine.Buff, len);
        pShell->TmpAuth.Login[len] = '\0';
    } else if (WSH_SHELL_TMP_PASS_IS_EMPTY()) {
        if (len >= WSH_SHELL_PASS_LEN)
            len = WSH_SHELL_PASS_LEN - 1;

        WSH_SHELL_MEMCPY(pShell->TmpAuth.Pass, pShell->CommandLine.Buff, len);
        pShell->TmpAuth.Pass[len] = '\0';
    }

    if (!WSH_SHELL_TMP_LOGIN_IS_EMPTY() && !WSH_SHELL_TMP_PASS_IS_EMPTY()) {
        WshShell_Bool_t isAuthOk = WshShell_Auth(pShell, pShell->TmpAuth.Login, pShell->TmpAuth.Pass);

        WSH_SHELL_MEMSET((void*)pShell->TmpAuth.Login, 0, WSH_SHELL_LOGIN_LEN);
        WSH_SHELL_MEMSET((void*)pShell->TmpAuth.Pass, 0, WSH_SHELL_PASS_LEN);

        if (!isAuthOk)
            WSH_SHELL_PRINT("%c", WSH_SHELL_SYM_SOUND);
    }

    WshShellIO_ClearInterBuff(&(pShell->CommandLine));
}

static void WshShell_StringHandler(WshShell_t* pShell) {
    pShell->CommandLine.Buff[pShell->CommandLine.Len] = 0;

    const WshShell_Char_t* pcCmdStr = WshShellStr_TrimString(pShell->CommandLine.Buff, pShell->CommandLine.Len);
    WshShell_Char_t cmdStr[WSH_SHELL_INTR_BUFF_LEN] = {0};
    WSH_SHELL_STRNCPY(cmdStr, pcCmdStr, WSH_SHELL_INTR_BUFF_LEN - 1);

    WshShell_Size_t argc                                      = 0;
    const WshShell_Char_t* pcArgv[WSH_SHELL_CMD_ARGS_MAX_NUM] = {0};

    WshShellStr_ParseToArgcArgv(cmdStr, &argc, pcArgv, WSH_SHELL_CMD_ARGS_MAX_NUM);
    if (argc == 0) {
        if (pShell->CommandLine.Len != 0)
            WshShellIO_ClearInterBuff(&(pShell->CommandLine));

        return;
    }

    WshShellHistory_SaveCmd(&(pShell->HistoryIO), pcCmdStr, WSH_SHELL_STRLEN(pcCmdStr));

    const WshShellCmd_t* pcCmd      = WshShellDefCmd_GetPtr();
    WshShellCmdHandler_t cmdHandler = NULL;

    if (WSH_SHELL_STRNCMP(pcCmd->Name, pcArgv[0], WSH_SHELL_CMD_NAME_LEN) == 0) {
        cmdHandler = pcCmd->Handler;
    } else {
        pcCmd = WshShellCmd_SearchCmd(&(pShell->Commands), pcArgv[0]);
        if (pcCmd == NULL) {
            WSH_SHELL_PRINT_WARN("Command \"%s\" not found!\r\n", pcCmdStr);
        } else if ((pShell->CurrUser->Groups & pcCmd->Groups) != 0) {
            cmdHandler = pcCmd->Handler;
        } else {
            WSH_SHELL_PRINT_ERR("Access denied: no group intersection for command \"%s\" and user \"%s\"!\r\n",
                                pcArgv[0], pShell->CurrUser->Login);

            WshShellIO_ClearInterBuff(&(pShell->CommandLine));
            return;
        }
    }

    const WshShell_Char_t** pDispatchArgv = pcArgv;
    WshShell_Size_t dispatchArgc          = argc;

#if WSH_SHELL_SUBCOMMANDS
    /*
     * Walk the subcommand tree. Each matched level shifts argv by one so the
     * terminal handler receives its own name at argv[0], mirroring top-level
     * dispatch. An unknown non-flag token at a node that has subcommands is
     * reported as an unknown subcommand so users aren't misled into thinking
     * their typo was silently parsed as an option.
     */
    if (cmdHandler && pcCmd) {
        WshShell_Size_t depth = 0;
        while (pcCmd->SubCmdNum > 0 && pcCmd->SubCmds != NULL && dispatchArgc >= 2 &&
               depth < WSH_SHELL_SUBCOMMANDS_MAX_DEPTH) {
            const WshShell_Char_t* pcNext = pDispatchArgv[1];

            /* If the next token is a flag, scan ahead past flags to find the
             * subcommand name. Known flags consume their own arguments (ArgNum).
             * If a subcommand is found beyond the flags, rotate the argv pointer
             * array so the subcommand name lands at position 1 and the flags
             * follow it — the subcommand handler then receives all tokens. */
            if (pcNext && pcNext[0] == '-') {
                WshShell_Size_t scanPos     = 1;
                WshShell_Bool_t subcmdFound = false;
                while (scanPos < dispatchArgc) {
                    const WshShell_Char_t* token = pDispatchArgv[scanPos];
                    if (!token)
                        break;
                    if (token[0] == '-') {
                        const WshShellOption_t* pcOpt = WshShellCmd_FindOptByName(pcCmd, token);
                        scanPos += 1 + (pcOpt ? pcOpt->ArgNum : 0);
                    } else {
                        if (WshShellCmd_SearchSubCmd(pcCmd, token)) {
                            for (WshShell_Size_t i = scanPos; i > 1; i--)
                                pDispatchArgv[i] = pDispatchArgv[i - 1];
                            pDispatchArgv[1] = token;
                            subcmdFound      = true;
                        }
                        break;
                    }
                }
                if (!subcmdFound)
                    break;
                pcNext = pDispatchArgv[1];
            }

            const WshShellCmd_t* pcSub = WshShellCmd_SearchSubCmd(pcCmd, pcNext);
            if (!pcSub) {
                WSH_SHELL_PRINT_WARN("Unknown subcommand: %s %s\r\n", pcCmd->Name, pcNext);
                WshShellIO_ClearInterBuff(&(pShell->CommandLine));
                return;
            }

            if ((pShell->CurrUser->Groups & pcSub->Groups) == 0) {
                WSH_SHELL_PRINT_ERR(
                    "Access denied: no group intersection for subcommand \"%s %s\" and user \"%s\"!\r\n", pcCmd->Name,
                    pcSub->Name, pShell->CurrUser->Login);
                WshShellIO_ClearInterBuff(&(pShell->CommandLine));
                return;
            }

            pcCmd      = pcSub;
            cmdHandler = pcSub->Handler;
            pDispatchArgv++;
            dispatchArgc--;
            depth++;
        }
    }
#endif /* WSH_SHELL_SUBCOMMANDS */

    if (cmdHandler) {
        WSH_SHELL_RET_STATE_t retState = cmdHandler(pcCmd, dispatchArgc, pDispatchArgv, pShell);

        if (retState != WSH_SHELL_RET_STATE_SUCCESS) {
            WSH_SHELL_PRINT_ERR("Command execution: %s\r\n", WshShell_GetRetStateStr(retState));
        } else {
            if (WSH_SHELL_INTER_CMD_EXISTS()) {
                WshShell_PS1Data_t data = {
                    .UserName     = pShell->CurrUser->Login,
                    .DevName      = pShell->DeviceName,
                    .InterCmdName = pShell->Interact.CmdName,
                };
                WshShell_GeneratePS1(pShell->PS1, &data);
            }
        }
    }

    WshShellIO_ClearInterBuff(&(pShell->CommandLine));
    WSH_SHELL_PRINT("\r\n");
}

static void WshShell_StringInteractHandler(WshShell_t* pShell) {
    pShell->CommandLine.Buff[pShell->CommandLine.Len] = 0;
    const WshShell_Char_t* pcCmdStr                   = pShell->CommandLine.Buff;

    WshShellHistory_SaveCmd(&(pShell->HistoryIO), pcCmdStr, WSH_SHELL_STRLEN(pcCmdStr));
    pShell->Interact.Handler(&(pShell->CommandLine));
    WshShellIO_ClearInterBuff(&(pShell->CommandLine));
}

static void WshShell_ExitInteractive(WshShell_t* pShell) {
    WshShellInteract_Flush(&(pShell->Interact));
    WshShell_PS1Data_t data = {
        .UserName     = pShell->CurrUser->Login,
        .DevName      = pShell->DeviceName,
        .InterCmdName = NULL,
    };
    WshShell_GeneratePS1(pShell->PS1, &data);
}

static void WshShell_SymbolHandler(WshShell_t* pShell, const WshShell_Char_t symbol) {
    switch (symbol) {
        case WSH_SHELL_SYM_CANCEL:
            WSH_SHELL_PRINT("^C");
            if (WSH_SHELL_INTER_CMD_EXISTS())
                WshShell_ExitInteractive(pShell);
            WshShellIO_ClearInterBuff(&(pShell->CommandLine));
            WSH_SHELL_PRINT(WSH_SHELL_END_LINE);
            WshShell_InvitationPrint(pShell);
            break;

        case WSH_SHELL_SYM_EXIT:
            if (WSH_SHELL_INTER_CMD_EXISTS()) {
                WshShell_ExitInteractive(pShell);
                WSH_SHELL_PRINT(WSH_SHELL_END_LINE);
                WshShell_InvitationPrint(pShell);
            } else
                WshShell_DeAuth(pShell, "^D");
            break;

        case WSH_SHELL_SYM_BACKSPACE:
        case WSH_SHELL_SYM_DELETE:
            WshShellIO_RemoveLeftSymbol(&(pShell->CommandLine));
            break;

        case WSH_SHELL_SYM_TAB:
            if (!WSH_SHELL_USER_IS_AUTH())
                break;

            if (WshShellAutocomplete_Try(pShell->CommandLine.Buff, pShell->CommandLine.Len, &(pShell->Commands))) {
                WshShellIO_RefreshConsoleFromInterBuff(&(pShell->CommandLine));
            } else {
                WshShell_InvitationPrint(pShell);
                WshShellIO_PrintInterBuff(&(pShell->CommandLine));
            }
            break;

        case WSH_SHELL_ESC_SEQ_START_CHAR:
            WshShellEsc_StartSeq(&(pShell->EscStorage));
            break;

        default:
            if (!WshShellStr_IsPrintableAscii(symbol)) {
                WSH_SHELL_PRINT("%c", WSH_SHELL_SYM_SOUND);
                return;
            }

            WshShell_Bool_t starsOrChars = (bool)(!WSH_SHELL_USER_IS_AUTH() && !WSH_SHELL_TMP_LOGIN_IS_EMPTY());
            WshShellIO_InsertSymbol(&(pShell->CommandLine), symbol, starsOrChars);
            break;
    }
}

#define SHELL_SAVE_PREV_AND_RETURN(pShell, sym) \
    do {                                        \
        (pShell)->PrevSym = (sym);              \
        return;                                 \
    } while (0)

void WshShell_InsertChar(WshShell_t* pShell, const WshShell_Char_t symbol) {
    WSH_SHELL_ASSERT(pShell);
    if (!pShell)
        return;

    pShell->ExtCallbacks.SymbolIn(NULL);

    WshShell_Bool_t isEnterPressed = false;
    if (symbol == WSH_SHELL_CHAR_CR || symbol == WSH_SHELL_CHAR_LF) {
        if (pShell->PrevSym == WSH_SHELL_CHAR_CR && symbol == WSH_SHELL_CHAR_LF) {
            SHELL_SAVE_PREV_AND_RETURN(pShell, symbol);
        }

        isEnterPressed = true;
    }

    WSH_SHELL_RET_STATE_t promptWaitRes = WshShellPromptWait_Handle(&(pShell->PromptWait), symbol);
    if (promptWaitRes == WSH_SHELL_RET_STATE_ERR_BUSY) {
        SHELL_SAVE_PREV_AND_RETURN(pShell, symbol);
    }

    if (isEnterPressed) {
        WSH_SHELL_PRINT(WSH_SHELL_END_LINE);

        if (!WSH_SHELL_USER_IS_AUTH()) {
            WshShell_AuthHandler(pShell);
            WshShell_InvitationPrint(pShell);
            SHELL_SAVE_PREV_AND_RETURN(pShell, symbol);
        }

        if (WSH_SHELL_INTER_CMD_EXISTS()) {
            WshShell_StringInteractHandler(pShell);
        } else
            WshShell_StringHandler(pShell);

        if (WshShell_IsAuth(pShell))
            WshShell_InvitationPrint(pShell);

        SHELL_SAVE_PREV_AND_RETURN(pShell, symbol);
    }

    if (WshShellEsc_IsSeqStarted(&(pShell->EscStorage))) {
        WshShellEsc_Handler(&(pShell->HistoryIO), &(pShell->CommandLine), &(pShell->EscStorage), symbol);
        SHELL_SAVE_PREV_AND_RETURN(pShell, symbol);
    }

    WshShell_SymbolHandler(pShell, symbol);
    SHELL_SAVE_PREV_AND_RETURN(pShell, symbol);
}