summaryrefslogtreecommitdiffhomepage
path: root/client/gtk.c
blob: ad5057b2290c6a53da33f68b574a42491ce5f47a (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

/*

  Copyright (c) 2009-2011 Samuel Lidén Borell <samuel@kodafritt.se>
 
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

#define _BSD_SOURCE 1
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <glib.h>
#include <assert.h>
#include <errno.h>

#include <locale.h>
#include <libintl.h>

#include <unistd.h> // For STDIN_FILENO

#include "../common/defines.h"
#include "backend.h"
#include "bankid.h"
#include "platform.h"
#include "misc.h"
#include "certutil.h"

#define _(string) gettext(string)
#define translatable(string) (string)

static const char *getErrorString(TokenError errorCode) {
    const char *s = NULL;
    switch (errorCode) {
        case TokenError_Success:
            return NULL;
        case TokenError_Unknown:
            s = translatable("An unknown error occurred");
            break;
        case TokenError_NotImplemented:
            s = translatable("Not implemented yet");
            break;
        case TokenError_MessageTooLong:
            s = translatable("Message to sign is too long");
            break;
        case TokenError_SignatureFailure:
            s = translatable("Failed to create signature");
            break;
        case TokenError_HostnameMismatch:
            s = translatable("Domain name mismatch");
            break;
        case TokenError_NoCertsMatched:
            s = translatable("The certificates didn't match");
            break;
        case TokenError_FailedToStoreCerts:
            s = translatable("Failed to store received certificates");
            break;
        /* File errors */
        case TokenError_FileNotReadable:
            s = translatable("The file could not be read");
            break;
        case TokenError_CantCreateFile:
            s = translatable("The file could not be saved");
            break;
        case TokenError_CantWriteToFile:
            s = translatable("The file could not be written to, even though it could be opened");
            break;
        case TokenError_BadFile:
            s = translatable("Invalid file format");
            break;
        case TokenError_BadPassword:
            s = translatable("Incorrect password");
            break;
        /* Smart card errors */
        case TokenError_BadPin:
            s = translatable("Incorrect PIN");
            break;
        /* Key generation errors */
        case TokenError_NoRandomState:
            s = translatable("No random state available (/dev/(u)random must exist)");
            break;
    }
    return gettext(s);
}


void platform_init(int *argc, char ***argv) {
    setlocale(LC_ALL, "");
    bindtextdomain(BINNAME, LOCALEDIR);
    textdomain(BINNAME);
    
    gtk_init(argc, argv);
}

void platform_leaveMainloop(void) {
    gtk_main_quit();
}

static PlatformPipeFunction* currentPipeFunction = NULL;

static gboolean pipeCallback(GIOChannel *source,
                             GIOCondition condition, gpointer data) {
    currentPipeFunction();
    return TRUE;
}

void platform_setupPipe(PlatformPipeFunction *pipeFunction) {
    assert(currentPipeFunction == NULL);
    currentPipeFunction = pipeFunction;
    
    GIOChannel *stdinChannel = g_io_channel_unix_new(STDIN_FILENO);
    g_io_add_watch(stdinChannel,
                   G_IO_IN | G_IO_HUP | G_IO_ERR, pipeCallback, NULL);
    g_io_channel_unref(stdinChannel);
}

void platform_mainloop(void) {
    gtk_main();
}

/* Sign/Authenticate dialog controls and state */
static GtkDialog *signDialog;
static GtkLabel *operationLabel;
static GtkTextView *signText;
static GtkComboBox *tokenCombo;
static GtkEntry *passwordEntry;
static GtkButton *signButton;
static GtkLabel *signButtonLabel;

static GtkWidget *signLabel;
static GtkWidget *signScroller;

static GtkInfoBar *info_bar;
static GtkLabel *info_label;

static GtkListStore *tokens;
static BackendNotifier *notifier;
static bool signDialogShown, signDialogMapped;

/* Password choice and key generation dialog */
static GtkDialog *keygenDialog;
static GtkEntry *keygenPasswordEntry;
static GtkEntry *keygenRepeatPasswordEntry;
static int keygenPasswordMinLen;
static int keygenPasswordMinDigits;
static int keygenPasswordMinNonDigits;
static bool keygenDialogShown;

