summaryrefslogtreecommitdiffstats
path: root/eurephiadm/commands/users.c
blob: 921009435709764e7fd906114c2d5ce2e749de3c (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
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
/* users.c  --  eurephiadm command - User Account Management
 *
 *  GPLv2 only - Copyright (C) 2008, 2009
 *               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.
 *
 */

/**
 * @file   users.c
 * @author David Sommerseth <dazo@users.sourceforge.net>
 * @date   2008-12-01
 *
 * @brief  eurephiadm users command.  User account management command.
 *
 */

#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
#include <assert.h>

#ifdef HAVE_LIBXML2
#include <libxml/tree.h>
#include <libxml/xpath.h>
#endif

#define MODULE "eurephia::Users" /**< Need to define the active module before including argparser.h */
#include <eurephia_nullsafe.h>
#include <eurephia_context.h>
#include <eurephia_log.h>
#include <eurephia_xml.h>
#include <eurephia_values_struct.h>
#include <eurephiadb_session_struct.h>
#include <eurephia_admin_struct.h>
#include <eurephiadb_mapping.h>
#include <eurephiadb_driver.h>
#include <certinfo.h>

#include "../argparser.h"
#include "../get_console_input.h"
#include "../field_print.h"
#include "../parse_certificate_files.h"
#include "../xsltparser.h"

// Reuse code which is in certificates.c
#define SHOWCERTS_FIREWALL  0x001
#define SHOWCERTS_DIGEST    0x002

/**
 * Forward declaration of a function already found in certificates.c
 */
int register_certificate(eurephiaCTX *ctx, int depth, const char *digest,
                         const char *cname, const char *org, const char *email);


/**
 * Help screens for the users command
 *
 * @param page which help screen to display
 */
void display_users_help(int page) {
        printf("\n%s -- Administer user accounts\n\n", MODULE);

        switch( page ) {
        case 'l':
                printf("The list mode can accept one parameter:\n\n"
                       "     -S | --sort <sort key>     Decide the sort order of the user list\n"
                       "\n"
                       "Available sort keys are: uid, username, activated, deactivated and lastaccess\n\n");
                break;

        case 's':
                printf("The show mode shows more information about a user account.\n"
                       "One of the following arguments are required:\n\n"
                       "     -i | --uid              Numeric user ID\n"
                       "     -u | --username         User name\n"
                       "\n"
                       "Optional arguments are:\n\n"
                       "     -l | --lastlog          Show users lastlog entries\n"
                       "     -L | --lastlog-details  Show a more verbose lastlog\n"
                       "     -a | --attempts         Show users failed attempts and blacklisting\n"
                       "     -b | --blacklist        Alias for --attempts\n"
                       "\n");
                break;

        case 'a':
                printf("The activate mode activates an account which not activated or deactivated.\n"
                       "One of the following arguments are required:\n\n"
                       "     -i | --uid          Numeric user ID\n"
                       "     -u | --username     User name\n\n");
                break;

        case 'd':
                printf("The deactivate mode deactivates a user account.\n"
                       "One of the following arguments are required:\n\n"
                       "     -i | --uid          Numeric user ID\n"
                       "     -u | --username     User name\n\n");
                break;

        case 'A':
                printf("The add user mode registers a new user account.\n"
                       "Both of the following arguments are required:\n\n"
                       "     -u | --username     User name to use for the new account (required)\n"
                       "     -P | --password     Assign a new password via the command line.\n\n"
                       "To register this new account against a certificate you can use the\n"
                       "following arguments.  These arguments cannot be used together.\n\n"
                       "     -C | --certid       Use already registered certificate, identified by certid.\n"
                       "     -D | --digest       Use already registered certificate, identified by digest.\n"
                       "     -c | --certfile     Use the given certificate file and register it along with\n"
                       "                         the account.\n"
                       "     -2 | --pkcs12       Certificate file is using the PKCS#12 format.\n\n");
                break;

        case 'D':
                printf("The delete user mode will delete a user account from the database.\n"
                       "One of the following arguments are required:\n\n"
                       "     -i | --uid          Numeric user ID\n"
                       "     -u | --username     User name\n\n");
                break;

        case 'p':
                printf("The change password mode is used for changing password for other\n"
                       "persons than yourself.\n\n"
                       "One of the following arguments are required:\n\n"
                       "     -i | --uid          Numeric user ID\n"
                       "     -u | --username     User name\n\n");
                break;

        default:
                printf("Available modes:\n"
                       "     -l | --list         List all user accounts\n"
                       "     -s | --show         Show user account details\n"
                       "     -a | --activate     Activate a user account\n"
                       "     -d | --deactivate   Deactivate a user account\n"
                       "     -A | --add          Add a new user account\n"
                       "     -D | --delete       Delete a user account\n"
                       "     -p | --password     Change password on a users account\n"
                       "     -h | --help <mode>  Further help for these modes\n\n");
                break;
        }
}


/**
 * Help screen wrapper for the users help function.
 *
 * @param ctx   eurephiaCTX
 * @param sess  eurephiaSESSION of the current logged in user
 * @param cfg   eurephiaVALUES struct of the current configuration
 * @param argc  argument count for the eurephiadm command
 * @param argv  argument table for the eurephiadm command
 *
 * @return returns 0 on success, otherwise 1.
 */
int help_Users2(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        e_options helpargs[] = {
                {"--list", "-l", 0},
                {"--show", "-s", 0},
                {"--activate", "-a", 0},
                {"--deactivate", "-d", 0},
                {"--add", "-A", 0},
                {"--delete", "-D", 0},
                {"--password", "-p", 0},
                {NULL, NULL, 0}
        };

        int i = 1;
        display_users_help(eurephia_getopt(&i, argc, argv, helpargs));
        return 0;
}

/**
 * Help screen wrapper.  Used by cmd_Help()
 */
void help_Users() {
        display_users_help(0);
}


/**
 * users list mode.  Lists all registered users.
 *
 * @param ctx   eurephiaCTX
 * @param sess  eurephiaSESSION of the current logged in user
 * @param cfg   eurephiaVALUES struct of the current configuration
 * @param argc  argument count for the eurephiadm command
 * @param argv  argument table for the eurephiadm command
 *
 * @return returns 0 on success, otherwise 1.
 */
int list_users(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        xmlDoc *userlist = NULL;
        int i = 0;
        char *sortkeys = NULL;
        const char *xsltparams[] = {"view", "'userlist'", NULL};

        e_options listargs[] = {
                {"--sort", "-S", 1},
                {"--help", "-h", 0},
                {NULL, NULL, 0}
        };

        assert((ctx != NULL) && (ctx->dbc != NULL) && (ctx->dbc->config != NULL));

        // Parse arguments
        for( i = 1; i < argc; i++ ) {
                switch( eurephia_getopt(&i, argc, argv, listargs) ) {
                case 'S':
                        sortkeys = optargs[0];
                        i++;
                        break;

                case 'h':
                        display_users_help('l');
                        return 0;

                default:
                        return 1;
                }
        }

        // Retrieve the user list - and display it
        userlist = eDBadminGetUserList(ctx, sortkeys);
        xslt_print_xmldoc(stdout, cfg, userlist, "users.xsl", xsltparams);
        xmlFreeDoc(userlist);

        return 0;
}

/**
 * Simple function to convert account flags from an XML document to a string of flags,
 * separated by space
 *
 * @param xpathCTX  XPath context of the XML document being parsed.
 * @param xpath     XPath expression of the flag nodes.
 *
 * @return  Returns a string of flags on success, otherwise NULL is returned.
 */
char *xmlFlags2str(xmlXPathContext *xpathCTX, const char *xpath) {
        xmlXPathObject *flagsObj = NULL;
        int i = 0;
        static char flagstr[8194];

        memset(&flagstr, 0, 8194);

        // Find the flag nodes given in the XPath query
        flagsObj = xmlXPathEvalExpression((xmlChar *)xpath, xpathCTX);
        if( flagsObj == NULL ) {
                fprintf(stderr,"Error: unable to evaluate xpath expression \"%s\"\n", xpath);
                return flagstr;
        }

        // Loop through all nodes and build up a string of all flags
        for( i = 0; i < flagsObj->nodesetval->nodeNr; i++ ) {
                char *flag = xmlExtractContent(flagsObj->nodesetval->nodeTab[i]);
                if( flag != NULL ) {
                        strncat(flagstr, flag, 8191-strlen_nullsafe(flagstr));
                        strcat(flagstr, " ");
                }
        }
        xmlXPathFreeObject(flagsObj);
        return flagstr;
}


/**
 * users show mode.  Show account information for a particular user
 *
 * @param ctx   eurephiaCTX
 * @param sess  eurephiaSESSION of the current logged in user
 * @param cfg   eurephiaVALUES struct of the current configuration
 * @param argc  argument count for the eurephiadm command
 * @param argv  argument table for the eurephiadm command
 *
 * @return returns 0 on success, otherwise 1.
 */
int show_user(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        int i, crit_set = 0, lastlog_verb = 0;
        long int show_info = USERINFO_user | USERINFO_certs;
        xmlDoc *user_xml = NULL, *srch_xml = NULL;
        xmlNode *srch_root = NULL;
#ifdef FIREWALL
        const char *xsltparams[] = {"view", NULL, "firewall", "'1'", "view_digest", "'0'", NULL};
#else
        const char *xsltparams[] = {"view", NULL, "firewall", "'0'", "view_digest", "'0'", NULL};
#endif

        e_options activargs[] = {
                {"--uid", "-i", 1},
                {"--username", "-u", 1},
                {"--lastlog", "-l", 0},
                {"--lastlog-details", "-L", 0},
                {"--attempts", "-a", 0},
                {"--blacklist", "-b", 0}, // Alias for -a | --attempts
                {"--help", "-h", 0},
                {NULL, NULL, 0}
        };

        assert((ctx != NULL) && (ctx->dbc != NULL) && (ctx->dbc->config != NULL));

        // Create a fieldMapping XML document, used for searching the user database
        eurephiaXML_CreateDoc(ctx, 1, "fieldMapping", &srch_xml, &srch_root);
        xmlNewProp(srch_root, (xmlChar *) "table", (xmlChar *)"users"); // Which table to search in


        // Argument parsing
        crit_set = 0;
        for( i = 1; i < argc; i++ ) {
                switch( eurephia_getopt(&i, argc, argv, activargs) ) {
                case 'i':
                        if( atoi_nullsafe(optargs[0]) == 0 ) {
                                fprintf(stderr, "%s: Invalid user id\n", MODULE);
                                return 1;
                        }
                        xmlNewChild(srch_root, NULL, (xmlChar *)"uid", (xmlChar *) optargs[0]);
                        crit_set++;
                        break;

                case 'u':
                        if( strlen_nullsafe(optargs[0]) < 3 ) {
                                fprintf(stderr, "%s: User name too short\n", MODULE);
                                return 1;
                        }
                        xmlNewChild(srch_root, NULL, (xmlChar *)"username", (xmlChar *)optargs[0]);
                        crit_set++;
                        break;

                case 'a':
                case 'b':
                        show_info = USERINFO_attempts | USERINFO_blacklist;
                        break;

                case 'L':
                        lastlog_verb = 1;
                case 'l':
                        show_info = USERINFO_lastlog;
                        break;

                case 'h':
                        display_users_help('s');
                        return 0;

                default:
                        return 1;
                }
        }

        // Check if we have the needed search criteria
        if( crit_set == 0 ) {
                fprintf(stderr,
                        "%s:  Missing required parameter.  You must provide either user id or user name\n",
                        MODULE);
                xmlFreeDoc(srch_xml);
                return 1;
        }

        if( crit_set > 1 ) {
                fprintf(stderr,
                        "%s: You cannot have several search criteria (-i | -u)\n", MODULE);
                xmlFreeDoc(srch_xml);
                return 1;
        }

        // Search and find the user which was requested
        if( (user_xml = eDBadminGetUserInfo(ctx, show_info, srch_xml)) == NULL )  {
                fprintf(stderr, "%s: User not found\n", MODULE);
                return 1;
        }
        xmlFreeDoc(srch_xml);

        if( show_info & USERINFO_user ) {
                xsltparams[1] = "'userinfo'";
                xslt_print_xmldoc(stdout, cfg, user_xml, "users.xsl", xsltparams);
        }

        // Show associated certificates if we was asked to show this info
        if( show_info & USERINFO_certs ) {
                xsltparams[1] = "''";
                xslt_print_xmldoc(stdout, cfg, user_xml, "certificates.xsl", xsltparams);
        }

        // Show lastlog for the user, if requested
        if( show_info & USERINFO_lastlog ) {
                xmlNode *user_n = NULL;

                xsltparams[1] = "'list'";
                if( lastlog_verb ) {
                        xsltparams[1] = "'details'";
                }

                user_n = eurephiaXML_getRoot(ctx, user_xml, "user", 1);
                if( user_n == NULL ) {
                        fprintf(stderr, "Could not retrieve valid data\n");
                        xmlFreeDoc(user_xml);
                        return 1;
                }
                printf("** Lastlog entries for %s\n\n", xmlGetNodeContent(user_n, "username"));

                xslt_print_xmldoc(stdout, cfg, user_xml, "lastlog.xsl", xsltparams);
        }

        // Show login attempt info and/or blacklist info
        if( (show_info & USERINFO_attempts) || (show_info & USERINFO_blacklist) ) {
                xsltparams[1] = "'attemptblacklist'";
                xslt_print_xmldoc(stdout, cfg, user_xml, "users.xsl", xsltparams);
        }

        // Clean up
        xmlFreeDoc(user_xml);

        return 0;
}




/**
 * This function handles activation, deactivation and deletion of an account
 *
 * @param ctx   eurephiaCTX
 * @param sess  eurephiaSESSION of the current logged in user
 * @param cfg   eurephiaVALUES struct of the current configuration
 * @param argc  argument count for the eurephiadm command
 * @param argv  argument table for the eurephiadm command
 *
 * @return returns 0 on success, otherwise 1.
 */
int account_activation(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        xmlDoc *user_xml = NULL, *update_xml = NULL, *srch_xml = NULL, *tmp_xml = NULL;
        xmlNode *user_n = NULL, *update_n = NULL, *srch_root = NULL, *tmp_n = NULL;
        char *uid_str = NULL, *activated = NULL, *deactivated = NULL, *actmode_str = NULL, *newpwd = NULL;
        int i, actmode = 0, rc = 0, crit_set = 0;

        e_options activargs[] = {
                {"--uid", "-i", 1},
                {"--username", "-u", 1},
                {"--new-password", "-P", 1},
                {"--help", "-h", 0},
                {NULL, NULL, 0}
        };

        assert((ctx != NULL) && (ctx->dbc != NULL) && (ctx->dbc->config != NULL));

        if( (strcmp(argv[0], "--activate") == 0) || (strcmp(argv[0], "-a") == 0) ) {
                actmode = 'a';
                actmode_str = "activated";
        } else if( (strcmp(argv[0], "--deactivate") == 0) || (strcmp(argv[0], "-d") == 0) ) {
                actmode = 'd';
                actmode_str = "deactivated";
        } else if( (strcmp(argv[0], "--delete") == 0) || (strcmp(argv[0], "-D") == 0) ) {
                actmode = 'D';
                actmode_str = "deleted";
        } else if( (strcmp(argv[0], "--password") == 0) || (strcmp(argv[0], "-p") == 0) ) {
                actmode = 'p';
                actmode_str = "updated with new password";
        } else {
                fprintf(stderr, "%s: System error - illegal users mode'%s'\n", MODULE, argv[0]);
                return 1;
        }

        // Create a fieldMapping XML document, used for searching the user database
        eurephiaXML_CreateDoc(ctx, 1, "fieldMapping", &srch_xml, &srch_root);
        xmlNewProp(srch_root, (xmlChar *) "table", (xmlChar *)"users"); // Which table to search in

        // Argument parsing
        crit_set = 0;
        for( i = 1; i < argc; i++ ) {
                switch( eurephia_getopt(&i, argc, argv, activargs) ) {
                case 'i':
                        if( atoi_nullsafe(optargs[0]) == 0 ) {
                                fprintf(stderr, "%s: Invalid user id\n", MODULE);
                                return 1;
                        }
                        xmlNewChild(srch_root, NULL, (xmlChar *)"uid", (xmlChar *) optargs[0]);
                        crit_set++;
                        break;

                case 'u':
                        if( strlen_nullsafe(optargs[0]) < 3 ) {
                                fprintf(stderr, "%s: User name too short\n", MODULE);
                                return 1;
                        }
                        xmlNewChild(srch_root, NULL, (xmlChar *)"username", (xmlChar *)optargs[0]);
                        crit_set++;
                        break;

                case 'h':
                        display_users_help(actmode);
                        return 0;

                case 'P':
                        newpwd = strdup_nullsafe(optargs[0]);
                        break;

                default:
                        return 1;
                }
        }

        // Check if we have the needed search criteria
        if( crit_set == 0 ) {
                fprintf(stderr,
                        "%s:  Missing required parameter.  You must provide either user id or user name\n",
                        MODULE);
                xmlFreeDoc(srch_xml);
                return 1;
        }

        if( crit_set > 1 ) {
                fprintf(stderr,
                        "%s: You cannot have several search criteria (-i | -u)\n", MODULE);
                xmlFreeDoc(srch_xml);
                return 1;
        }

        // Search and find the user which was requested
        if( (user_xml = eDBadminGetUserInfo(ctx, USERINFO_user, srch_xml)) == NULL )  {
                fprintf(stderr, "%s: User not found\n", MODULE);
                xmlFreeDoc(srch_xml);
                return 1;
        }
        xmlFreeDoc(srch_xml);

        // Parse the user information we received
        user_n = eurephiaXML_getRoot(ctx, user_xml, "user", 1);
        if( user_n == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0, "%s: Could not find user node in the XML document", MODULE);
                xmlFreeDoc(user_xml);
                return 1;
        }

        uid_str     = xmlGetAttrValue(user_n->properties, "uid");
        activated   = defaultValue(xmlGetNodeContent(user_n, "activated"), NULL);
        deactivated = defaultValue(xmlGetNodeContent(user_n, "deactivated"), NULL);

        // Create a new XML document which will be used to update the user account
        eurephiaXML_CreateDoc(ctx, 1, "update_user", &update_xml, &update_n);
        assert( (update_xml != NULL) && (update_n != NULL) );
        xmlNewProp(update_n, (xmlChar *) "uid", (xmlChar *) uid_str);

        // Add fieldMapping - to correctly map eurephia fields into the database fields
        update_n = xmlNewChild(update_n, NULL, (xmlChar *) "fieldMapping", NULL);
        xmlNewProp(update_n, (xmlChar *) "table", (xmlChar *) "users");

        switch( actmode ) {
        case 'a':  // Activate a user account
                if( (activated != NULL)  && (deactivated == NULL) ) {
                        printf("User account is already active\n");
                        goto exit;
                } else {
                        // Set activated field to now()
                        xmlNewChild(update_n, NULL,
                                     (xmlChar *) "activated", (xmlChar *) "CURRENT_TIMESTAMP");

                        // Remove deactivated flag
                        tmp_n = xmlNewChild(update_n, NULL,(xmlChar *) "deactivated", NULL);
                        xmlNewProp(tmp_n, (xmlChar *) "setnull", (xmlChar *) "1");
                }

                // Do the update of the user account
                rc = eDBadminUpdateUser(ctx, atoi_nullsafe(uid_str), update_xml);
                break;

        case 'd':  // Deactivate a user account
                if( (activated != NULL)  && (deactivated != NULL) ) {
                        printf("User account is already deactivated\n");
                        goto exit;
                } else if( (activated != NULL) ) {
                        // Set deactivated to now()
                        xmlNewChild(update_n, NULL,
                                     (xmlChar *) "deactivated", (xmlChar *) "CURRENT_TIMESTAMP");

                } else {
                        fprintf(stderr, "%s: User account is not activated yet\n", MODULE);
                        goto exit;
                }

                // Do the update of the user account
                rc = eDBadminUpdateUser(ctx, atoi_nullsafe(uid_str), update_xml);
                break;

        case 'p':  // Change password for a user

                // If we do not have a password .... ask for password via console
                if( newpwd == NULL ) {
                        char *chkpwd = NULL;

                        newpwd = (char *) malloc(66);
                        assert(newpwd != NULL);
                        memset(newpwd, 0, 66);

                        chkpwd = (char *) malloc(66);
                        assert(chkpwd != NULL);
                        memset(chkpwd, 0, 66);

                        get_console_input(newpwd, 64, "Password for user:", 1);
                        if( strlen_nullsafe(newpwd) < 4 ) {
                                free_nullsafe(newpwd);
                                free_nullsafe(chkpwd);
                                fprintf(stderr, "%s: Password is too short\n", MODULE);
                                goto exit;
                        }

                        get_console_input(chkpwd, 64, "Verify password for user:", 1);
                        if( strcmp(newpwd, chkpwd) != 0 ) {
                                free_nullsafe(newpwd);
                                free_nullsafe(chkpwd);
                                fprintf(stderr, "%s: Passwords didn't match\n", MODULE);
                                goto exit;
                        }
                        free_nullsafe(chkpwd);
                }

                // Update with new password
                tmp_n = xmlNewChild(update_n, NULL, (xmlChar *) "password", (xmlChar *)newpwd);
                xmlNewProp(tmp_n, (xmlChar *) "pwhash", (xmlChar *) "none");
                rc = eDBadminUpdateUser(ctx, atoi_nullsafe(uid_str), update_xml);

                free_nullsafe(newpwd);
                break;

        case 'D':  // Delete user account
                xmlFreeDoc(update_xml); // We need another XML doc to delete users

                eurephiaXML_CreateDoc(ctx, 1, "delete_user", &update_xml, &update_n);
                assert( (update_xml != NULL) && (update_n != NULL) );
                xmlNewProp(update_n, (xmlChar *) "uid", (xmlChar *) uid_str);

                rc = eDBadminDeleteUser(ctx, atoi_nullsafe(uid_str), update_xml);

                // Delete links between certificates associated to this user account
                xmlFreeDoc(update_xml);
                eurephiaXML_CreateDoc(ctx, 1, "usercerts", &update_xml, &update_n);
                assert( (update_xml != NULL) && (update_n != NULL) );

                xmlNewProp(update_n, (xmlChar *) "mode", (xmlChar *) "remove");
                update_n = xmlNewChild(update_n, NULL, (xmlChar *) "fieldMapping", NULL);
                xmlNewProp(update_n, (xmlChar *) "table", (xmlChar *) "usercerts");
                xmlNewChild(update_n, NULL, (xmlChar *) "uid", (xmlChar *) uid_str);

		tmp_xml = eDBadminUserCertsLink(ctx, update_xml);
                if( tmp_xml == NULL ) {
                        fprintf(stderr, "%s: Failed to remove the user-certs link\n", MODULE);
                }

		tmp_n = eurephiaXML_getRoot(ctx, tmp_xml, NULL, 1);
		if( xmlStrcmp(tmp_n->name, (xmlChar *) "Error") == 0 ) {
			fprintf(stderr, "%s: %s\n", MODULE, xmlExtractContent(tmp_n));
			rc = 0;
		}
		xmlFreeDoc(tmp_xml);
                break;
        }

        if( rc == 1 ) {
                printf("User account is %s\n", actmode_str);
        } else {
                fprintf(stderr, "%s: Operation failed\n", MODULE);
        }

 exit:
        xmlFreeDoc(user_xml);
        xmlFreeDoc(update_xml);
        return (rc != 1);
}


