summaryrefslogtreecommitdiffstats
path: root/eurephiadm/eurephiadm.c
blob: 8eac0a6d85d318e6b328ce98db64112b20581559 (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
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
/* eurephiadm.c  --  CLI based admin program for eurephia
 *
 *  GPLv2 - Copyright (C) 2008  David Sommerseth <dazo@users.sourceforge.net>
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; version 2
 *  of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <libgen.h>
#define _GNU_SOURCE
#include <getopt.h>

#include <eurephia_nullsafe.h>
#include <eurephia_context.h>
#include <eurephia_log.h>
#include <eurephia_values.h>
#include <eurephiadb_driver.h>
#include <eurephiadb_session_common.h>
#include <eurephiadb.h>

#include "client_context.h"
#include "client_config.h"
#include "client_session.h"
#include "get_console_input.h"
#include "commands.h"

#define EUREPHIADMVERSION "1.0"
#define MAX_ARGUMENTS 64


char *print_version(char *fprg) {
        char *prg = basename(fprg);

        fprintf(stdout, "%s (v%s) - eurephia administration utility\n"
                "Copyright (C) 2008  David Sommerseth <dazo@users.sourceforge.net>\n",
                prg, EUREPHIADMVERSION);
        return prg;
}


int cmd_Help(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        eurephiadm_functions *func = NULL;
        int i;
        char *prg = NULL;

        prg = print_version(argv[0]);

        fprintf(stdout, "\n    Usage: %s [global options] <command> [command options]\n\n", prg);

        fprintf(stdout,"        %-20.20s %-20.20s %-30.30s\n",
                "-V | --version", "", "Print version of eurephiadm");
        fprintf(stdout,"        %-20.20s %-20.20s %-30.30s\n",
                "-l | --log", "<file name>", "Log to file");
        fprintf(stdout,"        %-20.20s %-20.20s %-30.30s\n",
                "-L | --log-level", "<log level>", "Set log verbosity");


        fprintf(stdout,"\n        %-20.20s %-20.20s %-30.30s\n",
                "Command","Arguments","Description");
        fprintf(stdout, "        ------------------------------------------------------------------------\n");

        for( i = 0; cmdline_functions[i].command != NULL; i++ ) {
                func = (eurephiadm_functions *)&cmdline_functions[i];
                fprintf(stdout,"        %-20.20s %-20.20s %-30.30s\n",
                        func->command,
                        (func->arghint != NULL ? func->arghint : ""),
                        func->helpinfo);
        }
        fprintf(stdout, "\n");
        return 0;
}

int cmd_Logout(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        int rc = 0;
        rc = eDBadminLogout(ctx, sess);
        fprintf(stdout, "%s\n", (rc == 1 ? "Logged out succesfully" : "Logout failed."));
        return (rc == 0);
}

int cmd_ShowCfg(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        void dump_values(eurephiaVALUES *vls) {
                eurephiaVALUES *ptr = NULL;
                fprintf(stdout, "----------------------------------------------------------------------\n");
                for( ptr = vls; ptr != NULL; ptr = ptr->next) {
                        fprintf(stdout, "%20s = %s\n", ptr->key, ptr->val);
                }
                fprintf(stdout, "----------------------------------------------------------------------\n");
        }

        if( cfg != NULL ) {
                fprintf(stdout, "\n** eurephiadm configuration settings (config file) **\n");
                dump_values(cfg);
                fprintf(stdout, "\n");
        }
        if( ctx != NULL ) {
                fprintf(stdout, "** eurephia configuration settings (set in database) **\n");
                dump_values(ctx->dbc->config);
                fprintf(stdout, "\n");
        }
        return 0;
}


int eurephia_ConnectDB(eurephiaCTX *ctx, const char *argstr) {
        char *delims = " ";
        char *cp = NULL;
        const char *dbargv[MAX_ARGUMENTS];
        int dbargc = 0;

        if( (argstr == NULL) || (strlen(argstr) < 1) ) {
                eurephia_log(ctx, LOG_FATAL, 0, "No database connection string given");
                return 0;
        }

        // Split up argstr into separate arguments
        cp = strdup(argstr);
        assert(cp != NULL);
        
        dbargc = 0;
        dbargv[dbargc] = strtok(cp, delims);
        while( (dbargv[dbargc] != NULL) && (dbargc <= MAX_ARGUMENTS) ) {
                dbargv[++dbargc] = strtok(NULL, delims);
        }

        if( !eDBconnect(ctx, dbargc, dbargv) ) {
                eurephia_log(ctx, LOG_PANIC, 0, "Could not connect to the database");
                eDBlink_close(ctx);
                return 0;
        }
       
        return 1;
}

eurephiaSESSION *do_login(eurephiaCTX *ctx) {
        eurephiaSESSION *session = NULL;
        char username[33], password[33];
        int uid = 0;

        memset(&username, 0, 33);
        memset(&password, 0, 33);
        get_console_input(username, 32, "User:", 0);
        get_console_input(password, 32, "Password:", 1);

        if( (uid = eDBadminAuth(ctx, username, password)) < 1 ) {
                // Register failure
                memset(username, 0, 33);
                memset(password, 0, 33);
                return NULL;
        }
        memset(username, 0, 33);
        memset(password, 0, 33);

        session = create_session(ctx, NULL);
        snprintf(username, 30, "%i", uid); // Borrow username for converting uid to a string

        if( !eDBset_session_value(ctx, session, "uid", username) ) {
                eurephia_log(ctx, LOG_FATAL, 0, "Could not update session variables (uid)");
                eDBfree_session(ctx, session);
                return NULL;
        };

        if( !eDBadminRegisterLogin(ctx, session) ) {
                eurephia_log(ctx, LOG_FATAL, 0, "Could not register login");
                eDBfree_session(ctx, session);
                return NULL;
        }

        return session;
}


int main(int argc, char **argv) {
        FILE *logfile = NULL;
        int loglevel = 0;
        eurephiaCTX *ctx = NULL;
        eurephiaSESSION *session = NULL;
        eurephiaVALUES *cfg = NULL;
        char *sesskey_file = NULL;
        char *dbparams = NULL, *cmdargv[MAX_ARGUMENTS];
        int rc = 0, i = 0, found = 0, cmdargc = 0, argi = 0;
        eurephiadm_functions *call_fnc;

        if( argc < 2 ) {
                cmd_Help(NULL, NULL, NULL, argc, argv);
                return 1;
        }

        // Parse argument line
        argi = 1;
        while( 1 ) {
                int optidx = 0;

                /* global arguments */
                static struct option argopts[] = {
                        {"version", 0, 0, 'V'},
                        {"help", 0, 0, 'h'},
                        {"log", 1, 0, 'l'},
                        {"log-level", 1, 0, 'L'},
                        {0,0,0,0}
                };

                i = getopt_long(argc, argv, "Vhl:L:", argopts, &optidx);
                if( i == -1 ) {
                        break;
                }

                switch( i ) {
                case 'V':
                        print_version(argv[0]);
                        return 0;

                case 'h':
                        cmd_Help(NULL, NULL, NULL, argc, argv);
                        return 0;

                case 'l':
                        if( (logfile = fopen(optarg, "wb")) == NULL ) {
                                fprintf(stderr, "%s: ERROR :: Could not open log file: %s\n", 
                                        basename(argv[0]), optarg);
                                return 0;
                        }
                        argi++;
                        break;

                case 'L':
                        loglevel = atoi_nullsafe(optarg);
                        argi++;
                        break;
                }
                argi++;
        }

        if( argi >= argc ) {
                fprintf(stderr, "%s: ERROR :: No command given\n", basename(argv[0]));
                return 1;
        } else {
                for( i = argi; ((i < argc) && (i < MAX_ARGUMENTS)); i++ ) {
                        cmdargv[cmdargc++] = argv[i];
                }
        }

        // Find the command requested and save a pointer to that command's C function
        for( i = 0; cmdline_functions[i].command != NULL; i++ ) {
                call_fnc = (eurephiadm_functions *)&cmdline_functions[i];

                if( strcmp(call_fnc->command, cmdargv[0]) == 0 ) {
                        found = 1;
                        break;
                }
        }

        // Exit with error if command is not found
        if( found == 0 ) {
                fprintf(stderr, "%s:  No such command '%s'\n", basename(argv[0]), argv[argi]);
                return 5;
        }

        // Read configuration file
        cfg = ReadConfig("EUREPHIADM_CONFIG", "eurephiadm.cfg");
        if( cfg == NULL ) {
                fprintf(stderr, "No configuration file found.\n");
                return 2;
        }

        // If function do not need a logged in session, go a head process it now and exit
        if( call_fnc->need_session == 0 ) {
                rc = call_fnc->function(NULL, NULL, cfg, cmdargc, cmdargv);
                eFree_values(NULL, cfg);
                return rc;
        }


        //
        //  Load database driver, setup a context and create or reuse an open session
        //  and then call the command's function
        //

        // Create a eurephia context and load database driver
        ctx = eurephiaCTX_init(logfile, loglevel, cfg);
        if( ctx == NULL ) {
                fprintf(stderr, "Could not initialise a eurephia context.\n");
                return 3;
        }

        // Connect to the database
        dbparams = eGet_value(cfg, "database_params");
        if( !eurephia_ConnectDB(ctx, dbparams) ) {
                return 4;
        }

        // Load session file, if it exists.  (reuse open session)
        if( (sesskey_file = read_session_file(ctx)) == NULL ) {
                // No session file - go straight to login
                if( strcmp(call_fnc->command, "logout") == 0) {
                        fprintf(stderr, "You are already logged out\n");
                        rc = 0;
                        goto exit;
                }
                session = do_login(ctx);
        } else {
                // Session file found, check if it still is a valid session
                if( eDBadminValidateSession(ctx, sesskey_file) ) {;
                        // If valid, load this session
                        session = create_session(ctx, sesskey_file);
                } else {
                        // If not valid, remove session file and go to login
                        remove_session_file(ctx);
                        if( strcmp(call_fnc->command, "logout") == 0) {
                                fprintf(stderr, "You are already logged out\n");
                                rc = 0;
                                goto exit;
                        }
                        session = do_login(ctx);
                }
        }
        free_nullsafe(sesskey_file);


        // If we have an open session now, call the requested command
	if(session != NULL ) {
                // Write session info to a file
                if( !write_session_file(ctx, session) )  {
                        eurephia_log(ctx, LOG_ERROR, 0, "Could not write session file.  Login needed for actions");
                };

                // Execute the requested command
                rc = call_fnc->function(ctx, session, cfg, cmdargc, cmdargv);

                // Remove session info from memory
                eDBfree_session(ctx, session);
        } else {
                // If not an open session, make sure the session file is gone
                remove_session_file(ctx);
        }

 exit:
        // Disconnect from the database, and remove config and our context before exiting
        eFree_values(ctx, cfg);
        eDBdisconnect(ctx);
        eurephiaCTX_destroy(ctx);
        return rc;
}