static GtkDialog *activeDialog;

/**
 * Makes a dialog window stay above it's parent window.
 */
static void makeDialogTransient(GtkDialog *dialog, unsigned long parentWindowId) {
    bool transientOk = false;
    
    if (parentWindowId != PLATFORM_NO_WINDOW) {
#if GTK_CHECK_VERSION(2, 24, 0)
        GdkDisplay *display = gdk_display_get_default();
        GdkWindow *parent = gdk_x11_window_foreign_new_for_display(display,
            (Window)parentWindowId);
#else
        GdkWindow *parent = gdk_window_foreign_new((GdkNativeWindow)parentWindowId);
#endif
        if (parent != NULL) {
            gtk_widget_realize(GTK_WIDGET(dialog));
            GdkWindow *ourWindow = gtk_widget_get_window(GTK_WIDGET(dialog));
            if (ourWindow != NULL) {
                gdk_window_set_transient_for(ourWindow, parent);
                transientOk = true;
                //g_object_unref(G_OBJECT(ourWindow));
            }
            g_object_unref(G_OBJECT(parent));
        }
    }
    
    if (!transientOk) {
        gtk_window_set_keep_above(GTK_WINDOW(dialog), TRUE);
    }
}

static void showMessage(GtkMessageType type, const char *text) {
    GtkWidget *dialog = gtk_message_dialog_new(
        GTK_WINDOW(activeDialog), GTK_DIALOG_DESTROY_WITH_PARENT,
        type, GTK_BUTTONS_CLOSE, "%s", text);
    if (!activeDialog) {
        gtk_window_set_title(GTK_WINDOW(dialog), "FriBID");
    }
    gtk_dialog_run(GTK_DIALOG(dialog));
    gtk_widget_destroy(dialog);
}

static void hide_message(void) {
    gtk_widget_hide (GTK_WIDGET (info_bar));
}

static void show_inline_message(GtkMessageType message_type, const char *message) {
    gtk_widget_show(GTK_WIDGET (info_bar));
    gtk_info_bar_set_message_type(GTK_INFO_BAR (info_bar),
                                  message_type);
    gtk_label_set_text(info_label, message);
}

static void validateDialog(GtkWidget *ignored1, gpointer *ignored2) {
    gtk_widget_set_sensitive(GTK_WIDGET(signButton),
                             (gtk_combo_box_get_active(tokenCombo) != -1));
    hide_message();
    if (gtk_combo_box_get_active(tokenCombo) != -1) {
        GtkTreeIter iter = { .stamp = 0 };

        Token *token;
        token = NULL;

        if (gtk_combo_box_get_active_iter(tokenCombo, &iter)) {
            gtk_tree_model_get(GTK_TREE_MODEL(tokens), &iter,
                               1, &token, -1);
            gtk_widget_set_sensitive (GTK_WIDGET (passwordEntry), token_getStatus(token) != TokenStatus_NeedPIN);
            if (token_getStatus(token) == TokenStatus_NeedPIN) {
                show_inline_message (GTK_MESSAGE_INFO, _("Please enter PIN on pinpad"));
            }
        }
    }
}

static TokenError addTokenFile(const char *filename) {
    int fileLen;
    char *fileData;
    
    if (!platform_readFile(filename, &fileData, &fileLen))
        return TokenError_FileNotReadable;
    
    TokenError error = backend_addFile(notifier, fileData, fileLen,
                                       strdup(filename));
    
    guaranteed_memset(fileData, 0, fileLen);
    free(fileData);
    
    return error;
}

/**
 * Tells the backend to remove a file token.
 */
static void removeTokenFile(const char *filename) {
    GtkTreeIter iter = { .stamp = 0 };
    GtkTreeModel *model = GTK_TREE_MODEL(tokens);
    
    bool valid = gtk_tree_model_get_iter_first(model, &iter);
    while (valid) {
        char *displayName;
        char *otherFilename;
        Token *token;
        
        gtk_tree_model_get(model, &iter,
                           0, &displayName,
                           1, &token,
                           2, &otherFilename, -1);
        if (!strcmp(filename, otherFilename)) {
            // Remove this token
            token_remove(token);
            free(displayName);
            free(otherFilename);
            valid = gtk_list_store_remove(tokens, &iter);
        } else {
            valid = gtk_tree_model_iter_next(model, &iter);
        }
    }
}