/**
 * users add mode.  Creates a new user account.
 *
 * @param ctx   eurephiaCTX
 * @param sess  eurephiaSESSION of the current logged in user
 * @param cfg   eurephiaVALUES struct of the current configuration
 * @param argc  argument count for the eurephiadm command
 * @param argv  argument table for the eurephiadm command
 *
 * @return returns 0 on success, otherwise 1.
 */
int add_user(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        xmlDoc *user_xml = NULL;
        xmlNode *node = NULL, *node2 = NULL;
        struct stat cert_stat;
        int i = 0, certid = 0, uid = 0, certfile_format = CERTFILE_PEM;
        char *uname = NULL, *passwd = NULL, *certfile = NULL, *digest = NULL;

        e_options addu_args[] = {
                {"--username", "-u", 1},
                {"--password", "-P", 1},
                {"--certid",   "-C", 1},
                {"--certfile", "-c", 1},
                {"--digest",   "-d", 1},
                {"--pkcs12",   "-2", 0},
                {"--help", "-h", 0},
                {NULL, NULL, 0}
        };

        assert((ctx != NULL) && (ctx->dbc != NULL) && (ctx->dbc->config != NULL));

        // Parse arguments
        for( i = 1; i < argc; i++ ) {
                switch( eurephia_getopt(&i, argc, argv, addu_args) ) {
                case 'u':
                        if( strlen_nullsafe(optargs[0]) < 3 ) {
                                fprintf(stderr, "%s: username is too short\n", MODULE);
                                return 1;
                        }
                        uname = optargs[0];
                        break;

                case 'P':
                        if( strlen_nullsafe(optargs[0]) < 4 ) {
                                fprintf(stderr, "%s: password is too short\n", MODULE);
                                return 1;
                        }
                        passwd = strdup_nullsafe(optargs[0]);
                        break;

                case 'C':
                        if( (certid = atoi_nullsafe(optargs[0])) < 1 ) {
                                fprintf(stderr, "%s: Invalid certid (numeric value > 0)\n", MODULE);
                                return 1;
                        }
                        break;

                case 'c': // Check if certfile exists and is readable for us
                        if( strlen_nullsafe(optargs[0]) < 1 ) {
                                fprintf(stderr, "%s: certfile is too short\n", MODULE);
                                return 1;
                        }
                        certfile = optargs[0];

                        if( stat(certfile, &cert_stat) == -1 ) {
                                fprintf(stderr, "%s: Could not access certfile: %s (%s)\n", MODULE,
                                        certfile, strerror(errno));
                                return 1;
                        }

                        if( cert_stat.st_size == 0 ) {
                                fprintf(stderr, "%s: certfile '%s' is empty\n", MODULE, certfile);
                                return 1;
                        }
                        break;

                case '2':
                        certfile_format = CERTFILE_PKCS12;
                        break;

                case 'd':
                        if( strlen_nullsafe(optargs[0]) < 59 ) {
                                fprintf(stderr, "%s: Certificate digest is too short\n", MODULE);
                                return 1;
                        }
                        digest = optargs[0];
                        break;

                case 'h':
                        display_users_help('A');
                        return 0;

                default:
                        return 1;
                }
        }

        // Make sure received arguments are sane
        if( uname == NULL ) {
                fprintf(stderr, "%s: Missing user name\n", MODULE);
                return 1;
        }

        if( ((certid > 0) && (digest != NULL))
            || ((certid > 0) && (certfile != NULL))
            || ((digest != NULL) && (certfile != NULL)) ) {
                fprintf(stderr, "%s: --certid, --certfile and --digest cannot be used together\n", MODULE);
                return 1;
        }

        // If we do not have a password .... ask for password via console
        if( passwd == NULL ) {
                char *chkpwd = NULL;

                passwd = (char *) malloc(66);
                assert(passwd != NULL);
                memset(passwd, 0, 66);

                chkpwd = (char *) malloc(66);
                assert(chkpwd != NULL);
                memset(chkpwd, 0, 66);

                get_console_input(passwd, 64, "Password for user:", 1);
                if( strlen_nullsafe(passwd) < 4 ) {
                        free_nullsafe(passwd);
                        free_nullsafe(chkpwd);
                        fprintf(stderr, "%s: Password is too short\n", MODULE);
                        return 1;
                }

                get_console_input(chkpwd, 64, "Verify password for user:", 1);
                if( strcmp(passwd, chkpwd) != 0 ) {
                        free_nullsafe(passwd);
                        free_nullsafe(chkpwd);
                        fprintf(stderr, "%s: Passwords didn't match\n", MODULE);
                        return 1;
                }
                free_nullsafe(chkpwd);
        }


        // Prepare add user XML document with fieldMapping
        eurephiaXML_CreateDoc(ctx, 1, "add_user", &user_xml, &node);
        node = xmlNewChild(node, NULL, (xmlChar *) "fieldMapping", NULL);
        xmlNewProp(node, (xmlChar *) "table", (xmlChar *) "users");

        xmlNewChild(node, NULL, (xmlChar *) "username", (xmlChar *) uname);
        node2 = xmlNewChild(node, NULL, (xmlChar *) "password", (xmlChar *) passwd);
        xmlNewProp(node2, (xmlChar *) "pwhash", (xmlChar *) "none");

        // Add the user
        uid = eDBadminAddUser(ctx, user_xml);
        if( uid > 0 ) {
                fprintf(stdout, "%s: User registered successfully (user id %i)\n", MODULE, uid);
        } else {
                fprintf(stderr, "%s: Failed to register user\n", MODULE);
        }
        memset(passwd, 0, strlen_nullsafe(passwd));
        free_nullsafe(passwd);
        xmlFreeDoc(user_xml);

        if( (digest != NULL) || (certfile != NULL) ) {
                if( digest != NULL ) {
                        xmlDoc *cert_xml = NULL, *certlist = NULL;
                        xmlNode *cert_n = NULL;
                        int certcount = 0;

                        // when we have certificate digest, look that up
                        eurephiaXML_CreateDoc(ctx, 1, "certificate_info", &cert_xml, &cert_n);
                        cert_n = xmlNewChild(cert_n, NULL, (xmlChar *) "fieldMapping", NULL);
                        xmlNewProp(cert_n, (xmlChar *) "table", (xmlChar *) "certificates");
                        xmlNewChild(cert_n, NULL, (xmlChar *) "digest", (xmlChar *) digest);

                        certlist = eDBadminGetCertificateInfo(ctx, cert_xml, "certid");
                        if( certlist == NULL ) {
                                fprintf(stderr, "%s: Error while looking up certificate info.\n"
                                        "%s: User account is not associated with any certificates\n",
                                        MODULE, MODULE);
                                xmlFreeDoc(cert_xml);
                                goto exit;
                        }
                        xmlFreeDoc(cert_xml);

                        cert_n = eurephiaXML_getRoot(ctx, certlist, "certificates", 1);
                        if( cert_n == NULL ) {
                                fprintf(stderr, "%s: Could not find certificates root node in XML document. "
                                        "No association done.\n", MODULE);
                                xmlFreeDoc(certlist);
                                goto exit;
                        }
                        certcount = atoi_nullsafe(xmlGetAttrValue(cert_n->properties, "certificates"));
                        if( certcount == 0) {
                                fprintf(stderr, "%s: No certificates was found. No association is done.\n",
                                        MODULE);
                                xmlFreeDoc(certlist);
                                goto exit;
                        } else if( certcount > 1 ) {
                                fprintf(stderr, "%s: More than one certificates was found. "
                                        "No association is done.\n", MODULE);
                                xmlFreeDoc(certlist);
                                goto exit;
                        }

                        // Get the first and only certificate node
                        cert_n = xmlFindNode(cert_n, "certificate");
                        if( cert_n == NULL ) {
                                fprintf(stderr, "%s: Could not find certificate node in XML document. "
                                        "No association done.\n", MODULE);
                                xmlFreeDoc(certlist);
                                goto exit;
                        }
                        // finally, we should have located the certid in the XML
                        certid = atoi_nullsafe(xmlGetAttrValue(cert_n->properties, "certid"));
                        xmlFreeDoc(certlist);
                } else if( certfile != NULL ) {
                        // when we have certfile - register the certificate and register the link
                        certinfo *ci = NULL;

                        ci = Cert_ParseFile(certfile, certfile_format);
                        if( ci == NULL ) {
                                fprintf(stderr, "%s: Could not parse the certificate file.  "
                                        "No association done.\n", MODULE);
                                goto exit;
                        }

                        certid = register_certificate(ctx, 0, ci->digest, ci->common_name, ci->org, ci->email);
                        if( certid == 0 ) {
                                fprintf(stderr, "%s: Failed to register certificate file.  No association done.",
                                        MODULE);
                        }
                }
        }

        // If we have a certificate id, register a certificate link to the user account
        if( (certid > 0) && (uid > 0) ) {
                xmlDoc *usercert_xml = NULL, *res_xml = NULL;
                xmlNode *usercert_n = NULL, *res_n = NULL;
                xmlChar tmp[66];

                memset(&tmp, 0, 66);
                eurephiaXML_CreateDoc(ctx, 1, "usercerts", &usercert_xml, &usercert_n);
                assert( (usercert_xml != NULL) && (usercert_n != NULL) );

                xmlNewProp(usercert_n, (xmlChar *) "mode", (xmlChar *) "register");
                usercert_n = xmlNewChild(usercert_n, NULL, (xmlChar *) "fieldMapping", NULL);
                xmlNewProp(usercert_n, (xmlChar *) "table", (xmlChar *) "usercerts");

                xmlStrPrintf(tmp, 64, (xmlChar *) "%i%c", uid, '\0');
                xmlNewChild(usercert_n, NULL, (xmlChar *) "uid", tmp);
                xmlStrPrintf(tmp, 64, (xmlChar *) "%i%c", certid, '\0');
                xmlNewChild(usercert_n, NULL, (xmlChar *) "certid", tmp);

		res_xml = eDBadminUserCertsLink(ctx, usercert_xml);
                if( res_xml == NULL ) {
                        fprintf(stderr, "%s: Failed to register user <-> certificate link\n", MODULE);
			goto exit;
                }

		res_n = eurephiaXML_getRoot(ctx, res_xml, NULL, 1);
		if( xmlStrcmp(res_n->name, (xmlChar *) "Error") == 0 ) {
			fprintf(stderr, "%s: %s\n", MODULE, xmlExtractContent(res_n));
		}
		xmlFreeDoc(res_xml);
        }
 exit:
        return (uid > 0);
}


/**
 * Main function for the users command.
 *
 * @param ctx   eurephiaCTX
 * @param sess  eurephiaSESSION of the current logged in user
 * @param cfg   eurephiaVALUES struct of the current configuration
 * @param argc  argument count for the eurephiadm command
 * @param argv  argument table for the eurephiadm command
 *
 * @return returns 0 on success, otherwise 1.
 */
int cmd_Users(eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv) {
        char **mode_argv;
        int i, mode_argc = 0, rc = 0;
        int (*mode_fnc) (eurephiaCTX *ctx, eurephiaSESSION *sess, eurephiaVALUES *cfg, int argc, char **argv);

        e_options modeargs[] = {
                {"--list", "-l", 0},
                {"--show", "-s", 0},
                {"--activate", "-a", 0},
                {"--deactivate", "-d", 0},
                {"--add", "-A", 0},
                {"--delete", "-D", 0},
                {"--password", "-p", 0},
                {"--help", "-h", 0},
                {NULL, NULL, 0}
        };

        assert((ctx != NULL) && (ctx->dbc != NULL) && (ctx->dbc->config != NULL));
        mode_fnc = NULL;
        for( i = 1; i < argc; i++ ) {
                switch( eurephia_getopt(&i, argc, argv, modeargs) ) {
                case 'l':
                        mode_fnc = list_users;
                        break;

                case 's':
                        mode_fnc = show_user;
                        break;

                case 'a':
                        mode_fnc = account_activation;
                        break;

                case 'd':
                        mode_fnc = account_activation;
                        break;

                case 'h':
                        mode_fnc = help_Users2;
                        break;

                case 'A':
                        mode_fnc = add_user;
                        break;

                case 'D':
                        mode_fnc = account_activation;
                        break;

                case 'p':
                        mode_fnc = account_activation;
                        break;

                default:
                        break;
                }
                if( mode_fnc != NULL ) {
                        break;
                }
        }

        // If we do not have any known mode defined, exit with error
        if( mode_fnc == NULL )  {
                fprintf(stderr, "Unknown argument.  No mode given\n");
                return 1;
        }

        // Allocate memory for our arguments being sent to the mode function
        mode_argv = (char **) calloc(sizeof(char *), (argc - i)+2);
        assert(mode_argv != NULL);

        // Copy over only the arguments needed for the mode
        mode_argc = eurephia_arraycp(i, argc, argv, mode_argv, (argc - i));

        // Call the mode function
        rc = mode_fnc(ctx, sess, cfg, mode_argc, mode_argv);
        free_nullsafe(mode_argv);

        return rc;
}