/**
 * Selects the newest token. Since the token names usually start with
 * a date (at least file-based tokens from Swedbank) this function
 * simply uses strcmp().
 */
static void selectDefaultToken(GtkWidget *ignored1, gpointer *ignored2) {
    GtkTreeModel *model = GTK_TREE_MODEL(tokens);
    GtkTreeIter iter = { .stamp = 0 };
    
    if (signDialogMapped) return;
    signDialogMapped = true;
    
    if (gtk_tree_model_get_iter_first(model, &iter)) {
        char *newest = NULL;
        gint newest_index = -1;
        gint current_index = 0;
        do {
            char *current;
            gtk_tree_model_get(model, &iter, 0, &current, -1);
            
            if (!newest || strcmp(current, newest) > 0) {
                newest = current;
                newest_index = current_index;
            }
            current_index++;
        } while (gtk_tree_model_iter_next(model, &iter));
        
        if (newest) {
            gtk_tree_model_iter_nth_child(model, &iter, NULL, newest_index);
            gtk_combo_box_set_active_iter(tokenCombo, &iter);
            
            // Now give the password box focus
            gtk_widget_grab_focus(GTK_WIDGET(passwordEntry));
        }
    }
}

void platform_startSign(const char *url, const char *hostname, const char *ip,
                        unsigned long parentWindowId) {
    
    GtkBuilder *builder = gtk_builder_new();
    GError *error = NULL;
    GtkBox *box;
    GtkContainer *content_area;
    
    if (!gtk_builder_add_from_file(builder, UI_GTK_XML, &error)) {
        fprintf(stderr, BINNAME ": Failed to open GtkBuilder XML: %s\n", error->message);
        g_error_free(error);
        return;
    }
    
    activeDialog = signDialog = GTK_DIALOG(gtk_builder_get_object(builder, "dialog_sign"));
    
    signButton = GTK_BUTTON(gtk_builder_get_object(builder, "button_sign"));
    signButtonLabel = GTK_LABEL(gtk_builder_get_object(builder, "buttonlabel_sign"));
    
    operationLabel = GTK_LABEL(gtk_builder_get_object(builder, "header_op"));
    gtk_label_set_text(GTK_LABEL(gtk_builder_get_object(builder, "header_domain")),
                       hostname);
    
    signLabel = GTK_WIDGET(gtk_builder_get_object(builder, "sign_label"));
    signScroller = GTK_WIDGET(gtk_builder_get_object(builder, "sign_scroller"));
    signText = GTK_TEXT_VIEW(gtk_builder_get_object(builder, "sign_text"));
    platform_setMessage(NULL);
    
    // Create a GtkListStore of (displayname, token, filename) tuples
    tokens = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_STRING);
    gtk_tree_sortable_set_sort_column_id(GTK_TREE_SORTABLE(tokens), 0, GTK_SORT_ASCENDING);
    
    tokenCombo = GTK_COMBO_BOX(gtk_builder_get_object(builder, "signature_combo"));
    gtk_combo_box_set_model(tokenCombo, GTK_TREE_MODEL(tokens));
    
    GtkCellRenderer *renderer = gtk_cell_renderer_text_new();
    gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(tokenCombo),
                               renderer, TRUE);
    gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(tokenCombo),
                                   renderer, "text", 0, (char *)NULL);
    
    // Used to dim the "Sign" button when no signature has been selected
    g_signal_connect(G_OBJECT(tokenCombo), "changed",
                     G_CALLBACK(validateDialog), NULL);
    
    passwordEntry = GTK_ENTRY(gtk_builder_get_object(builder, "password_entry"));

    info_bar = GTK_INFO_BAR(gtk_info_bar_new());
    info_label = GTK_LABEL(gtk_label_new(""));

    content_area = GTK_CONTAINER (gtk_info_bar_get_content_area(GTK_INFO_BAR (info_bar)));
    gtk_container_add(GTK_CONTAINER(content_area), GTK_WIDGET (info_label));
    gtk_widget_show(GTK_WIDGET(info_label));

    box = GTK_BOX(gtk_builder_get_object(builder, "vbox1"));
    gtk_box_pack_end(box, GTK_WIDGET (info_bar), TRUE, FALSE, 2);
    
    makeDialogTransient(signDialog, parentWindowId);
    
    validateDialog(NULL, NULL);
    
    g_signal_connect(G_OBJECT(signDialog), "map-event",
                     G_CALLBACK(selectDefaultToken), NULL);
    
    gtk_window_set_modal(GTK_WINDOW(signDialog), TRUE);
    signDialogShown = false;
    signDialogMapped = false;
}

void platform_endSign(void) {
    // Remove all manually added tokens
    GtkTreeModel *model = GTK_TREE_MODEL(tokens);
    GtkTreeIter iter = { .stamp = 0 };
    
    bool valid = gtk_tree_model_get_iter_first(model, &iter);
    while (valid) {
        char *displayName, *filename;
        Token *token;
        
        gtk_tree_model_get(model, &iter,
                           0, &displayName,
                           1, &token,
                           2, &filename, -1);
        token_remove(token);
        free(displayName);
        free(filename);
        valid = gtk_tree_model_iter_next(model, &iter);
    }
    
    gtk_widget_destroy(GTK_WIDGET(signDialog));
    g_object_unref(tokens);
}

void platform_setMessage(const char *message) {
    if (message == NULL) {
        gtk_widget_hide(signLabel);
        gtk_widget_hide(signScroller);
        
        gtk_window_set_title(GTK_WINDOW(signDialog), _("Identification"));
        gtk_label_set_label(GTK_LABEL(operationLabel), _("<big><b>Prove identity to: </b></big>"));
        gtk_label_set_label(signButtonLabel, _("_Prove identity"));
    } else {
        GtkTextBuffer *textBuffer = gtk_text_view_get_buffer(signText);
        gtk_text_buffer_set_text(textBuffer, message, strlen(message));
        
        gtk_widget_show(signLabel);
        gtk_widget_show(signScroller);
        
        gtk_window_set_title(GTK_WINDOW(signDialog), _("Signing"));
        gtk_label_set_label(GTK_LABEL(operationLabel), _("<big><b>Create signature on: </b></big>"));
        gtk_label_set_label(GTK_LABEL(signButtonLabel), _("_Sign"));
    }
}

/**
 * Sets the backend notifier to use for receiving token insertion/removal
 * events and manually requesting token files to be added.
 */
void platform_setNotifier(BackendNotifier *notifierToUse) {
    notifier = notifierToUse;
}

/**
 * Add  from the key directories
 */
void platform_addKeyDirectories(void) {
    char** paths;
    size_t len;
    
    // Look for P12s in ~/cbt and ~/.cbt
    platform_keyDirs(&paths, &len);
    for (size_t i = 0; i <= len; i++) {
        PlatformDirIter *dir = platform_openKeysDir(paths[i]);
        if (dir) {
            while (platform_iterateDir(dir)) {
                char *filename = platform_currentPath(dir);
                
                if (!strstr(filename, ".tmp")) {
                    addTokenFile(filename);
                }
                
                free(filename);
            }
            platform_closeDir(dir);
        }
        free(paths[i]);
    }
}

static gboolean addTokenFunc(gpointer ptr) {
    Token *token = (Token*)ptr;
    GtkTreeIter iter = { .stamp = 0 };
    const char *filename = (char *)token_getTag(token);
    
    // Check for errors
    TokenError error = token_getLastError(token);
    if (error) {
        platform_showError(error);
        return FALSE;
    }
    
    // Add token
    gtk_list_store_insert_with_values(tokens, &iter, -1,
                                      0, token_getDisplayName(token),
                                      1, token,
                                      2, filename, -1);
    
    if (filename) {
        // The token was manually added. Select it.
        gtk_combo_box_set_active_iter(tokenCombo, &iter);
    }
    
    return FALSE;
}

static gboolean removeTokenFunc(gpointer ptr) {
    Token *token = (Token*)ptr;
    GtkTreeModel *model = GTK_TREE_MODEL(tokens);
    GtkTreeIter iter = { .stamp = 0 };
    
    bool valid = gtk_tree_model_get_iter_first(model, &iter);
    while (valid) {
        Token *listToken;
        gtk_tree_model_get(model, &iter,
                           1, &listToken, -1);
        valid = (listToken == token ?
            gtk_list_store_remove(tokens, &iter) :
            gtk_tree_model_iter_next(model, &iter));
    }
    
    return FALSE;
}

/**
 * Adds a token to the list of identity tokens. This function should be called
 * after platform_startSign.
 */
void platform_addToken(Token *token) {
    g_idle_add_full(G_PRIORITY_HIGH, addTokenFunc, token, NULL);
}

/**
 * Removes a token from the list of identity tokens. This function should only
 * be called after platform_startSign has been called.
 */
void platform_removeToken(Token *token) {
    g_idle_add_full(G_PRIORITY_HIGH, removeTokenFunc, token, NULL);
}


static void selectExternalFile(void) {
    TokenError error = TokenError_Success;
    GtkFileChooser *chooser = GTK_FILE_CHOOSER(gtk_file_chooser_dialog_new(
            _("Select external identity file"), GTK_WINDOW(signDialog),
            GTK_FILE_CHOOSER_ACTION_OPEN,
            _("_Cancel"), GTK_RESPONSE_CANCEL,
            _("_Open"), GTK_RESPONSE_ACCEPT,
            (char *)NULL));
    activeDialog = GTK_DIALOG(chooser);
    
    while (gtk_dialog_run(GTK_DIALOG(chooser)) == GTK_RESPONSE_ACCEPT) {
        gchar *filename = gtk_file_chooser_get_filename(chooser);
        
        removeTokenFile(filename);
        
        // Add an item to the token list and select it
        certutil_clearErrorString();
        error = addTokenFile(filename);
        
        g_free(filename);
        if (error) platform_showError(error);
        else break;
    }
    
    activeDialog = signDialog;
    gtk_widget_destroy(GTK_WIDGET(chooser));
}

#define RESPONSE_OK       10
#define RESPONSE_CANCEL   20
#define RESPONSE_EXTERNAL 30

/**
 * Waits for the user to fill in the dialog, and loads the P12 file for
 * the selected subject.
 */
bool platform_sign(Token **token, char *password, int password_maxlen) {
    guint response;
    certutil_clearErrorString();

    // Restrict the password to the length of the preallocated
    // password buffer
    gtk_entry_set_max_length(passwordEntry, password_maxlen-1);
    
    if (!signDialogShown) {
        gtk_widget_show(GTK_WIDGET(signDialog));
        signDialogShown = true;
    }
    
    while ((response = gtk_dialog_run(signDialog)) == RESPONSE_EXTERNAL) {
        // User pressed "External file..."
        selectExternalFile();
    }
    
    if (response == RESPONSE_OK) {
        // User pressed "Log in" or "Sign"
        GtkTreeIter iter = { .stamp = 0 };
        
        *token = NULL;
        
        if (gtk_combo_box_get_active_iter(tokenCombo, &iter)) {
            gtk_tree_model_get(GTK_TREE_MODEL(tokens), &iter,
                               1, token, -1);
        }

        // Copy the password to the secure buffer
        strncpy(password, gtk_entry_get_text(passwordEntry), password_maxlen-1);
        // Be sure to terminate this under all circumstances
        password[password_maxlen-1] = '\0';
        return true;
    } else {
        // User pressed cancel or closed the dialog
        return false;
    }
}


void platform_startChoosePassword(const char *name, unsigned long parentWindowId) {
    
    GtkBuilder *builder = gtk_builder_new();
    GError *error = NULL;
    
    if (!gtk_builder_add_from_file(builder, UI_GTK_XML, &error)) {
        fprintf(stderr, BINNAME ": Failed to open GtkBuilder XML: %s\n", error->message);
        g_error_free(error);
        return;
    }
    
    gtk_label_set_text(GTK_LABEL(gtk_builder_get_object(builder, "label_keygen_name")),
                       name);
    
    keygenPasswordEntry = GTK_ENTRY(gtk_builder_get_object(builder, "entry_keygen_password"));
    keygenRepeatPasswordEntry = GTK_ENTRY(gtk_builder_get_object(builder, "entry_keygen_repeat"));
    
    activeDialog = keygenDialog = GTK_DIALOG(gtk_builder_get_object(builder, "dialog_keygen"));
    
    makeDialogTransient(keygenDialog, parentWindowId);
    
    gtk_window_set_modal(GTK_WINDOW(keygenDialog), TRUE);
    keygenDialogShown = false;
}

void platform_setPasswordPolicy(int minLength, int minNonDigits, int minDigits) {
    keygenPasswordMinLen = minLength;
    keygenPasswordMinNonDigits = minNonDigits;
    keygenPasswordMinDigits = minDigits;
}

void platform_endChoosePassword(void) {
    gtk_widget_destroy(GTK_WIDGET(keygenDialog));
    
}

static bool weakPassword(int length, int minimum, const char *format) {
    if (length < minimum) {
        char *error = rasprintf(format, minimum);
        showMessage(GTK_MESSAGE_ERROR, error);
        g_free(error);
        return TRUE;
    }
    return FALSE;
}

bool platform_choosePassword(char *password, long password_maxlen) {
    // Restrict the password to the length of the preallocated
    // password buffer
    gtk_entry_set_max_length(keygenPasswordEntry, password_maxlen-1);
    gtk_entry_set_max_length(keygenRepeatPasswordEntry, password_maxlen-1);
    
    if (!keygenDialogShown) {
        gtk_widget_show(GTK_WIDGET(keygenDialog));
        keygenDialogShown = true;
    }
    
    for (;;) {
        gint response = gtk_dialog_run(keygenDialog);
        
        if (response == GTK_RESPONSE_OK) {
            // Check if the passwords match
            
            // TODO disable the button when passwords don't match and show
            //      an explanation in an info bar, instead of showing an
            //      error dialog
            if (strcmp(gtk_entry_get_text(keygenPasswordEntry),
                       gtk_entry_get_text(keygenRepeatPasswordEntry))) {
                // Did not match
                showMessage(GTK_MESSAGE_ERROR, _("The passwords don't match!"));
                continue;
            }
            
            // Check password policy
            const char *pwtext = gtk_entry_get_text(keygenPasswordEntry);
            int pwlen = g_utf8_strlen(pwtext, -1);
            
            int numDigits = 0;
            int numNonDigits = 0;
            const char *c = pwtext;
            while (*c) {
                if (*c >= '0' && *c <= '9') numDigits++;
                else numNonDigits++;
                c = g_utf8_find_next_char(c, NULL);
            }
            
            if (weakPassword(pwlen, keygenPasswordMinLen,
                    ngettext("The password must be at least one character",
                             "The password must be at least %d characters",
                             keygenPasswordMinLen)) ||
                weakPassword(numNonDigits, keygenPasswordMinNonDigits,
                    ngettext("The password must have at least one character that is not a digit",
                             "The password must have at least %d characters that are not digits",
                             keygenPasswordMinNonDigits)) ||
                weakPassword(numDigits, keygenPasswordMinDigits,
                    ngettext("The password must have at least one digit",
                             "The password must have at least %d digits",
                             keygenPasswordMinDigits))) {
                // Not OK
                continue;
            }
            
            // Copy the password to the secure buffer
            strncpy(password, pwtext, password_maxlen-1);
            // Be sure to terminate this under all circumstances
            password[password_maxlen-1] = '\0';
            return true;
        } else {
            // User pressed cancel or closed the dialog
            return false;
        }
    }
}

void platform_focusPassword() {
    gtk_widget_grab_focus(GTK_WIDGET(passwordEntry));
}

void platform_showError(TokenError error) {
    assert(error != TokenError_Success);
    
    int lastErrno = errno;
    const char *text = getErrorString(error);
    char *longText;
    
    switch (error) {
        case TokenError_FileNotReadable:
        case TokenError_CantCreateFile:
            longText = rasprintf("%s\n\n%s", text, g_strerror(lastErrno));
            showMessage(GTK_MESSAGE_ERROR, longText);
            g_free(longText);
            break;
        default:
            if (certutil_getErrorString()) {
                longText = rasprintf("%s\n\n%s", text, certutil_getErrorString());
                showMessage(GTK_MESSAGE_ERROR, longText);
                g_free(longText);
            } else {
                showMessage(GTK_MESSAGE_ERROR, text);
            }
            break;
    }
}