pwman

Check-in [c14cf350df]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Move src and doc files to top directory
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk | manualheaven
Files: files | file ages | folders
SHA3-256: c14cf350df69a4d3af42c5005298b4d2324a00ea86df20d61ff6a3df46489aae
User & Date: base@atomicules.co.uk 2014-05-15 21:36:21
Context
2014-05-15
21:47
Change gitignore now moving away from autohell check-in: 5e56b19a49 user: base@atomicules.co.uk tags: manualheaven, trunk
21:36
Move src and doc files to top directory check-in: c14cf350df user: base@atomicules.co.uk tags: manualheaven, trunk
21:35
Remove Autohell junk check-in: 80b7cd3685 user: base@atomicules.co.uk tags: manualheaven, trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Added actions.c.































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWman - Password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <ui.h>
#include <pwman.h>
#include <gnupg.h>

extern Pw * uilist_get_highlighted_item();
extern PWList * uilist_get_highlighted_sublist();
extern PWList * pwlist_new(char*);
extern PWSearchResult * uilist_get_highlighted_searchresult();
extern char *pwgen_ask();

int disp_h = 15, disp_w = 60;
extern int curitem;
extern WINDOW *bottom;

int
action_list_add_pw()
{
	Pw *pw;
	InputField fields[] = {
		{"Name:\t", NULL, STRING_MEDIUM, STRING},
		{"Host:\t", NULL, STRING_MEDIUM, STRING},
		{"User:\t", NULL, STRING_MEDIUM, STRING},
		{"Password:\t", NULL, STRING_SHORT, STRING, pwgen_ask},
		{"Launch Command:\t", NULL, STRING_LONG, STRING}
	};
	int i, x;

	pw = pwlist_new_pw(); 
	ui_statusline_ask_str(fields[0].name, pw->name, STRING_MEDIUM);
	ui_statusline_ask_str(fields[1].name, pw->host, STRING_MEDIUM);
	ui_statusline_ask_str(fields[2].name, pw->user, STRING_MEDIUM);
/*
		int x = strlen(msg) + 5;

	if(input == NULL){
		input = malloc(len);
	}
	statusline_clear();
	statusline_msg(msg);

	echo();
	show_cursor();
	mvwgetnstr(bottom, 1, x, input, len);
	noecho();
	hide_cursor();

	statusline_clear();*/

	ui_statusline_ask_str_with_autogen(fields[3].name, pw->passwd, STRING_SHORT, fields[3].autogen, 0x07);
/*	statusline_msg(fields[3].name);
	x = strlen(fields[3].name) + 5;

	if((i = getch()) == 0x07){
		pw->passwd = fields[3].autogen();
	} else {
		echo();
		show_cursor();
		mvwgetnstr(bottom, 1, x, pw->passwd, PASS_LEN);
		mvwaddch(bottom, 1, x, i);
		wmove(bottom, 1, x+1);
		noecho();
		hide_cursor();
		statusline_clear();
	}*/
	
	ui_statusline_ask_str(fields[4].name, pw->launch, STRING_LONG);
	
	fields[0].value = pw->name;
	fields[1].value = pw->host;
	fields[2].value = pw->user;
	fields[3].value = pw->passwd;
	fields[4].value = pw->launch;

	i = action_yes_no_dialog(fields, (sizeof(fields)/sizeof(InputField)), NULL, "Add this entry");

	if(i){
		pwlist_add_ptr(current_pw_sublist, pw);
		ui_statusline_msg("New password added");
	} else {
		pwlist_free_pw(pw);
		ui_statusline_msg("New password cancelled");
	}

	uilist_refresh();
}

int
action_edit_pw(Pw *pw)
{
	InputField fields[] = {
		{"Name:\t", NULL, STRING_MEDIUM, STRING},
		{"Host:\t", NULL, STRING_MEDIUM, STRING},
		{"User:\t", NULL, STRING_MEDIUM, STRING},
		{"Password:\t", NULL, STRING_SHORT, STRING, pwgen_ask},
		{"Launch Command:\t", NULL, STRING_LONG, STRING}
	};

	if(pw == NULL){
		return -1;
	}
	/*
	 * Get specified password
	 */

	fields[0].value = pw->name;
	fields[1].value = pw->host;
	fields[2].value = pw->user;
	fields[3].value = pw->passwd;
	fields[4].value = pw->launch;

	/*
	 * initialize the info window
	 */

	action_input_dialog(fields, (sizeof(fields)/sizeof(InputField)), "Edit Password");
}

int 
action_list_rename()
{
	Pw* curpw;
	PWList* curpwl;
	char *new_name;

	new_name = malloc(STRING_MEDIUM);

	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			curpw = uilist_get_highlighted_item();
			if(curpw){
				ui_statusline_ask_str("New Name", new_name, STRING_MEDIUM);
				if(strlen(new_name) > 0) {
					pwlist_rename_item(curpw, new_name);
				}
			}
			break;
		case PW_SUBLIST:
			curpwl = uilist_get_highlighted_sublist();
			if(curpwl){
				ui_statusline_ask_str("New Sublist Name", new_name, STRING_MEDIUM);
				if(strlen(new_name) > 0) {
					pwlist_rename_sublist(curpwl, new_name);
				}
			}
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}

	uilist_refresh();
}

int
action_edit_options()
{
	InputField fields[] = {
		{"GnuPG Path:\t", options->gpg_path, STRING_LONG, STRING},
		{"GnuPG ID:\t", options->gpg_id, STRING_LONG, STRING},
		{"Password File:\t", options->password_file, STRING_LONG, STRING},
		{"Passphrase Timeout(in minutes):\t", &options->passphrase_timeout, STRING_SHORT, INT}
	};

	action_input_dialog(fields, (sizeof(fields)/sizeof(InputField)), "Edit Preferences");

	write_options = TRUE;
}

int 
action_input_dialog_draw_items(WINDOW* dialog_win, InputField *fields, 
		int num_fields, char *title, char *msg)
{
	int i, h = 0;

	wclear(dialog_win);
	
	box(dialog_win, 0, 0);

	if(title){
		wattron(dialog_win, A_BOLD);
		i = strlen(title);
		h += 2;
		mvwaddstr(dialog_win, h, (disp_w - i)/2, title);
		wattroff(dialog_win, A_BOLD);
	}

	/* loop through fields */
	for(i = 0; i < num_fields; i++){
		h += 2;
		if(fields[i].type == STRING){
			mvwprintw(dialog_win, h, 3,
				"%d - %s %s", (i+1), fields[i].name, (char*)fields[i].value);
		} else if(fields[i].type == INT){
			mvwprintw(dialog_win, h, 3,
				"%d - %s %d", (i+1), fields[i].name, *((int*)fields[i].value) );
		} else if(fields[i].type == INFORMATION){
			mvwprintw(dialog_win, h, 3,
				"%d - %s", (i+1), fields[i].name);
		}
	}

	wattron(dialog_win, A_BOLD);

	if(msg){
		i = strlen(msg);
		h += 2;
		mvwaddstr(dialog_win, h, (disp_w - i)/2, msg);
	}

	wattroff(dialog_win, A_BOLD);

	/*
	 * do final stuff the put all together
	 */
	wrefresh(dialog_win);
}

int 
action_input_dialog(InputField *fields, int num_fields, char *title)
{
	int ch, i;
	char *ret;
	WINDOW *dialog_win;
	char msg[] = "(press 'q' to return to list)";
	char msg2[80];
	/*
	 * initialize the info window
	 */
	if(title){
		disp_h = ((num_fields+2) * 2) + 3;
	} else {
		disp_h = ((num_fields+1) * 2) + 3;
	}
	
	dialog_win = newwin(disp_h, disp_w, (LINES - disp_h)/2, (COLS - disp_w)/2);
	keypad(dialog_win, TRUE);

	action_input_dialog_draw_items(dialog_win, fields, num_fields, title, msg);
	/*
	 * actions loop
	 */
	while((ch = wgetch(dialog_win)) != 'q'){
		if(!options->readonly) {
			if( (ch >= '1') && (ch <= NUM_TO_CHAR(num_fields)) ){
				i = CHAR_TO_NUM(ch);
				if(fields[i].autogen != NULL){
					fields[i].value = (char*)ui_statusline_ask_str_with_autogen(
								fields[i].name, (char*)fields[i].value, 
								fields[i].max_length, fields[i].autogen, 0x07); 
				} else if(fields[i].type == STRING){
					fields[i].value = (char*)ui_statusline_ask_str(fields[i].name, 
								(char*)fields[i].value, fields[i].max_length);
				} else if(fields[i].type == INT){
					ui_statusline_ask_num(fields[i].name, (int*)fields[i].value);
				} else if(fields[i].type == INFORMATION){
					// Easy, do nothing!
				}
				action_input_dialog_draw_items(dialog_win, fields, num_fields, title, msg);
			} else if(ch == 'l'){
				delwin(dialog_win);
				action_list_launch();
				break;
			}	
		} else {
			statusline_readonly();
		}
	}
	/*
	 * clean up
	 */
	delwin(dialog_win);
	uilist_refresh();
}

int 
action_input_gpgid_dialog(InputField *fields, int num_fields, char *title)
{
	int i, valid_id;
	int ch = '1', first_time = 1;
	char *ret;
	WINDOW *dialog_win;
	char msg[] = "(press 'q' when export recipient list is complete)";
	char msg2[80];
	/*
	 * initialize the info window
	 */
	disp_h = ((num_fields+2) * 2) + 3;
	dialog_win = newwin(disp_h, disp_w, (LINES - disp_h)/2, (COLS - disp_w)/2);
	keypad(dialog_win, TRUE);

	action_input_dialog_draw_items(dialog_win, fields, num_fields, title, msg);

	/*
	 * actions loop - ignore read only as not changing main state
	 */
	while(first_time || ((ch = wgetch(dialog_win)) != 'q')){
		// On first loop, drop straight into recipient 1
		first_time = 0;

		if( (ch >= '1') && (ch <= NUM_TO_CHAR(num_fields)) ){
			i = CHAR_TO_NUM(ch);
			fields[i].value = (char*)ui_statusline_ask_str(fields[i].name, 
								(char*)fields[i].value, fields[i].max_length);
			
			// Now verify it's a valid recipient
			if(strlen(fields[i].value)) {
				valid_id = gnupg_check_id(fields[i].value);
				if(valid_id == 0) {
					// Good, valid id
				} else {
					// Invalid id. Warn and blank
					if(valid_id == -2) {
					   snprintf(msg2, 80, "Key expired for '%s'", (char*)fields[i].value);
					} else {
					   snprintf(msg2, 80, "Invalid recipient '%s'", (char*)fields[i].value);
					}
					ui_statusline_msg(msg2);
					snprintf(fields[i].value, STRING_LONG, "");
				}

				// Redraw display
				action_input_dialog_draw_items(dialog_win, fields, num_fields, title, msg);
			}
		}
	}

	/*
	 * clean up
	 */
	delwin(dialog_win);
	uilist_refresh();
}

int 
action_yes_no_dialog(InputField *fields, int num_fields, char *title, char *question)
{
	int ch, i;
	char *ret;
	WINDOW *dialog_win;

	/*
	 * initialize the info window
	 */
	if(title){
		disp_h = ((num_fields+2) * 2) + 3;
	} else {
		disp_h = ((num_fields+1) * 2) + 3;
	}
	
	dialog_win = newwin(disp_h, disp_w, (LINES - disp_h)/2, (COLS - disp_w)/2);
	keypad(dialog_win, TRUE);

	action_input_dialog_draw_items(dialog_win, fields, num_fields, title, NULL);
	
	i = ui_statusline_yes_no(question, 1);

	/*
	 * clean up
	 */
	delwin(dialog_win);
	uilist_refresh();

	return i;
}

int
action_list_add_sublist()
{
	char *name;
	PWList *sublist, *iter;

	name = malloc(STRING_MEDIUM);
	ui_statusline_ask_str("Sublist Name:", name, STRING_MEDIUM);
	for(iter = current_pw_sublist->sublists; iter != NULL; iter = iter->next){
		if( strcmp(iter->name, name) == 0){
			free(name);
			return -1;
		}
	}
	sublist = pwlist_new(name);

	pwlist_add_sublist(current_pw_sublist, sublist);
	uilist_refresh();
}

int
action_list_at_top_level()
{
	if(current_pw_sublist->parent){
		action_list_up_one_level();
		uilist_refresh();
		return 0;
	} else {
		return 1;
	}
}

int
action_list_select_item()
{
	Pw* curpw;
	PWList* curpwl;
	PWSearchResult* cursearch;

	// Are they searching, or in normal mode?
	if(search_results != NULL) {
		cursearch = uilist_get_highlighted_searchresult();
		curpwl = cursearch->sublist;
		curpw = cursearch->entry;

		if(curpw){
			action_edit_pw(curpw);
		} else if(curpwl){
			// Quite out of searching
			search_remove();

			// Now display the selected sublist
			current_pw_sublist = curpwl;
			uilist_refresh();
		}
	} else {
		switch(uilist_get_highlighted_type()){
			case PW_ITEM:
				curpw = uilist_get_highlighted_item();
				if(curpw){
					action_edit_pw(curpw);
				}
				break;
			case PW_SUBLIST:
				curpwl = uilist_get_highlighted_sublist();
				if(curpwl){
					current_pw_sublist = curpwl;
					uilist_refresh();
				}
				break;
			case PW_UPLEVEL:
				action_list_up_one_level();
				break;
			case PW_NULL:
			default:
				/* do nothing */
				break;
		}
	}
}

int
action_list_delete_item()
{
	Pw* curpw;
	PWList* curpwl;
	int i;
	char str[STRING_LONG];
	
	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			curpw = uilist_get_highlighted_item();
			if(curpw){
				snprintf(str, STRING_LONG, "Really delete \"%s\"", curpw->name);
				i = ui_statusline_yes_no(str, 0);
				if(i){
					pwlist_delete_pw(current_pw_sublist, curpw);
					ui_statusline_msg("Password deleted");
				} else {
					ui_statusline_msg("Password not deleted");
				}	
			}
			break;
		case PW_SUBLIST:
			curpwl = uilist_get_highlighted_sublist();
			if(curpwl){
				snprintf(str, STRING_LONG, "Really delete Sublist \"%s\"", curpwl->name);
				i = ui_statusline_yes_no(str, 0);
				if(i){
					pwlist_delete_sublist(curpwl->parent, curpwl);
					ui_statusline_msg("Password Sublist deleted");
				} else {
					ui_statusline_msg("Password not deleted");
				}
			}
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}
	uilist_refresh();
}

int
action_list_move_item()
{
	Pw* curpw;
	PWList *curpwl, *iter;
	int i;
	char str[STRING_LONG];
	char answer[STRING_MEDIUM];

	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			curpw = uilist_get_highlighted_item();
			if(curpw){
				while(1){
					snprintf(str, STRING_LONG, "Move \"%s\" to where?", curpw->name);
					ui_statusline_ask_str(str, answer, STRING_MEDIUM);
					
					/* if user just enters nothing do nothing */
					if(answer[0] == 0){
						return 0;
					}
					
					for(iter = current_pw_sublist->sublists; iter != NULL; iter = iter->next){
						if( strcmp(iter->name, answer) == 0 ){
							pwlist_detach_pw(current_pw_sublist, curpw);
							pwlist_add_ptr(iter, curpw);
							uilist_refresh();
							return 0;
						}
					}
					ui_statusline_msg("Sublist does not exist, try again");
					getch();
				}
			}
			break;
		case PW_SUBLIST:
			curpwl = uilist_get_highlighted_sublist();
			if(curpwl){
				while(1){
					snprintf(str, STRING_LONG, "Move sublist \"%s\" to where?", curpwl->name);
					ui_statusline_ask_str(str, answer, STRING_MEDIUM);
					
					/* if user just enters nothing, do nothing */
					if(answer[0] == 0){
						return 0;
					}
					if( strcmp(answer, curpwl->name) == 0 ){
						return 0;
					}

					for(iter = current_pw_sublist->sublists; iter != NULL; iter = iter->next){
						if( strcmp(iter->name, answer) == 0 ){
							pwlist_detach_sublist(current_pw_sublist, curpwl);
							pwlist_add_sublist(iter, curpwl);
							uilist_refresh();
							return 0;
						}
					}
					ui_statusline_msg("Sublist does not exist, try again");
					getch();
				}
			}
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}
}

int
action_list_move_item_up_level()
{
	Pw* curpw;
	PWList *curpwl, *iter;
	int i;
	char str[STRING_LONG];
	char answer[STRING_MEDIUM];

	// Do nothing if searching
	if(search_results != NULL) {
		return;
	}

	// Do the right thing based on type
	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			curpw = uilist_get_highlighted_item();
			if(curpw && current_pw_sublist->parent){
				pwlist_detach_pw(current_pw_sublist, curpw);
				pwlist_add_ptr(current_pw_sublist->parent, curpw);
				uilist_refresh();
			}
			break;
		case PW_SUBLIST:
			curpwl = uilist_get_highlighted_sublist();
			if(curpwl && current_pw_sublist->parent){
				pwlist_detach_sublist(current_pw_sublist, curpwl);
				pwlist_add_sublist(current_pw_sublist->parent, curpwl);
				uilist_refresh();
			}
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}
}

int
action_list_up_one_level()
{
	/* move up one sublist */
	if(current_pw_sublist->parent){
		current_pw_sublist = current_pw_sublist->parent;
		uilist_refresh();
	}
}
	
int
action_list_export()
{
	Pw* curpw;
	PWList *curpwl;

	debug("list_export: enter switch");
	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			debug("list_export: is a pw");
			curpw = uilist_get_highlighted_item();
			if(curpw){
				pwlist_export_passwd(curpw);
			}
			break;
		case PW_SUBLIST:
			debug("list_export: is a pwlist");
			curpwl = uilist_get_highlighted_sublist();
			if(curpwl){
				pwlist_export_list(curpwl);
			}
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}
}

void _create_information_field(char* name, InputField* field)
{
	field->name = name;
	field->value = NULL;
	field->max_length = 0;
	field->type = INFORMATION;
}

int
action_list_locate()
{
	int depth = 0, count = 0;
	char* currentName;
	InputField* fields;
	Pw* curpw = NULL;
	PWList *curpwl = NULL;
	PWList *parent = NULL;
	PWSearchResult* cursearch;

	if(search_results != NULL) {
		cursearch = uilist_get_highlighted_searchresult();
		curpwl = cursearch->sublist;
		curpw = cursearch->entry;

		if(curpw) {
			parent = curpwl;
		} else {
			parent = curpwl->parent;
		}
	} else {
		parent = current_pw_sublist;
		switch(uilist_get_highlighted_type()){
			case PW_ITEM:
				curpw = uilist_get_highlighted_item();
				break;
			case PW_SUBLIST:
				curpwl = uilist_get_highlighted_sublist();
				break;
			default:
				/* do nothing */
				break;
		}
	}

	if(curpw) {
		currentName = curpw->name;
		depth = 1;
	} else if(curpwl) {
		currentName = curpwl->name;
		depth = 1;
	}

	// Figure out how many parents we have
	curpwl = parent;
	while(curpwl){
		curpwl = curpwl->parent;
		depth++;
	}
	count = depth;

	// Now grab their names
	fields = calloc(sizeof(InputField), depth);
	if(currentName){
		depth--;
		_create_information_field(currentName, &fields[depth]);
	}
	curpwl = parent;
	while(curpwl){
		depth--;
		_create_information_field(curpwl->name, &fields[depth]);
		curpwl = curpwl->parent;
	}

	// Have it rendered
	action_input_dialog(fields, count, "Location of Item");

	// All done, tidy up
	free(fields);
}

int
action_list_launch()
{
	int i;
	Pw* curpw;
	char msg[STRING_LONG];

	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			debug("list_launch: is a pw");
			curpw = uilist_get_highlighted_item();
			if(curpw){
				i = launch(curpw);
				snprintf(msg, STRING_LONG, "Application exited with code %d", i);
				ui_statusline_msg(msg);
			}
			break;
		case PW_SUBLIST:
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}
}

int
action_list_read_file()
{
	pwlist_free_all();
	if(pwlist_read_file() != 0){
		pwlist = pwlist_new("Main");
		current_pw_sublist = pwlist;
	}
	uilist_refresh();
	return -1;
}

int
action_list_move_item_up()
{
	Pw* curpw;
	PWList *curpwl;
	int worked = 0;

	// Do nothing if searching
	if(search_results != NULL) {
		return;
	}

	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			curpw = uilist_get_highlighted_item();
			worked = pwlist_change_item_order(curpw, current_pw_sublist, 1);
			break;
		case PW_SUBLIST:
			curpwl = uilist_get_highlighted_sublist();
			worked = pwlist_change_list_order(curpwl, 1);
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}

	if(worked) {
		uilist_up();
	}
}

int 
action_list_move_item_down()
{
	Pw* curpw;
	PWList *curpwl;
	int worked = 0;

	// Do nothing if searching
	if(search_results != NULL) {
		return;
	}

	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			curpw = uilist_get_highlighted_item();
			worked = pwlist_change_item_order(curpw, current_pw_sublist, 0);
			break;
		case PW_SUBLIST:
			curpwl = uilist_get_highlighted_sublist();
			worked = pwlist_change_list_order(curpwl, 0);
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}

	if(worked) {
		uilist_down();
	}
}

Added convert_pwdb.c.













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  Convert_PWDB - Convert old pwman files into the new format
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#define STR_LEN 255
#define CONVERT_DB_PACKAGE "Convert_PWDB"
#define CONVERT_DB_VERSION "0.1.0"

#include <libxml/parser.h>
#include <stdlib.h>
#include <stdio.h>
#include <pwman.h>

static void show_version();
static void show_usage(char*);

struct ConvertDB_Options {
	char *gpg_id;
	char *infile;
	char *outfile;
} convertdb_options;

int export = 0;

void
debug(char *fmt, ... )
{
#ifdef DEBUG
	va_list ap;
	int d, c;
	char *s;

	fputs("Convert_PWDB Debug% ", stderr);
	
	va_start(ap, fmt);
	while(*fmt){
		if(*fmt == '%'){
			switch(*++fmt){
				case 's': 	/* string */
					s = va_arg(ap, char*);
					fputs(s, stderr);
					break;
				case 'd':	/* int */
					d = va_arg(ap, int);
					fprintf(stderr, "%d", d);
					break;
				case 'c':	/* char */
					c = va_arg(ap, int);
					fputc(c, stderr);
					break;
				default:
					fputc('%', stderr);
					fputc(*fmt, stderr);
					break;
			}
		} else {
			fputc(*fmt, stderr);
		}
		*fmt++;
	}
	va_end(ap);
	fputc('\n', stderr);
#endif
}

PWList *
new_pwlist(char *name)
{
	PWList *new;
	new = malloc( sizeof(PWList) );
	new->name = malloc(STRING_MEDIUM);
	strncpy(new->name, name, STRING_MEDIUM);
	new->parent = NULL;
	new->list = NULL;
	new->sublists = NULL;
	debug("new_pwlist: %s", name);

	return new;
}

int 
free_pwlist(PWList *old)
{
	Pw *current, *next;
	PWList *curlist, *nlist;

	if(old == NULL){
		return 0;
	}
	for(current = old->list; current != NULL; current = next){
		next = current->next;

		free_pw(current);
	}
	for(curlist = old->sublists; curlist != NULL; curlist = nlist){
		nlist = curlist->next;

		free_pwlist(curlist);
	}
	
	free(old->name);
	free(old);
	old = NULL;
	return 0;
}

Pw*
new_pw()
{
	Pw *new;
	new = malloc(sizeof(Pw));
	new->id = 0;
	new->name = malloc(STRING_MEDIUM);
	new->host = malloc(STRING_MEDIUM);
	new->user = malloc(STRING_MEDIUM);
	new->passwd = malloc(STRING_SHORT);
	new->launch = malloc(STRING_LONG);

	memset(new->name, 0, STRING_MEDIUM);
	memset(new->host, 0, STRING_MEDIUM);
	memset(new->user, 0, STRING_MEDIUM);
	memset(new->passwd, 0, STRING_SHORT);
	memset(new->launch, 0, STRING_LONG);
	
	return new;
}

int
free_pw(Pw *old)
{
	free(old->name);
	free(old->user);
	free(old->host);
	free(old->passwd);
	free(old->launch);
	free(old);
}

int
add_pw_ptr(PWList *list, Pw *new)
{
	Pw *current;
	
	if(list == NULL){
		debug("add_pw_ptr : Bad PwList");
		return -1;
	}
	if(new == NULL){
		debug("add_pw_ptr : Bad Pw");
		return -1;
	}
	if(list->list == NULL){
		list->list = new;
		new->next = NULL;
		return 0;
	}

	debug("add_pw_ptr: add to list");
	current = list->list;
	while(current->next != NULL){
		current = current->next;
	}
	current->next = new;
	new->next = NULL;

	return 0;
}


int 
write_password_node(xmlNodePtr root, Pw *pw)
{
	xmlNodePtr node;

	node = xmlNewChild(root, NULL, (xmlChar*)"PwItem", NULL);
	xmlNewChild(node, NULL, (xmlChar*)"name", (xmlChar*)pw->name);
	xmlNewChild(node, NULL, (xmlChar*)"host", (xmlChar*)pw->host);
	xmlNewChild(node, NULL, (xmlChar*)"user", (xmlChar*)pw->user);
	xmlNewChild(node, NULL, (xmlChar*)"passwd", (xmlChar*)pw->passwd);
	xmlNewChild(node, NULL, (xmlChar*)"launch", (xmlChar*)pw->launch);
}

int
write_pwlist(xmlNodePtr parent, PWList *pwlist)
{
	xmlNodePtr node;
	Pw* iter;

	node = xmlNewChild(parent, NULL, (xmlChar*)"PwList", NULL);
	xmlSetProp(node, (xmlChar*)"name", (xmlChar*)pwlist->name);

	for(iter = pwlist->list; iter != NULL; iter = iter->next){
		write_password_node(node, iter);
	}
}

xmlDocPtr
write_new_doc(PWList *pwlist)
{
	char vers[5];
	xmlDocPtr doc;
	xmlNodePtr root;

	if(pwlist == NULL){
		puts("write_new_doc: bad password data");
		exit(-1);
	}
	snprintf(vers, 5, "%d", FF_VERSION);
	doc = xmlNewDoc((xmlChar*)"1.0");

	if(!export){
		root = xmlNewDocNode(doc, NULL, (xmlChar*)"PWMan_PasswordList", NULL);
		xmlSetProp(root, "version", vers);
		write_pwlist(root, pwlist);
	} else {
		root = xmlNewDocNode(doc, NULL, (xmlChar*)"PWMan_Export", NULL);
		xmlSetProp(root, "version", vers);
		write_password_node(root, pwlist->list);	
	}

	xmlDocSetRootElement(doc, root);

	return doc;
}

Pw *
read_pw_node(xmlNodePtr parent)
{
	Pw *new;
	xmlNodePtr node;
	char *text;

	new = new_pw();

	for(node = parent->children; node != NULL; node = node->next){
		if(!node || !node->name){
			debug("read_pw_node: fucked node");
		} else if( strcmp((char*)node->name, "name") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->name, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "user") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->user, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "passwd") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->passwd, text, STRING_SHORT);
		} else if( strcmp((char*)node->name, "host") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->host, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "launch") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->launch, text, STRING_LONG);
		} else {
			debug("read_pw_node: unrecognised node \"%s\"", node->name);
		}
	}
	return new;
}

PWList*
parse_old_doc(xmlDocPtr doc)
{
	PWList *pwlist;
	Pw *pw;
	xmlNodePtr root, node;

	pwlist = new_pwlist("Main");

	if(!doc){
		debug("parse_old_doc: Bad xmlDocPtr");
		return NULL;
	}
	root = xmlDocGetRootElement(doc);
	
	if(!root || !root->name){
		debug("parse_old_doc: Badly formed data");
		return NULL;
	}
	if( strcmp(root->name, "PWMan_Export") == 0){
		export = 1;
	} else if( strcmp(root->name, "PWMan_List") == 0){
		export = 0;
	} else {
		debug("parse_old_doc: Not a pwman file");
		return NULL;
	}
	for(node = root->children; node != NULL; node = node->next){
		if(!node || !node->name){
			debug("parse_old_doc: Bad xml Node");
		} else if( strcmp((char*)node->name, "PW_Item") == 0){
			pw = read_pw_node(node);
			add_pw_ptr(pwlist, pw);
		} else {
			debug("parse_old_doc: Unrecognised xml Node - \"%s\"", node->name);
		}
	}

	if(pwlist->list){
		return pwlist;
	} else {
		fputs("Unrecognised file format\n", stderr);
		exit(-1);
	}
}

char *
add_to_buf(char *buf, char *new)
{
	size_t size;

	if(new == NULL){
		return buf;
	} 
	if(buf == NULL){
		buf = malloc(strlen(new)+1);
		strncpy(buf, new, strlen(new)+1);
		return buf;
	}

	size = strlen(buf) + strlen(new) + 1;
	buf = (char*)realloc(buf, size);
	strncat(buf, new, size);

	return buf;
}

xmlDocPtr
get_data()
{
	FILE *fp;
	char *cmd;
	char *data;
	char buf[STR_LEN];
	xmlDocPtr doc;

	data = NULL;
	cmd = malloc(STR_LEN);
	snprintf(cmd, STR_LEN, "gpg -d %s", convertdb_options.infile);
	debug(cmd);
	fp = popen(cmd, "r");

	while( fgets(buf, STR_LEN, fp) != NULL ){
		data = add_to_buf(data, buf);
	}
	pclose(fp);

	if(!data){
		exit(-1);
	}

	doc = xmlParseMemory(data, strlen(data));

	return doc;
}

void
put_data(xmlDocPtr doc)
{
	FILE *fp;
	char *cmd;

	cmd = malloc(STR_LEN);
	snprintf(cmd, STR_LEN, "gpg -e -r %s -o %s", convertdb_options.gpg_id, convertdb_options.outfile);
	debug(cmd);
	fp = popen(cmd, "w");

#if XML_VERSION >= 20423
	xmlDocFormatDump(fp, doc, TRUE);
#else
	xmlDocDump(fp, doc);
#endif
	
	pclose(fp);
}

void
free_convertdb_options()
{
	free(convertdb_options.infile);
	free(convertdb_options.outfile);
	free(convertdb_options.gpg_id);
}

char *
ask(char *msg)
{
	char * input;

	input = malloc(STR_LEN);

	fputs(msg, stdout);
	fputc('\t', stdout);
	fgets(input, STR_LEN, stdin);

	input[ strlen(input) - 1] = 0;

	return input;
}

void
get_options(int argc, char *argv[])
{
	int i;

	for(i = 0; i < argc; i++){
		if( !strcmp(argv[i], "--help") || !strcmp(argv[i], "-h") ){
			show_usage(argv[0]);
			exit(1);
		} else if( !strcmp(argv[i], "--version") || !strcmp(argv[i], "-v") ){
			show_version();
			exit(1);
		}
	}
	
	if(argc > 1){
		convertdb_options.gpg_id = malloc(STR_LEN);
		strncpy(convertdb_options.gpg_id, argv[1], STR_LEN);
	} else {
		convertdb_options.gpg_id = ask("ID to encrypt new file to:");
	}
	if(argc > 2){
		convertdb_options.infile = malloc(STR_LEN);
		strncpy(convertdb_options.infile, argv[2], STR_LEN);
	} else {
		convertdb_options.infile = ask("File in old format:");
	}
	if(argc > 3){
		convertdb_options.outfile = malloc(STR_LEN);
		strncpy(convertdb_options.outfile, argv[3], STR_LEN);
	} else {
		convertdb_options.outfile = ask("File to write new format to:");
	}
}

int
main(int argc, char *argv[])
{
	xmlDocPtr doc;
	PWList *pwlist;
	
	get_options(argc, argv);

	doc = get_data();
	pwlist = parse_old_doc(doc);
	xmlFreeDoc(doc);
	
	doc = write_new_doc(pwlist);
	put_data(doc);
	xmlFreeDoc(doc);

	free_convertdb_options();
	return 0;
}

static void
show_version()
{
	puts(CONVERT_DB_PACKAGE " v " CONVERT_DB_VERSION);
	puts("Written by Ivan Kelly <ivan@ivankelly.net>\n");
	puts("Copyright (C) 2002 Ivan Kelly");
	puts("This program is free software; you can redistribute it and/or modify");
	puts("it under the terms of the GNU General Public License as published by");
	puts("the Free Software Foundation; either version 2 of the License, or");
	puts("(at your option) any later version.\n");

	puts("This program is distributed in the hope that it will be useful,");
	puts("but WITHOUT ANY WARRANTY; without even the implied warranty of");
	puts("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
	puts("GNU General Public License for more details.\n");

	puts("You should have received a copy of the GNU General Public License");
	puts("along with this program; if not, write to the Free Software");
	puts("Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.\n");
}

static void
show_usage(char *argv_0)
{
	printf("Usage: %s [<gnupg_id> [<oldfile> [<newfile>]]]\n", argv_0);
	puts("Convert Password Database from PWMan versions >= 0.2.1 to new format 0.3.0+\n");
	puts("  --help                 show usage");
	puts("  --version              display version information");
	puts("  <gnupg_id>             GnuPG ID to encrypt new password database to");
	puts("  <oldfile>              password database file in old format");
	puts("  <newfile>              password database file to write in new format\n\n");
	puts("Report bugs to <ivan@ivankelly.net>");
}

Deleted doc/pwman.1.

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
.TH PWMAN 1 "March 26, 2002"
.nh
.SH NAME
pwman \- curses based password storage program
.SH SYNOPSIS
.B pwman
[ \fB--help\fP | \fB--version\fP | \fB--gpg-path <path>\fP | \fB--gpg-id\fP <id> | \fB--file\fP <file> | \fB--passphrase-timeout <time in minutes> ] 
.SH DESCRIPTION
This manual page documents briefly the
.B pwman
program.
.PP
.B pwman
is a curses based password storage application. It uses GnuPG to encrypt and decrypt the password file.
The curses user interface was inspired by Jaako Heinonen's abook. 
.SH OPTIONS
.TP
\fB\-\-help\fP
Show usage.
.TP
\fB\-\-version\fP
Show version information.
.TP
\fB\-\-gpg-path\fP <path>
Specify path to GnuPG Executable.
.TP
\fB\-\-gpg-id\fP <id>
Specify GnuPG key to use while encrypting.

This can either be a key ID, or an email address.
.TP
\fB\-\-file\fP <file>
File to read passwords from.
.TP
\fB\-\-passphrase-timeout\fP <time in minutes>
Time before passphrase times out.
.TP
Press '\fB?\fP' during use to get a list of commands.
.SH SEE ALSO
.BR gpg (1),
.br
.SH AUTHOR
.B pwman 
was written by Ivan Kelly <ivan@ivankelly.net>
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































Added filter.c.































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <string.h>
#include <pwman.h>
#include <ui.h>

/*xtern int curitem;*/

PwFilter *
filter_new()
{
	PwFilter *new;

	new = malloc(sizeof(PwFilter));
	if(new == NULL) {
		pw_abort("Failed to allocate memory to hold filtering details!");
	}

	new->field = -1;
	new->filter = malloc(STRING_LONG);
	if(new == NULL) {
		pw_abort("Failed to allocate memory to hold filtering term!");
	}
	new->filter[0] = 0;

	return new;
}

/*
 * String checking only case insensitive using gnu glibc
 */
static char*
filter_strcasestr(char *haystack, char *needle){
	// Never matches if null/empty string given
	if(haystack == NULL) {
		return 0;
	}
	if(strlen(haystack) == 0) {
		return 0;
	}

#ifdef HAVE_STRCASESTR
	return (char*)strcasestr(haystack, needle);
#else
	return (char*)strstr(haystack, needle);
#endif
}

int
filter_apply(Pw *pw, PwFilter* fil)
{
	if( (fil == NULL) || (fil->filter == NULL) ){
		/* no filter object */
		return 1;
	}
	if( strlen(fil->filter) == 0 ){
		/* no filter */
		return 1;
	}
	switch(fil->field){
		case 0:
			if( filter_strcasestr(pw->name, fil->filter) ){
				return 1;
			}					
			break;
		case 1:
			if( filter_strcasestr(pw->host, fil->filter) ){
				return 1;
			}
			break;
		case 2:
			if( filter_strcasestr(pw->user, fil->filter) ){
				return 1;
			}
			break;
		case 3:
			if( filter_strcasestr(pw->launch, fil->filter) ){
				return 1;
			}
			break;
		default:
/*			fprintf(stderr, "Invalid filter field %d\n", fil->field);*/
			break;
	}
	return 0;
}

void
filter_get()
{
	char c;

	ui_statusline_ask_char("Filter which field? (n)ame (h)ost (u)ser (l)aunch n(o)ne", &c, "nhulo\n");
	switch(c){
		case 'n':
			options->filter->field = 0;
			break;
		case 'h':
			options->filter->field = 1;
			break;
		case 'u':
			options->filter->field = 2;
			break;
		case 'l':
			options->filter->field = 3;
			break;
		case 'o':
		default:
			options->filter->field = -1;
			options->filter->filter[0] = 0;

			uilist_refresh();
			return;
			break;
	}
	ui_statusline_ask_str("String to search for: ", options->filter->filter, STRING_MEDIUM);

	current_pw_sublist->current_item = -1;
	uilist_refresh();
}


int
filter_alert(PwFilter* fil)
{
	char alert[80];	

	if( (fil == NULL) || (fil->filter == NULL) ){
		/* no filter object */
		return 1;
	}
	if( strlen(fil->filter) == 0 ){
		/* no filter */
		return 1;
	}
	switch(fil->field){
		case 0:
			sprintf(alert, " (Filtering on name with '%s')", fil->filter);
			break;
		case 1:
			sprintf(alert, " (Filtering on host with '%s')", fil->filter);
			break;
		case 2:
			sprintf(alert, " (Filtering on user with '%s')", fil->filter);
		case 3:
			sprintf(alert, " (Filtering on launch with '%s')", fil->filter);
		default:
/*			fprintf(stderr, "Invalid filter field %d\n", fil->field);*/
			break;
	}

	ui_statusline_clear();
	ui_statusline_msg(alert);
}


Added gnupg.c.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */


/*
 * define for strings to check for with regex
 * should allow for internationalization
 */

#define GPG_ERR_CANTWRITE	"file create error"
#define GPG_ERR_CANTOPEN 	"can't open"
#define GPG_ERR_BADPASSPHRASE	"bad passphrase"
#define GPG_ERR_NOSECRETKEY	"secret key not available"

/* end defines */

#include <sys/stat.h>
#include <pwman.h>
#include <ui.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <regex.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>

#define STDOUT 0
#define STDIN 1
#define STDERR 2

int passphrase_good = 0;
extern int errno;
extern int write_options;

int gnupg_hit_sigpipe = 0;
static void gnupg_sigpipe_handler()
{
	gnupg_hit_sigpipe = 1;
}

static char *
gnupg_add_to_buf(char *buf, char *new)
{
	size_t size;

	if(new == NULL){
		return buf;
	}
	if(buf == NULL){
		buf = malloc(strlen(new)+1);
		strncpy(buf, new, strlen(new)+1);
		return buf;
	}
	
	size = strlen(buf) + strlen(new) + 1;
	buf = (char*)realloc(buf, size);
	strncat(buf, new, size);
	
	return buf;
}

static int
gnupg_str_in_buf(char *buf, char *check)
{
	regex_t reg;

	debug("str_in_buf: start checking");
	
	if( (buf == NULL) || (check == NULL) ){
		return 0;
	}
	regcomp(&reg, check ,0);
	if(regexec(&reg, buf, 0, NULL , 0) == 0){
		regfree(&reg);
		return 1;
	} else {
		regfree(&reg);
		return 0;
	}
}

static char *
gnupg_expand_filename(char *filename)
{
	char *buf = malloc(STRING_LONG);
	
	if((filename[0] == '~') && getenv("HOME")){
		snprintf(buf, STRING_LONG, "%s%s\0", getenv("HOME"), filename+1);
		strncpy(filename, buf, STRING_LONG);
	}
	free(buf);

	return filename;
}

static int 
gnupg_exec(char *path, char *args[], FILE *stream[3])
{
	int stdin_fd[2];
	int stdout_fd[2];
	int stderr_fd[2];
	int pid, ret;

	pipe(stdin_fd);
	pipe(stdout_fd);
	pipe(stderr_fd);

	pid = fork();

	if( (path == NULL) || (args == NULL) ){
		return -1;
	}

	// Do the right thing with the fork
	if(pid == 0){
		close(stdout_fd[0]);
		close(stdin_fd[1]);
		close(stderr_fd[0]);

		dup2(stdout_fd[1], fileno(stdout));
		dup2(stdin_fd[0], fileno(stdin));
		dup2(stderr_fd[1], fileno(stderr));

		ret = execv(path, args);
		if(ret) {
			pw_abort("Failed to run %s, aborted with error code %d", path, errno);
		}
	} else {
		close(stdout_fd[1]);
		close(stdin_fd[0]);
		close(stderr_fd[1]);

		if(stream != NULL){
			stream[STDOUT] = fdopen(stdout_fd[0], "r");
			stream[STDIN] = fdopen(stdin_fd[1], "w");
			stream[STDERR] = fdopen(stderr_fd[0], "r");
		}
		
		// Mark us as not having had a sigpipe yet
		gnupg_hit_sigpipe = 0;
		signal(SIGPIPE, gnupg_sigpipe_handler);

		return pid;
	}
}

static void
gnupg_exec_end(int pid, FILE *stream[3])
{
	char buf[STRING_LONG];

	// If we hit a problem, report that
	if(gnupg_hit_sigpipe) {
		fputs("GPG hit an error and died...\n", stderr);
		while( fgets(buf, STRING_LONG - 1, stream[STDOUT]) != NULL ){
			fputs(buf, stderr);
		}
		while( fgets(buf, STRING_LONG - 1, stream[STDERR]) != NULL ){
			fputs(buf, stderr);
		}
		// TODO - figure out why we don't get the real error message from
		//  GPG displayed here like one might expect
	}
	signal(SIGPIPE, NULL);

	// Close up
	debug("gnupg_exec_end : close streams");
	if(stream[0]){ fclose(stream[0]); }
	if(stream[1]){ fclose(stream[1]); }
	if(stream[2]){ fclose(stream[2]); }

	debug("waiting for pid %d", pid);
	waitpid(pid, NULL, 0);

	// Bail out if gpg broke
	if(gnupg_hit_sigpipe) {
		exit(-1);
	}
}

static char*
gnupg_find_recp(char *str)
{
	char *user;
	char *start;
	char *end;
	int size;
	debug(str);

	// Is it "<id>" ?
	start = strstr(str,"\"");
	if(start != NULL) {
		start += 1;
		end = strstr(start,"\"");
	} else {
		// Is it ID <id>\n?
		start = strstr(str,"ID");
		if(start != NULL) {
			start += 3;
			end = strstr(start,"\n");
		} else {
			// No idea
			user = "(not sure)";
			return user;
		}
	}

	size = end - start;
	user = malloc(size+1);
	strncpy(user, start, size);
	debug("Recipient is %s", user);
	return user;
}

// Returns 0 if found, -1 if not found, and -2 if found but expired
int
gnupg_check_id(char *id)
{	
	regex_t reg;
	regex_t expired_reg;
	int pid;
	char text[STRING_LONG], idstr[STRING_LONG], keyid[STRING_LONG];
   char exp[STRING_LONG], *args[4];
	FILE *streams[3];
	int id_is_key_id = 0;
	int key_found = 0;
	int key_is_expired = -1;
	
	debug("check_gnupg_id: check gnupg id\n");

	// Check we're given nice input
	if( strchr(id, '%') ){ 
		/* hmm, could be format string bug so tell get lost */
		return -1;
	}

	// Build our expired key matching regexp
	snprintf(exp, STRING_LONG, "^(pub|sub):e:");
	regcomp(&expired_reg, exp, REG_EXTENDED);

	// Is the supplied ID really a key ID?
	// (If it is, it's 8 chars long, and 0-9A-F)
	snprintf(keyid, STRING_LONG, "^[0-9A-Z]{8}$");
	regcomp(&reg, keyid,REG_EXTENDED);
	if(regexec(&reg, id, 0, NULL , 0) == 0) {
		// The supplied ID is a key ID
		id_is_key_id = 1;
		debug("check_gnupg_id: supplied ID was a gnupg key id\n");
	} else {
		debug("check_gnupg_id: supplied ID taken to be an email address\n");
	}

	if(id_is_key_id == 1) {
		// Match on "pub:.:SIZE:type:FULLID:DATE"
		// Where FULLID is 8 chars then the 8 chars we expected
		snprintf(idstr, STRING_LONG, "^pub:.:[0-9]+:[0-9]+:[0-9a-zA-Z]{8}%s:", id);
	} else {
		// Match on "(pub|uid) .... NAME <EMAIL ADDRESS>"
		snprintf(idstr, STRING_LONG, "[^<]*<%s>", id);
	}

	// Fire off GPG to find all our keys
	args[0] = "gpg";
	args[1] = "--with-colons";
	args[2] = "--list-keys";
	args[3] = NULL;

	pid = gnupg_exec(options->gpg_path, args, streams);

	while( fgets(text, STRING_LONG, streams[STDOUT]) ){
		regcomp(&reg, idstr, REG_EXTENDED);
		if(regexec(&reg, text, 0, NULL , 0) == 0){
			// Found the key!
         key_found = 1;

			// Check it isn't also expired
			if(regexec(&expired_reg, text, 0, NULL , 0) == 0) {
            // Only mark as expired if we haven't found another
            //  version that isn't expired
            if(key_is_expired == -1) {
   				key_is_expired = 1;
            }
			} else {
				key_is_expired = 0;
         }
		}
	}
	
   // Tidy up
	gnupg_exec_end(pid, streams);

   // If we found it, return found / found+expired
   if(key_found) {
		if(key_is_expired) {
			return -2; 
		}
		return 0; 
   }

   // Didn't find it
	return -1;
}

/**
 * Get a single GnuPG Recipient ID
 */
void
gnupg_get_id(char *id)
{
	while(1){
		id = ui_statusline_ask_str("GnuPG Recipient ID:", id, STRING_LONG);
		if(id[0] == 0){
			return;
		}
		if(gnupg_check_id(id) == 0){
			return;
		}
		debug("get_gnupg_id: if here is reached id is bad");
		ui_statusline_msg("Bad Recipient, Try again"); getch();
	}
}

/**
 * Get multiple GnuPG Recipient IDs
 */
void
gnupg_get_ids(char **ids, int max_id_num)
{
	InputField fields[max_id_num];
	char names[max_id_num][STRING_LONG];
	int i;

	for(i=0; i<max_id_num; i++) {
		fields[i].name = names[i]; // Needs a local string to write into
		snprintf(fields[i].name, STRING_LONG, "Recipient %d: ", (i+1));
		fields[i].value = ids[i]; // String to write into comes from caller
		fields[i].max_length = STRING_LONG;
		fields[i].type = STRING;
	}

	// Prompt to edit the recipients
	// This will verify the IDs for us
	action_input_gpgid_dialog(fields, max_id_num, "Edit Recipients");
}

char *
gnupg_get_filename(char *filename, char rw)
{
	if(rw == 'r'){
		filename = ui_statusline_ask_str("File to read from:", filename, STRING_LONG);
	} else if(rw == 'w'){
		filename = ui_statusline_ask_str("File to write to:", filename, STRING_LONG);
	} else {
		pw_abort("File request must be for read or write, got '%s'", rw);
	}
}

static const char *
gnupg_get_passphrase()
{
	static char *passphrase = NULL;

/*	passphrase == malloc(V_LONG_STR);*/
	if((time_base >= (time(NULL) - (options->passphrase_timeout*60))) && (passphrase_good == 1)){
		return passphrase;
	}
	
	passphrase_good = 0;

	passphrase = ui_statusline_ask_passwd("Enter GnuPG passphrase (^G to Cancel):", passphrase, 
			STRING_LONG, 0x07); /* 0x07 == ^G */
	passphrase_good = 1;

	return passphrase;
}

void
gnupg_forget_passphrase()
{
	passphrase_good = 0;

	debug("forget_passphrase: passphrase forgotten");
	ui_statusline_msg("Passphrase forgotten");
}

static int 
gnupg_check_executable()
{
	FILE *streams[3];
	char *args[3];
	int pid, count, version[3];
	
	debug("check_gnupg: start");
	if(options->gpg_path == NULL){
		return -1;
	}

	args[0] = "gpg";
	args[1] = "--version";
	args[2] = NULL;
	
	pid = gnupg_exec(options->gpg_path, args, streams);

	/* this might do version checking someday if needed */
	count = fscanf(streams[STDOUT], "gpg (GnuPG) %d.%d.%d", 
			&version[0], &version[1], &version[2]);
	gnupg_exec_end(pid, streams);

	debug("exec ended");
	if(count != 3){
		ui_statusline_msg("WARNING! GnuPG Executable not found"); getch();
		return -1;
	} else {
		debug("check_gnupg: Version %d.%d.%d", version[0], version[1], version[2]);	
		return 0;
	}
}

int
gnupg_write_many(xmlDocPtr doc, char** ids, int num_ids, char* filename)
{
	FILE *streams[3];
	char buf[STRING_LONG];
	char *args[10];
	char *err;
	int pid, i, pos, num_valid_ids;

	debug("gnupg_write: do some checks");	
	if((gnupg_check_executable() != 0) || !filename || (filename[0] == 0)){
		debug("gnupg_write: no gnupg or filename not set");
		return -1;
	}

	// Ensure all IDs are valid, and we have enough
	num_valid_ids = 0;
	for(i=0; i<num_ids; i++) {
		if(ids[i][0] != 0) {
			if(gnupg_check_id(ids[i]) != 0) {
				gnupg_get_id(ids[i]);
				
				if(ids[i][0] == 0) {
					return -1;
				}
			}

			num_valid_ids++;
		}
	}
	debug("gnupg_write: writing to %d recipients", num_valid_ids);
	if(num_valid_ids == 0) {
		return -1;
	}

	debug("gnupg_write: start writing");

	err = NULL;
	args[0] = "gpg";
	args[1] = "-e";
	args[2] = "-a";
	args[3] = "--always-trust"; /* gets rid of error when moving 
				       keys from other machines */
	args[4] = "--yes";
	args[5] = "-o";
	args[6] = gnupg_expand_filename( filename );

	// Add in all the recipients
	pos = 7;
	for(i=0; i<num_ids; i++) {
		if(ids[i][0] != 0) {
			args[pos] = "-r";
			pos++;
			args[pos] = ids[i];
			pos++;
		}
	}
	args[pos] = NULL;

	while(1){
		/* clear err buffer */
		if(err != NULL){ free(err); err = NULL; }

		pid = gnupg_exec(options->gpg_path, args, streams);

#if XML_VERSION >= 20423
		xmlDocFormatDump(streams[STDIN], doc, TRUE);
#else
		xmlDocDump(streams[STDIN], doc);
#endif
		close( fileno(streams[STDIN]) );
		
		while( fgets(buf, STRING_LONG - 1, streams[STDERR]) != NULL ){
			err = gnupg_add_to_buf(err, buf);
		}
		gnupg_exec_end(pid, streams);
		
		debug("gnupg_write: start error checking");
		/*
		 * check for errors(no key, bad pass, no file etc etc)
		 */
		if( gnupg_str_in_buf(err, GPG_ERR_CANTWRITE) ){
			debug("gnupg_write: cannot write to %s", filename);

			snprintf(buf, STRING_LONG, "Cannot write to %s", filename);
			ui_statusline_msg(buf); getch();

			filename = gnupg_get_filename(filename, 'w');
			if(filename[0] == 0){
				return -1;
			}
			continue;
		}
		break;
	}

	ui_statusline_msg("List Saved");
	debug("gnupg_write: file write sucessful");
	
	return 0;
}

int
gnupg_write(xmlDocPtr doc, char* id, char* filename)
{
	return gnupg_write_many(doc, &id, 1, filename);
}

int
gnupg_read(char *filename, xmlDocPtr *doc)
{
	char *args[9], *passphrase, *data, *err, buf[STRING_LONG], *user;
	FILE *streams[3];
	int pid;
	int ret = 0;
	
	if(gnupg_check_executable() != 0){
		*doc = xmlNewDoc((xmlChar*)"1.0");
		return -1;
	}
/*
	if(check_gnupg_passphrase(filename) == -1){
		return -1;
	}*/

	data = NULL;
	err = NULL;
	user = NULL;
	args[0] = "gpg";
	args[1] = "--passphrase-fd";
	args[2] = "0";
	args[3] = "--no-verbose";
	args[4] = "--batch";
	args[5] = "--output";
	args[6] = "-";
	args[7] = gnupg_expand_filename( filename );
	args[8] = NULL;
	
	while(1){
		/* clear buffers */
		if(err != NULL){ free(err); err = NULL; }
		if(data != NULL){ free(data); data = NULL; }
		
		passphrase = (char*)gnupg_get_passphrase();

		if(passphrase == NULL){
			// They hit cancel on the password prompt
			write_options = 0;
			filename[0] = 0;
			ret = 255;
			break;
		}

		pid = gnupg_exec(options->gpg_path, args, streams);

		fputs( passphrase, streams[STDIN]);
		fputc( '\n' , streams[STDIN]);
		fclose(streams[STDIN]);
		streams[STDIN] = NULL;

		debug("gnupg_read: start reading data");
		while( fgets(buf, STRING_LONG - 1, streams[STDOUT]) != NULL ){
			data = gnupg_add_to_buf(data, buf);
		}
		while( fgets(buf, STRING_LONG - 1, streams[STDERR]) != NULL ){
			err = gnupg_add_to_buf(err, buf);
		}
	
		gnupg_exec_end(pid, streams);

		debug("gnupg_read: start error checking");
		debug(err);
		/*
		 * check for errors(no key, bad pass, no file etc etc)
		 */
		if( gnupg_str_in_buf(err, GPG_ERR_BADPASSPHRASE) ){
			debug("gnupg_read: bad passphrase");
			ui_statusline_msg("Bad Passphrase, please re-enter");
			getch();

			passphrase_good = 0;
			continue;
		}
		if( gnupg_str_in_buf(err, GPG_ERR_CANTOPEN) ){
			debug("gnupg_read: cannot open %s", filename);
			snprintf(buf, STRING_LONG, "Cannot open file \"%s\"", filename);
			ui_statusline_msg(buf); getch();

			ret = -1;
			break;
		}
		if( gnupg_str_in_buf(err, GPG_ERR_NOSECRETKEY) ){
			debug("gnupg_read: secret key not available!");
			user = gnupg_find_recp(err);
			snprintf(buf, STRING_LONG, "You do not have the secret key for %s", user);
			ui_statusline_msg(buf); getch();

			ret = 254;
			break;
		}
		break;
	}


	debug("gnupg_read: finished read");
	if(data != NULL){
		debug("gnupg_read: data != NULL");
		*doc = xmlParseMemory(data, strlen(data));
		free(data);
	} else {
		debug("gnupg_read: data is null");
		*doc = xmlNewDoc((xmlChar*)"1.0");
	}
	if(err != NULL){ free(err); }
	if(user != NULL){ free(user); }

	debug("gnupg_read: finished all");

	return ret;
}

Added gnupg.h.

















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifndef PW_GNUPG_H
#define PW_GNUPG_H

#include <libxml/tree.h>
#include <libxml/parser.h>

void gnupg_forget_passphrase();

int gnupg_check_id(char*);
void gnupg_get_id(char*);
void gnupg_get_ids(char **, int);

char* gnupg_get_filename(char*, char);
const char* gnupg_get_passphrase();

int gnupg_read(char*, xmlDocPtr*);
int gnupg_write(xmlDocPtr, char*, char*);
int gnupg_write_many(xmlDocPtr, char**, int, char*);

#endif

Added help.h.











































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifndef HELP_H 
#define HELP_H

static char *help[] = {
	"	?		help\n",
	"	q/Q		quit\n",
	"	^L		refresh windows\n",
	"\n",
	"	arrows / j,k	scroll list\n",
	"	enter/space/e	view/edit item\n",
	"	U		move up a level\n",
	"\n",
	"	a		add item\n",
	"	A		add sublist\n",
	"	m		move item/sublist\n",
	"	M		move item/sublist up one level\n",
	"	[		move item up the list\n",
	"	]		move item down the list\n",
	"	r		rename item/sublist\n",
	"	d/del		delete item/sublist\n",
	"	L		locate item/sublist (prints path)\n",
	"\n",
	"	f		enable / disable filtering\n",
	"	/		enable / disable searching\n",
	"\n",
	"	l		launch item\n",
	"	Format:		%u = user\n",
	"			%h = host\n",
	"			%p = password\n",
	"	e.g.	mysql -Dmydb -u%u -p%p -h%h\n",
	"\n",
	"	Editor Help\n",
	"	[#]		edit field denoted by #\n",
	"	i.e.	press 3 to edit field 3\n",
	"\n",
	"	Misc Help\n",
	"	o		edit options\n",
	"	^W		write database to file (save)\n",
	"	^R		read database from file (reload)\n",
	"	I		import password from file\n",
	"	E		export password to file\n",
	"	^G		Generate password\n",
	"	^F		Forget passphrase\n",
	NULL
};

#endif


Added import_export.c.































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - password application manager
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <pwman.h>
#include <ui.h>
#include <stdlib.h>
#include <libxml/tree.h>
#include <libxml/parser.h>

int
export_passwd(Pw *pw)
{
	char vers[5];
	char id[STRING_LONG], file[STRING_LONG];
	
	xmlDocPtr doc;
	xmlNodePtr root;

	if(check_gnupg() != 0){
		debug("export_passwd: gnupg not found");
		return -1;
	}
	if(!pw){
		debug("export_passwd: bad password");
		statusline_msg("Bad password");
		return -1;
	}

	get_gnupg_id(id);
	if(id[0] == 0){
		debug("export_passwd: cancel because id is blank");
		return -1;
	}
	
	get_filename(file, 'w');

	debug("export_passwd: construct xml doc");
	snprintf(vers, 5, "%d", FF_VERSION);
	doc = xmlNewDoc((xmlChar*)"1.0");
	
	root = xmlNewDocNode(doc, NULL, (xmlChar*)"PWMan_Export", NULL);

	xmlSetProp(root, "version", vers);
	
	write_password_node(root, pw);

	xmlDocSetRootElement(doc, root);

	gnupg_write(doc, id, file);
	
	xmlFreeDoc(doc);
	return 0;
}

int
export_passwd_list(PWList *pwlist)
{
	char vers[5];
	char id[STRING_LONG], file[STRING_LONG];
	
	xmlDocPtr doc;
	xmlNodePtr root;

	if(check_gnupg() != 0){
		debug("export_passwd_list: gnupg not found");
		return -1;
	}
	if(!pwlist){
		debug("export_passwd_list: bad password");
		statusline_msg("Bad password");
		return -1;
	}

	get_gnupg_id(id);
	if(id[0] == 0){
		debug("export_passwd_list: cancel because id is blank");
		return -1;
	}
	
	get_filename(file, 'w');

	debug("export_passwd_list: construct xml doc");
	snprintf(vers, 5, "%d", FF_VERSION);
	doc = xmlNewDoc((xmlChar*)"1.0");
	
	root = xmlNewDocNode(doc, NULL, (xmlChar*)"PWMan_Export", NULL);

	xmlSetProp(root, "version", vers);
	
	write_pwlist(root, pwlist);

	xmlDocSetRootElement(doc, root);

	gnupg_write(doc, id, file);
	
	xmlFreeDoc(doc);
	return 0;
}

int
import_passwd()
{
	char file[STRING_LONG], *buf, *cmd, *s, *text;
	int i = 0;
	xmlNodePtr node, root;
	xmlDocPtr doc;

	get_filename(file, 'r');

	gnupg_read(file, &doc);	
	
	if(!doc){
		debug("import_passwd: bad data");
		return -1;
	}
	root = xmlDocGetRootElement(doc);
	if(!root || !root->name	|| (strcmp((char*)root->name, "PWMan_Export") != 0) ){
		statusline_msg("Badly Formed password data");
		return -1;
	}
	if( buf = xmlGetProp(root, (xmlChar*)"version") ){
		i = atoi( buf );
	} else {
		i = 0;
	}
	if(i < FF_VERSION){
		statusline_msg("Password Export File in older format, use convert_pwdb");
		return -1;
	}
	
	for(node = root->children; node != NULL; node = node->next){
		if(strcmp(node->name, "PwList") == 0){
			read_pwlist(node, current_pw_sublist);
			break;
		} else if(strcmp(node->name, "PwItem") == 0){
			read_password_node(node, current_pw_sublist);
			break;
		}
	}
	xmlFreeDoc(doc);
	return 0;
}

Added launch.c.













































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWman - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <pwman.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>

char * 
launch_find_replace(char *haystack, char* needle, char* cow)
{
	char *pos;
	int len,i;
	char *ret, *ret_p;

	pos = strstr(haystack, needle);
	if(pos == NULL){
		return haystack;
	}

	/*
	 * real ugly shit for 
	 * replacing the strings
	 */
	len = (strlen(haystack) - strlen(needle)) + strlen(cow) + 1;
	ret = malloc(len);
	ret_p = ret;
	i = pos - &haystack[0];
	strncpy(ret_p, haystack, i);
	ret_p += i;
	strcpy(ret_p, cow);
	ret_p += strlen(cow);
	pos += strlen(needle);
	strcpy(ret_p, pos);

	return ret;
}

int 
launch_execute(char *cmd) {
	int pid, status;
	char *argv[4];

	if (cmd == NULL){
		return 1;
	}
	
	pid = fork();
	if (pid == -1){
		return -1;
	}
	if (pid == 0) {
		argv[0] = "pwman_exec";
		argv[1] = "-c";
		argv[2] = cmd;
		argv[3] = NULL;

		execv("/bin/sh", argv);
		exit(127);
	}
	do {
		if (waitpid(pid, &status, 0) == -1) {
			if (errno != EINTR){
				return -1;
			} 
		}else {
			return status;
		}
	} while(1);
}

int
launch(Pw *pw)
{
	int i;
	char *cmd;
	char **cmd_array;

	if((pw == NULL) || (pw->launch == NULL)){
		return -1;
	}
	cmd = launch_find_replace(pw->launch, "%h", pw->host);
	cmd = launch_find_replace(cmd, "%u", pw->user);
	cmd = launch_find_replace(cmd, "%p", pw->passwd);

	def_prog_mode();
	ui_end();

	i = launch_execute(cmd);

	puts("Press any key to continue");
	getch();
	
	ui_init();
	reset_prog_mode();

	return i;
}

Added misc.c.



























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - Password Management Software
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <pwman.h>
#include <ui.h>

void _stderr_print(char *fmt, va_list ap)
{
	int d, c;
	char *s;

	while(*fmt){
		if(*fmt == '%'){
			switch(*++fmt){
				case 's': 	/* string */
					s = va_arg(ap, char*);
					fputs(s, stderr);
					break;
				case 'd':	/* int */
					d = va_arg(ap, int);
					fprintf(stderr, "%d", d);
					break;
				case 'c':	/* char */
					c = va_arg(ap, int);
					fputc(c, stderr);
					break;
				default:
					fputc('%', stderr);
					fputc(*fmt, stderr);
					break;
			}
		} else {
			fputc(*fmt, stderr);
		}
		*fmt++;
	}
	va_end(ap);
	fputc('\n', stderr);
}

void
pw_abort(char *fmt, ... )
{
	va_list ap;
	va_start(ap, fmt);
	_stderr_print(fmt, ap);
	exit(1);
}

void
debug(char *fmt, ... )
{
#ifdef DEBUG
	va_list ap;
	fputs("PWMan Debug% ", stderr);
	va_start(ap, fmt);
	_stderr_print(fmt, ap);
#endif
}

char *
trim_ws(char *str)
{
	int i;

	for(i = (strlen(str) - 1); i >= 0; i--){
		if(str[i] != ' '){
			return str;
		} else {
			str[i] = 0;
		}
	}
	ui_statusline_msg(str);
}

Added options.c.





























































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWman - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <pwman.h>
#include <stdlib.h>
#include <libxml/tree.h>
#include <libxml/parser.h>

Options*
options_new()
{
	Options *new;

	new = malloc(sizeof(Options));
	new->gpg_id = malloc(STRING_LONG);
	new->gpg_path = malloc(STRING_LONG);
	new->password_file = malloc(STRING_LONG);
	new->passphrase_timeout = 180;
	new->readonly = FALSE;

	new->filter = filter_new();
	new->search = search_new();

	return new;
}

char*
options_get_file()
{
	char *conf_file;

	conf_file = malloc(STRING_LONG);
	
	if(!getenv("HOME")){
		return NULL;
	} else {
		snprintf(conf_file, STRING_LONG, "%s/%s", getenv("HOME"), CONF_FILE);
	}

	return conf_file;
}

int
options_read()
{
	char *file, *text;
	xmlDocPtr doc;
	xmlNodePtr node, root;
	
	file = options_get_file();
	if(file == NULL){
		return -1;
	}

	doc = xmlParseFile(file);
	if(!doc){
		return -1;
	}

	root = xmlDocGetRootElement(doc);

	if(!root || !root->name || (strcmp((char*)root->name, "pwm_config") != 0) ){
		fprintf(stderr,"PWM-Warning: Badly Formed .pwmanrc\n");
		return -1;
	}

	for(node = root->children; node != NULL; node = node->next){
		if(!node || !node->name){
			debug("read_config: Fucked up xml node");
		} else if( strcmp((char*)node->name, "gpg_id") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(options->gpg_id, text, STRING_LONG);
		} else if( strcmp((char*)node->name, "gpg_path") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(options->gpg_path, text, STRING_LONG);
		} else if( strcmp((char*)node->name, "password_file") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(options->password_file, text, STRING_LONG);
		} else if( strcmp((char*)node->name, "passphrase_timeout") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text){ options->passphrase_timeout = atoi(text); }
		} else if( strcmp((char*)node->name, "filter") == 0){
			options->filter->field = atoi( (char*)xmlGetProp(node, "field") );
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(options->filter->filter, text, STRING_LONG);
		} else if( strcmp((char*)node->name, "readonly") == 0){
			options->readonly = TRUE;
		} else if( strcmp((char*)node->name, "text") == 0){
			// Safe to ignore. This is whitespace etc
		} else {
			debug("read_config: Unrecognised xml node '%s'", (char*)node->name);
		}
	}
	write_options = TRUE;
	xmlFreeDoc(doc);
	return 0;
}

int
options_write()
{
	char *file;
	char text[STRING_SHORT];
	xmlDocPtr doc;
	xmlNodePtr node, root;

	if(!write_options){
		return 0;
	}
	file = options_get_file();
	if(file == NULL){
		return -1;
	}

	if(!options){
		return -1;
	}
	doc = xmlNewDoc((xmlChar*) "1.0");
	root = xmlNewDocNode(doc, NULL, (xmlChar*)"pwm_config", NULL);
	xmlNewChild(root, NULL, (xmlChar*)"gpg_id", (xmlChar*)options->gpg_id);
	xmlNewChild(root, NULL, (xmlChar*)"gpg_path", (xmlChar*)options->gpg_path);
	xmlNewChild(root, NULL, (xmlChar*)"password_file", (xmlChar*)options->password_file);

	snprintf(text, STRING_SHORT, "%d", options->passphrase_timeout);
	xmlNewChild(root, NULL, (xmlChar*)"passphrase_timeout", (xmlChar*)text);

	snprintf(text, STRING_SHORT, "%d", options->filter->field);
	node = xmlNewChild(root, NULL, (xmlChar*)"filter", (xmlChar*)options->filter->filter);
	xmlSetProp(node, "field", text);

	// Note - search isn't serialised, but filter is

	xmlDocSetRootElement(doc, root);

	if( xmlSaveFormatFile(file, doc, TRUE) != -1 ){
		xmlFreeDoc(doc);
		return 0;
	} else {
		debug("write_options: couldn't write config file");
		xmlFreeDoc(doc);
		return -1;
	}
}

void
options_get()
{
	char pw_file[STRING_LONG];
	char text[STRING_SHORT];
	
	puts("Hmm... can't open ~/.pwmanrc, we'll create one manually now.");
	
	printf("GnuPG ID [you@yourdomain.com] or [012345AB]: ");
	fgets(options->gpg_id, STRING_LONG, stdin);
	if( strcmp(options->gpg_id, "\n") == 0 ){
		strncpy(options->gpg_id, "you@yourdomain.com", STRING_SHORT);
	} else {
		options->gpg_id[ strlen(options->gpg_id) - 1] = 0;
	}
	
	printf("Path to GnuPG [/usr/bin/gpg]: ");
	fgets(options->gpg_path, STRING_LONG, stdin);
	if( strcmp(options->gpg_path, "\n") == 0){
		strncpy(options->gpg_path, "/usr/bin/gpg", STRING_LONG);
	} else {
		options->gpg_path[ strlen(options->gpg_path) - 1] = 0;
	}
	
	snprintf(pw_file, STRING_LONG, "%s/.pwman.db", getenv("HOME") );
	printf("Password Database File [%s]: ", pw_file );
	fgets(options->password_file, STRING_LONG, stdin);
	if( strcmp(options->password_file, "\n") == 0){
		strncpy(options->password_file, pw_file, STRING_LONG);
	} else {
		options->password_file[ strlen(options->password_file) - 1] = 0;
	}
	
	printf("Passphrase Timeout(in minutes) [180]: ");
	fgets(text, STRING_SHORT, stdin);
	if( strcmp(text, "\n") == 0){
		options->passphrase_timeout = 180;
	} else {
		options->passphrase_timeout = atoi(text);
	}

	write_options = TRUE;
	options_write();
}

Added pwdb2csv.c.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWDB2CSV - Convert pwman database files into Comma Separated Values
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#define STR_LEN 255
#define PWDB2CSV_PACKAGE "PWDB2CSV"
#define PWDB2CSV_VERSION "0.1.0"

#include <libxml/parser.h>
#include <stdlib.h>
#include <stdio.h>
#include <pwman.h>

static void show_version();
static void show_usage(char*);

struct PWDB2CSV_Options {
	char *gpg_id;
	char *infile;
	char *outfile;
} pwdb2csv_options;

void
debug(char *fmt, ... )
{
#ifdef DEBUG
	va_list ap;
	int d, c;
	char *s;

	fputs("PWDB2CSV Debug% ", stderr);
	
	va_start(ap, fmt);
	while(*fmt){
		if(*fmt == '%'){
			switch(*++fmt){
				case 's': 	/* string */
					s = va_arg(ap, char*);
					fputs(s, stderr);
					break;
				case 'd':	/* int */
					d = va_arg(ap, int);
					fprintf(stderr, "%d", d);
					break;
				case 'c':	/* char */
					c = va_arg(ap, int);
					fputc(c, stderr);
					break;
				default:
					fputc('%', stderr);
					fputc(*fmt, stderr);
					break;
			}
		} else {
			fputc(*fmt, stderr);
		}
		*fmt++;
	}
	va_end(ap);
	fputc('\n', stderr);
#endif
}

PWList *
new_pwlist(char *name)
{
	PWList *new;

	new = malloc( sizeof(PWList) );
	new->name = malloc(STRING_MEDIUM);
	strncpy(new->name, name, STRING_MEDIUM);
	new->parent = NULL;
	new->list = NULL;
	new->sublists = NULL;
	debug("new_pwlist: %s", name);

	return new;
}

int 
free_pwlist(PWList *old)
{
	Pw *current, *next;
	PWList *curlist, *nlist;

	debug("free_pwlist: free a password list");
	if(old == NULL){
		return 0;
	}
	for(current = old->list; current != NULL; current = next){
		next = current->next;

		free_pw(current);
	}
	for(curlist = old->sublists; curlist != NULL; curlist = nlist){
		nlist = curlist->next;

		free_pwlist(curlist);
	}
	
	free(old->name);
	free(old);
	old = NULL;
	return 0;
}

Pw*
new_pw()
{
	Pw *new;
	new = malloc(sizeof(Pw));
	new->id = 0;
	new->name = malloc(STRING_MEDIUM);
	new->host = malloc(STRING_MEDIUM);
	new->user = malloc(STRING_MEDIUM);
	new->passwd = malloc(STRING_SHORT);
	new->launch = malloc(STRING_LONG);

	memset(new->name, 0, STRING_MEDIUM);
	memset(new->host, 0, STRING_MEDIUM);
	memset(new->user, 0, STRING_MEDIUM);
	memset(new->passwd, 0, STRING_SHORT);
	memset(new->launch, 0, STRING_LONG);
	
	return new;
}

int
free_pw(Pw *old)
{
	debug("free_pw: free a password");
	free(old->name);
	free(old->user);
	free(old->host);
	free(old->passwd);
	free(old->launch);
	free(old);
}

int
add_pw_ptr(PWList *list, Pw *new)
{
	Pw *current;
	
	if(list == NULL){
		debug("add_pw_ptr : Bad PwList");
		return -1;
	}
	if(new == NULL){
		debug("add_pw_ptr : Bad Pw");
		return -1;
	}
	if(list->list == NULL){
		list->list = new;
		new->next = NULL;
		return 0;
	}

	debug("add_pw_ptr: add to list");
	current = list->list;
	while(current->next != NULL){
		current = current->next;
	}
	current->next = new;
	new->next = NULL;

	return 0;
}

int
add_pw_sublist(PWList *parent, PWList *new)
{
	PWList *current;

	current = parent->sublists;
	new->parent = parent;
	if(current == NULL){
		parent->sublists = new;
		new->next = NULL;
		return 0;
	} 
	while(current->next != NULL){
		current = current->next;
	}
	current->next = new;
	new->next = NULL;

	return 0;
}

char *
escape_string(char *str)
{
	char *str2, *iter, *iter2, *c;
	int i = 0;
	
	str2 = malloc( strlen(str) + 100 ); /* any string with 100 quotes is a pisstake , it's just here for safety */
	
	for(iter = str, iter2 = str2; iter != 0, i < 100; iter++, iter2++, i++){
		if(*iter != '"'){
			*iter2 = *iter;
		} else {
			*iter2 = '\\'; iter2++;
			*iter2 = *iter;
		}
	}
	
	free(str);
	str = str2;

	return str;
}

int 
write_password_node(FILE *fp, Pw *pw)
{
	fprintf(fp, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n", escape_string(pw->name), escape_string(pw->host), 
			escape_string(pw->user), escape_string(pw->passwd), escape_string(pw->launch));
}

int
write_pwlist(FILE *fp, PWList *pwlist)
{
	Pw* iter;
	PWList *pwliter;
	
	for(pwliter = pwlist->sublists; pwliter != NULL; pwliter = pwliter->next){
		write_pwlist(fp, pwliter);
	}
	for(iter = pwlist->list; iter != NULL; iter = iter->next){
		write_password_node(fp, iter);
	}

	return 0;
}

void
read_password_node(xmlNodePtr parent, PWList *list)
{
	Pw *new;
	xmlNodePtr node;
	char *text;

	new = new_pw();

	for(node = parent->children; node != NULL; node = node->next){
		if(!node || !node->name){
			debug("read_pw_node: fucked node");
		} else if( strcmp((char*)node->name, "name") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->name, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "user") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->user, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "passwd") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->passwd, text, STRING_SHORT);
		} else if( strcmp((char*)node->name, "host") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->host, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "launch") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->launch, text, STRING_LONG);
		} else {
			debug("read_pw_node: unrecognised node \"%s\"", node->name);
		}
	}
	add_pw_ptr(list, new);
}

int
read_pwlist(xmlNodePtr parent, PWList *parent_list)
{
	xmlNodePtr node;
	PWList *new;

	char name[STRING_MEDIUM];
	if(!parent || !parent->name){
		return -1;
	} 
	debug("Parent name is %s\n", parent->name);

	if(strcmp((char*)parent->name, "PwList") == 0){
		strncpy(name, xmlGetProp(parent, (xmlChar*)"name"), STRING_MEDIUM);
		new = new_pwlist(name);

		for(node = parent->children; node != NULL; node = node->next){
			debug("Child name is %s\n", node->name);	
			if(!node) {
				fprintf(stderr, "read_pwlist: messed up node - null\n");
			// Doesn't appear to be a problem
//			} else if(!node->next){
//				fprintf(stderr, "read_pwlist: messed up node - no next sibling\n");
			} else if(strcmp(node->name, "PwList") == 0){
				read_pwlist(node, new);
			} else if(strcmp(node->name, "PwItem") == 0){
				read_password_node(node, new);
			}
		}
	}

	if(parent_list == NULL){
		parent_list = new;
	} else {
		add_pw_sublist(parent_list, new);
	}
	return 0;
}

PWList*
parse_doc(xmlDocPtr doc)
{
	PWList *pwlist = NULL;
	xmlNodePtr root, node;
	char *buf;
	int i;
	
	if(!doc){
		return NULL;
	}

	root = xmlDocGetRootElement(doc);
	if(!root || !root->name || (strcmp((char*)root->name, "PWMan_PasswordList") != 0) ){
		return NULL;
	}
	if(buf = xmlGetProp(root, (xmlChar*)"version")){
		i = atoi( buf );
	} else {
		i = 0;
	}
	if(i < FF_VERSION){
		return NULL;
	}

	pwlist = new_pwlist("Main");
	for(node = root->children; node != NULL; node = node->next){
		if(strcmp(node->name, "PwList") == 0){
			read_pwlist(node, pwlist);

			break;
		}
	}
	xmlFreeDoc(doc);

	return pwlist;
}

char *
add_to_buf(char *buf, char *new)
{
	size_t size;

	if(new == NULL){
		return buf;
	} 
	if(buf == NULL){
		buf = malloc(strlen(new)+1);
		strncpy(buf, new, strlen(new)+1);
		return buf;
	}

	size = strlen(buf) + strlen(new) + 1;
	buf = (char*)realloc(buf, size);
	strncat(buf, new, size);

	return buf;
}

xmlDocPtr
get_data()
{
	FILE *fp;
	char *cmd;
	char *data;
	char buf[STR_LEN];
	xmlDocPtr doc;

	data = NULL;
	cmd = malloc(STR_LEN);
	snprintf(cmd, STR_LEN, "gpg -d %s", pwdb2csv_options.infile);
	debug(cmd);
	fp = popen(cmd, "r");

	while( fgets(buf, STR_LEN, fp) != NULL ){
		data = add_to_buf(data, buf);
	}
	pclose(fp);

	if(!data){
		exit(-1);
	}

	doc = xmlParseMemory(data, strlen(data));

	return doc;
}

void
put_data(PWList *pwlist)
{
	FILE *fp;

	fp = fopen(pwdb2csv_options.outfile, "w");

	if(!fp){
		fprintf(stderr, "write_pwlist: couldn't open file \"%s\"\n", pwdb2csv_options.outfile);
		return;
	}

	write_pwlist(fp, pwlist);

	fclose(fp);
}

void
free_pwdb2csv_options()
{
	debug("free_pwdb2csv_options: free options");
	free(pwdb2csv_options.infile);
	free(pwdb2csv_options.outfile);
}

char *
ask(char *msg)
{
	char * input;

	input = malloc(STR_LEN);

	fputs(msg, stdout);
	fputc('\t', stdout);
	fgets(input, STR_LEN, stdin);

	input[ strlen(input) - 1] = 0;

	return input;
}

void
get_options(int argc, char *argv[])
{
	int i;

	for(i = 0; i < argc; i++){
		if( !strcmp(argv[i], "--help") || !strcmp(argv[i], "-h") ){
			show_usage(argv[0]);
			exit(1);
		} else if( !strcmp(argv[i], "--version") || !strcmp(argv[i], "-v") ){
			show_version();
			exit(1);
		}
	}
	
	if(argc > 1){
		pwdb2csv_options.infile = malloc(STR_LEN);
		strncpy(pwdb2csv_options.infile, argv[1], STR_LEN);
	} else {
		pwdb2csv_options.infile = ask("Password Database:");
	}
	if(argc > 2){
		pwdb2csv_options.outfile = malloc(STR_LEN);
		strncpy(pwdb2csv_options.outfile, argv[2], STR_LEN);
	} else {
		pwdb2csv_options.outfile = ask("CSV file:");
	}
}

int
main(int argc, char *argv[])
{
	xmlDocPtr doc;
	PWList *pwlist;
	
	get_options(argc, argv);

	doc = get_data();
	pwlist = parse_doc(doc);
	
	put_data(pwlist);

	free_pwdb2csv_options();
	return 0;
}

static void
show_version()
{
	puts(PWDB2CSV_PACKAGE " v " PWDB2CSV_VERSION);
	puts("Written by Ivan Kelly <ivan@ivankelly.net>\n");
	puts("Copyright (C) 2002 Ivan Kelly");
	puts("This program is free software; you can redistribute it and/or modify");
	puts("it under the terms of the GNU General Public License as published by");
	puts("the Free Software Foundation; either version 2 of the License, or");
	puts("(at your option) any later version.\n");

	puts("This program is distributed in the hope that it will be useful,");
	puts("but WITHOUT ANY WARRANTY; without even the implied warranty of");
	puts("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
	puts("GNU General Public License for more details.\n");

	puts("You should have received a copy of the GNU General Public License");
	puts("along with this program; if not, write to the Free Software");
	puts("Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.\n");
}

static void
show_usage(char *argv_0)
{
	printf("Usage: %s [<pwdatabase> [<csvfile>]]\n", argv_0);
	puts("Convert Password Database from PWMan Encrypted Format to Comma Separated Values\n");
	puts("  --help                 show usage");
	puts("  --version              display version information");
	puts("  <pwdatabase>           password database file in encrypted");
	puts("  <csvfile>              file to write to with comma separated values\n\n");
	puts("Report bugs to <ivan@ivankelly.net>");
}

Added pwgen.c.















































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - password manager application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * all code in this file is taken from pwgen
 * (c) 2001 Theodore Ts'o
 */

#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <pwman.h>
#include <ui.h>

struct pwgen_element {
	char	*str;
	int	flags;
};

/*
 * Flags for the pw_element
 */
#define CONSONANT	0x0001
#define VOWEL		0x0002
#define DIPTHONG	0x0004
#define NOT_FIRST	0x0008


struct pwgen_element elements[] = {
	{ "a",	VOWEL },
	{ "ae", VOWEL | DIPTHONG },
	{ "ah",	VOWEL | DIPTHONG },
	{ "ai", VOWEL | DIPTHONG },
	{ "b",  CONSONANT },
	{ "c",	CONSONANT },
	{ "ch", CONSONANT | DIPTHONG },
	{ "d",	CONSONANT },
	{ "e",	VOWEL },
	{ "ee", VOWEL | DIPTHONG },
	{ "ei",	VOWEL | DIPTHONG },
	{ "f",	CONSONANT },
	{ "g",	CONSONANT },
	{ "gh", CONSONANT | DIPTHONG | NOT_FIRST },
	{ "h",	CONSONANT },
	{ "i",	VOWEL },
	{ "ie", VOWEL | DIPTHONG },
	{ "j",	CONSONANT },
	{ "k",	CONSONANT },
	{ "l",	CONSONANT },
	{ "m",	CONSONANT },
	{ "n",	CONSONANT },
	{ "ng",	CONSONANT | DIPTHONG | NOT_FIRST },
	{ "o",	VOWEL },
	{ "oh",	VOWEL | DIPTHONG },
	{ "oo",	VOWEL | DIPTHONG},
	{ "p",	CONSONANT },
	{ "ph",	CONSONANT | DIPTHONG },
	{ "qu",	CONSONANT | DIPTHONG},
	{ "r",	CONSONANT },
	{ "s",	CONSONANT },
	{ "sh",	CONSONANT | DIPTHONG},
	{ "t",	CONSONANT },
	{ "th",	CONSONANT | DIPTHONG},
	{ "u",	VOWEL },
	{ "v",	CONSONANT },
	{ "w",	CONSONANT },
	{ "x",	CONSONANT },
	{ "y",	CONSONANT },
	{ "z",	CONSONANT }
};

#define NUM_ELEMENTS (sizeof(elements) / sizeof (struct pwgen_element))

char *pwgen(char *buf, int size)
{
	int	c, i, len, flags, feature_flags;
	int	prev, should_be, first;
	char	*str;

	if(buf == NULL){
		buf = malloc(size);
	}

	c = 0;
	prev = 0;
	should_be = 0;
	first = 1;

	should_be = pwgen_random_number(1) ? VOWEL : CONSONANT;
	
	while (c < size) {
		i = pwgen_random_number(NUM_ELEMENTS);
		str = elements[i].str;
		len = strlen(str);
		flags = elements[i].flags;
		/* Filter on the basic type of the next element */
		if ((flags & should_be) == 0)
			continue;
		/* Handle the NOT_FIRST flag */
		if (first && (flags & NOT_FIRST))
			continue;
		/* Don't allow VOWEL followed a Vowel/Dipthong pair */
		if ((prev & VOWEL) && (flags & VOWEL) &&
		    (flags & DIPTHONG))
			continue;
		/* Don't allow us to overflow the buffer */
		if (len > size-c)
			continue;
		/*
		 * OK, we found an element which matches our criteria,
		 * let's do it!
		 */
		strcpy(buf+c, str);

		/* Handle PW_ONE_CASE */
		if ((first || flags & CONSONANT) && (pwgen_random_number(10) < 3)) {
			buf[c] = toupper(buf[c]);
		}
		
		c += len;
		
		/* Time to stop? */
		if (c >= size)
			break;
		
		/*
		 * Handle PW_ONE_NUMBER
		 */
		if (!first && (pwgen_random_number(10) < 3)) {
			buf[c++] = pwgen_random_number(9)+'0';
			buf[c] = 0;
				
			first = 1;
			prev = 0;
			should_be = pwgen_random_number(1) ? VOWEL : CONSONANT;
			continue;
		}
				
		/*
		 * OK, figure out what the next element should be
		 */
		if (should_be == CONSONANT) {
			should_be = VOWEL;
		} else { /* should_be == VOWEL */
			if ((prev & VOWEL) ||
			    (flags & DIPTHONG) ||
			    (pwgen_random_number(10) > 3))
				should_be = CONSONANT;
			else
				should_be = VOWEL;
		}
		prev = flags;
		first = 0;
	}

	return buf;
}

#ifdef HAVE_DRAND48
extern double drand48();
#endif

/* Borrowed/adapted from e2fsprogs's UUID generation code */
static int pwgen_get_random_fd(void)
{
	struct timeval	tv;
	static int	fd = -2;
	int		i;

	if (fd == -2) {
		gettimeofday(&tv, 0);
		fd = open("/dev/urandom", O_RDONLY);
		if (fd == -1)
			fd = open("/dev/random", O_RDONLY | O_NONBLOCK);
#ifdef HAVE_DRAND48
		srand48((tv.tv_sec<<9) ^ (getpgrp()<<15) ^
			(getpid()) ^ (tv.tv_usec>>11));
#else
		srandom((getpid() << 16) ^ (getpgrp() << 8) ^ getuid() 
		      ^ tv.tv_sec ^ tv.tv_usec);
#endif
	}
	/* Crank the random number generator a few times */
	gettimeofday(&tv, 0);
	for (i = (tv.tv_sec ^ tv.tv_usec) & 0x1F; i > 0; i--)
#ifdef HAVE_DRAND48
		drand48();
#else
		rand();
#endif
	return fd;
}

/*
 * Generate a random number n, where 0 <= n < max_num, using
 * /dev/urandom if possible.
 */
int pwgen_random_number(int max_num)
{
	int i, fd = pwgen_get_random_fd();
	int lose_counter = 0, nbytes=4;
	unsigned int rand;
	char *cp = (char *) &rand;

	if (fd >= 0) {
		while (nbytes > 0) {
			i = read(fd, cp, nbytes);
			if ((i < 0) &&
			    ((errno == EINTR) || (errno == EAGAIN)))
				continue;
			if (i <= 0) {
				if (lose_counter++ == 8)
					break;
				continue;
			}
			nbytes -= i;
			cp += i;
			lose_counter = 0;
		}
	}
	if (nbytes == 0)
		return (rand % max_num);

	/* OK, we weren't able to use /dev/random, fall back to rand/rand48 */

#ifdef RAND48
	return ((int) ((drand48() * max_num)));
#else
	return ((int) (random() / ((float) RAND_MAX) * max_num));
#endif
}

char 
*pwgen_ask(char *pw)
{
	int i;
	ui_statusline_ask_num("Length of Password(default 5):\t", &i);

	if(i == 0){
		i = 5;
	} else if(i > STRING_SHORT) {
		i = STRING_SHORT;
	}
	pw = pwgen(pw, i);

	return pw;
}

int 
pwgen_indep()
{
	char pass[STRING_SHORT], text[STRING_LONG];

	pwgen_ask(pass);

	snprintf(text, STRING_LONG, "Generated Password: %s", pass);
	ui_statusline_msg(text);
}

Added pwlist.c.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <pwman.h>
#include <gnupg.h>
#include <ui.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <libxml/tree.h>
#include <libxml/parser.h>

int pwindex = 0;
extern int errno;
void pwlist_free_pw(Pw*);


PWList *
pwlist_new(char *name)
{
	PWList *new;
	new = malloc( sizeof(PWList) );
	new->name = malloc(STRING_MEDIUM);
	strncpy(new->name, name, STRING_MEDIUM);
	new->parent = NULL;
	new->list = NULL;
	new->next = NULL;
	new->sublists = NULL;
	debug("new_pwlist: %s", name);

	return new;
}

int
pwlist_init()
{
	pwindex = 0;
	pwlist = NULL;
	current_pw_sublist = NULL;
	return 0;
}

int 
pwlist_free(PWList *old)
{
	Pw *current, *next;
	PWList *curlist, *nlist;

	if(old == NULL){
		return 0;
	}
	for(current = old->list; current != NULL; current = next){
		next = current->next;

		pwlist_free_pw(current);
	}
	for(curlist = old->sublists; curlist != NULL; curlist = nlist){
		nlist = curlist->next;

		pwlist_free(curlist);
	}
	
	free(old->name);
	free(old);
	old = NULL;
	return 0;
}

int
pwlist_free_all()
{
	pwlist_free(pwlist);
	return 0;
}

Pw*
pwlist_new_pw()
{
	Pw *new;
	new = malloc(sizeof(Pw));
	new->id = 0;
	new->name = malloc(STRING_MEDIUM);
	new->host = malloc(STRING_MEDIUM);
	new->user = malloc(STRING_MEDIUM);
	new->passwd = malloc(STRING_SHORT);
	new->launch = malloc(STRING_LONG);

	memset(new->name, 0, STRING_MEDIUM);
	memset(new->host, 0, STRING_MEDIUM);
	memset(new->user, 0, STRING_MEDIUM);
	memset(new->passwd, 0, STRING_SHORT);
	memset(new->launch, 0, STRING_LONG);
	
	return new;
}

void
pwlist_free_pw(Pw *old)
{
	free(old->name);
	free(old->user);
	free(old->host);
	free(old->passwd);
	free(old->launch);
	free(old);
}

int
pwlist_change_item_order(Pw* pw, PWList *parent, int moveUp) {
	Pw *iter = NULL;
	Pw *pprev = NULL;
	Pw *prev = NULL;
	Pw *next = NULL;
	Pw *nnext = NULL;

	// Find us, in our parents list of children
	for(iter = parent->list; iter != NULL; iter = iter->next){
		if(iter == pw) {
			// Grab the next one, and the one after
			next = pw->next;
			if(next != NULL) {
				nnext = next->next;
			} else {
				nnext = NULL;
			}

			// Which way do we need to shuffle?
			if(moveUp) {
				// Up the list, if we can
				if(prev == NULL) { break; }

				// Are we going to the top?
				if(prev == parent->list) {
					parent->list = pw;
					pw->next = prev;
					prev->next = next;
				} else {
					pprev->next = pw;
					pw->next = prev;
					prev->next = next;
				}
				return 1;
			} else {
				// Down the list, if we can
				if(next == NULL) { break; }

				// Were we at the top?
				if(pw == parent->list) {
					parent->list = next;
					next->next = pw;
					pw->next = nnext;
				} else {
					prev->next = next;
					next->next = pw;
					pw->next = nnext;
				}
				return 1;
			}
		} else {
			// Update the running list of prev and pprev
			pprev = prev;
			prev = iter;
		}
	}

	return 0;
}

int
pwlist_change_list_order(PWList *pw, int moveUp) {
	// Grab the parent, assuming there is one
	PWList *parent = pw->parent;
	if(parent==NULL) { return 0; }


	// Find us
	PWList *iter = NULL;
	PWList *pprev = NULL;
	PWList *prev = NULL;
	PWList *next = NULL;
	PWList *nnext = NULL;

	// Find us, in our parents list of children
	for(iter = parent->sublists; iter != NULL; iter = iter->next){
		if(iter == pw) {
			// Grab the next one, and the one after
			next = pw->next;
			if(next != NULL) {
				nnext = next->next;
			} else {
				nnext = NULL;
			}

			// Which way do we need to shuffle?
			if(moveUp) {
				// Up the list, if we can
				if(prev == NULL) { break; }

				// Are we going to the top?
				if(prev == parent->sublists) {
					parent->sublists = pw;
					pw->next = prev;
					prev->next = next;
				} else {
					pprev->next = pw;
					pw->next = prev;
					prev->next = next;
				}
				return 1;
			} else {
				// Down the list, if we can
				if(next == NULL) { break; }

				// Were we at the top?
				if(pw == parent->sublists) {
					parent->sublists = next;
					next->next = pw;
					pw->next = nnext;
				} else {
					prev->next = next;
					next->next = pw;
					pw->next = nnext;
				}
				return 1;
			}
		} else {
			// Update the running list of prev and pprev
			pprev = prev;
			prev = iter;
		}
	}

	return 0;
}

void
pwlist_rename_item(Pw* pwitem, char* new_name) {
	strncpy(pwitem->name, new_name, STRING_MEDIUM);
}
void
pwlist_rename_sublist(PWList *pwlist, char* new_name) {
	strncpy(pwlist->name, new_name, STRING_MEDIUM);
}

int
pwlist_add(PWList *parent, char* name, char* host, char* user, char* passwd, char* launch)
{
	Pw* new = pwlist_new_pw();
	
	new->id = pwindex++;
	strncpy(new->name, name, STRING_MEDIUM);
	strncpy(new->host, host, STRING_MEDIUM);
	strncpy(new->user, user, STRING_MEDIUM);
	strncpy(new->passwd, passwd, STRING_SHORT);
	strncpy(new->launch, launch, STRING_LONG);

	pwlist_add_ptr(parent, new);

	return 0;
}

int 
pwlist_add_sublist(PWList *parent, PWList *new)
{
	PWList *current;

	current = parent->sublists;
	new->parent = parent;
	new->current_item = 1;

	if(current == NULL){
		debug("add_pw_sublist: current = NULL");
		parent->sublists = new;
		new->next = NULL;
		return 0;
	}
	while(current->next != NULL){
		current = current->next;
	}
	current->next = new;
	new->next = NULL;

	return 0;
}

int
pwlist_add_ptr(PWList *list, Pw *new)
{
	Pw *current;
	
	if(list == NULL){
		debug("add_pw_ptr : Bad PwList");
		return -1;
	}
	if(new == NULL){
		debug("add_pw_ptr : Bad Pw");
		return -1;
	}
	if(list->list == NULL){
		list->list = new;
		new->next = NULL;
		return 0;
	}

	debug("add_pw_ptr: add to list");
	current = list->list;
	while(current->next != NULL){
		current = current->next;
	}
	current->next = new;
	new->next = NULL;

	return 0;
}

void 
pwlist_detach_pw(PWList *list, Pw *pw)
{
	Pw *iter, *prev;

	prev = NULL;
	for(iter = list->list; iter != NULL; iter = iter->next){
		
		if(iter == pw){
			if(prev == NULL){
				list->list = iter->next;
			} else {
				prev->next = iter->next;
			}
			break;
		}
		prev = iter;
	}
}

void 
pwlist_delete_pw(PWList *list, Pw *pw)
{
	Pw *iter, *prev;

	prev = NULL;
	for(iter = list->list; iter != NULL; iter = iter->next){
		
		if(iter == pw){
			if(prev == NULL){
				list->list = iter->next;
			} else {
				prev->next = iter->next;
			}
			pwlist_free_pw(iter);
			break;
		}
		prev = iter;
	}
}

void 
pwlist_detach_sublist(PWList *parent, PWList *old)
{
	PWList *iter, *prev;

	prev = NULL;
	for(iter = parent->sublists; iter != NULL; iter = iter->next){

		if(iter == old){
			if(prev == NULL){
				parent->sublists = iter->next;
			} else {
				prev->next = iter->next;
			}
			break;
		}
		prev = iter;
	}
}

void
pwlist_delete_sublist(PWList *parent, PWList *old)
{
	PWList *iter, *prev;

	prev = NULL;
	for(iter = parent->sublists; iter != NULL; iter = iter->next){

		if(iter == old){
			if(prev == NULL){
				parent->sublists = iter->next;
			} else {
				prev->next = iter->next;
			}
			pwlist_free(iter);
			break;
		}
		prev = iter;
	}
}

void 
pwlist_write_node(xmlNodePtr root, Pw* pw)
{
	xmlNodePtr node;

	// We need to escape the strings before storing them
	// Otherwise, special characters (especially &) will
	//  end up broken!
	xmlChar *escapedName = 
		xmlEncodeSpecialChars(root->doc, (xmlChar*)pw->name);
	xmlChar *escapedHost =
		xmlEncodeSpecialChars(root->doc, (xmlChar*)pw->host);
	xmlChar *escapedUser =
		xmlEncodeSpecialChars(root->doc, (xmlChar*)pw->user);
	xmlChar *escapedPasswd = 
		xmlEncodeSpecialChars(root->doc, (xmlChar*)pw->passwd);
	xmlChar *escapedLaunch =
		xmlEncodeSpecialChars(root->doc, (xmlChar*)pw->launch);

	// Build the entry and add in our (escaped) contents
	node = xmlNewChild(root, NULL, (xmlChar*)"PwItem", NULL);

	xmlNewChild(node, NULL, (xmlChar*)"name", escapedName);
	xmlNewChild(node, NULL, (xmlChar*)"host", escapedHost);
	xmlNewChild(node, NULL, (xmlChar*)"user", escapedUser);
	xmlNewChild(node, NULL, (xmlChar*)"passwd", escapedPasswd);
	xmlNewChild(node, NULL, (xmlChar*)"launch", escapedLaunch);

	// Finally, we need to free all our escaped versions now we're done
	xmlFree(escapedName);
	xmlFree(escapedHost);
	xmlFree(escapedUser);
	xmlFree(escapedPasswd);
	xmlFree(escapedLaunch);
}

void
pwlist_write(xmlNodePtr parent, PWList *list)
{
	xmlNodePtr node;
	Pw *iter;
	PWList *pwliter;
	
	node = xmlNewChild(parent, NULL, (xmlChar*)"PwList", NULL);
	xmlSetProp(node, (xmlChar*)"name", (xmlChar*)list->name);
	
	for(iter = list->list; iter != NULL; iter = iter->next){
		pwlist_write_node(node, iter);
	}
	for(pwliter = list->sublists; pwliter != NULL; pwliter = pwliter->next){
		pwlist_write(node, pwliter);
	}
}

int
pwlist_write_file()
{
	char vers[5];
	xmlDocPtr doc;
	xmlNodePtr root;

	if(options->readonly){
		return 0;
	}

	if(!pwlist){
		debug("write_file: bad password file");
		ui_statusline_msg("Bad password list");
		return -1;
	}
	snprintf(vers, 5, "%d", FF_VERSION);
	doc = xmlNewDoc((xmlChar*)"1.0");
	
	root = xmlNewDocNode(doc, NULL, (xmlChar*)"PWMan_PasswordList", NULL);

	xmlSetProp(root, (xmlChar*)"version", (xmlChar*)vers);
	pwlist_write(root, pwlist);

	xmlDocSetRootElement(doc, root);

	gnupg_write(doc, options->gpg_id, options->password_file);
	
	xmlFreeDoc(doc);
	return 0;
}

void
pwlist_read_node(xmlNodePtr parent, PWList *list)
{
	Pw* new;
	xmlNodePtr node;
	char *text;
	
	new = pwlist_new_pw();

	for(node = parent->children; node != NULL; node = node->next){
		if(!node || !node->name){
			debug("Messed up xml node");
		} else if( strcmp((char*)node->name, "name") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->name, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "user") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->user, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "passwd") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->passwd, text, STRING_SHORT);
		} else if( strcmp((char*)node->name, "host") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->host, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "launch") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->launch, text, STRING_LONG);
		} 
	}
	pwlist_add_ptr(list, new);
}

int
pwlist_read(xmlNodePtr parent, PWList *parent_list)
{
	xmlNodePtr node;
	PWList *new;

	char name[STRING_MEDIUM];
	if(!parent || !parent->name){
		ui_statusline_msg("Messed up xml node");
		return -1;
	}
	if(strcmp((char*)parent->name,"PwList") == 0){
		strncpy(name, xmlGetProp(parent, (xmlChar*)"name"), STRING_MEDIUM);
		new = pwlist_new(name);

		for(node = parent->children; node != NULL; node = node->next){
			if(!node || !node->name){
				debug("read_pwlist: messed up child node");
			} else if(strcmp(node->name, "PwList") == 0){
				pwlist_read(node, new);
			} else if(strcmp(node->name, "PwItem") == 0){
				pwlist_read_node(node, new);
			}
		}
	}

	if(parent_list == NULL){
		pwlist = new;
		current_pw_sublist = pwlist;

		pwlist->current_item = 0;
	} else {
		pwlist_add_sublist(parent_list, new);
	}
	return 0;
}

int
pwlist_read_file()
{
    char fn[STRING_LONG];
	char *buf;
	int i = 0;
	int gnupg_worked = 0;
	xmlNodePtr node, root;
	xmlDocPtr doc;

	// Have the defined a file yet?
	if(!options->password_file){
		return -1;
	}
	// Do we need to create a new file?
	snprintf(fn, STRING_LONG, "%s", options->password_file);
	if(access(fn, F_OK) != 0){
		ui_statusline_msg("Database not found, created. Press any key to begin  "); getch();
		return -1;
	}

	// Try to load the file
	gnupg_worked = gnupg_read(options->password_file, &doc);	

	// Did it work?
	if(gnupg_worked != 0) {
		return gnupg_worked;
	}
	
	if(!doc){
		ui_statusline_msg("Bad xml Data");
		return -1;
	}
	root = xmlDocGetRootElement(doc);
	if(!root || !root->name	|| (strcmp((char*)root->name, "PWMan_PasswordList") != 0) ){
		ui_statusline_msg("Badly Formed password data");
		return -1;
	}
	if( buf = xmlGetProp(root, (xmlChar*)"version") ){
		i = atoi( buf );
	} else {
		i = 0;
	}
	if(i < FF_VERSION){
		ui_statusline_msg("Password File in older format, use convert_pwdb");
		return -1;
	}

	for(node = root->children; node != NULL; node = node->next){
		if(strcmp(node->name, "PwList") == 0){
			pwlist_read(node, NULL);

			break;
		}
	}
	xmlFreeDoc(doc);
	return 0;
}


int
pwlist_do_export(PWList *pwlist, Pw *pw)
{
	char vers[5];
	char file[STRING_LONG];
	int max_id_num = 5, i=0, valid_ids = 0;
	char *ids[max_id_num];
	
	xmlDocPtr doc;
	xmlNodePtr root;

	if(!pwlist && !pw) {
		debug("export_passwd: bad password");
		ui_statusline_msg("Bad password");
		return -1;
	}

	// We need the IDs to default to empty strings
	for(i=0; i<max_id_num; i++) {
		ids[i] = malloc(STRING_LONG);
		snprintf(ids[i], STRING_LONG, "");
	}

	// Fetch the IDs
	gnupg_get_ids(ids,max_id_num);

	// Check we really got one
	for(i=0; i<max_id_num; i++) {
		if(ids[i][0] != 0) {
			valid_ids++;
		}
	}

	if(valid_ids == 0){
		debug("export_passwd: cancel because id is blank");
		return -1;
	} else {
		debug("exporting to %d ids", valid_ids);
	}
	
	gnupg_get_filename(file, 'w');

	debug("export_passwd: construct xml doc");
	snprintf(vers, 5, "%d", FF_VERSION);
	doc = xmlNewDoc((xmlChar*)"1.0");
	
	root = xmlNewDocNode(doc, NULL, (xmlChar*)"PWMan_Export", NULL);

	xmlSetProp(root, "version", vers);
	
   if(pwlist) {
      pwlist_write(root, pwlist);
   } else {
      pwlist_write_node(root, pw);
   }

	xmlDocSetRootElement(doc, root);

	gnupg_write_many(doc, ids, max_id_num, file);
	
	xmlFreeDoc(doc);

	// All done.
	// Free our ID structures
	for(i=0; i<max_id_num; i++) {
		free(ids[i]);
	}
	
	return 0;
}

int
pwlist_export_passwd(Pw *pw)
{
   return pwlist_do_export(NULL, pw);
}
int
pwlist_export_list(PWList *pwlist)
{
   return pwlist_do_export(pwlist, NULL);
}


int
pwlist_import_passwd()
{
	char file[STRING_LONG], *buf;
	int i = 0;
	xmlNodePtr node, root;
	xmlDocPtr doc;

	gnupg_get_filename(file, 'r');

	gnupg_read(file, &doc);	
	
	if(!doc){
		debug("import_passwd: bad data");
		return -1;
	}
	root = xmlDocGetRootElement(doc);
	if(!root || !root->name	|| (strcmp((char*)root->name, "PWMan_Export") != 0) ){
		ui_statusline_msg("Badly Formed password data");
		return -1;
	}
	if( buf = xmlGetProp(root, (xmlChar*)"version") ){
		i = atoi( buf );
	} else {
		i = 0;
	}
	if(i < FF_VERSION){
		ui_statusline_msg("Password Export File in older format, use convert_pwdb");
		return -1;
	}
	
	for(node = root->children; node != NULL; node = node->next){
		if(strcmp(node->name, "PwList") == 0){
			pwlist_read(node, current_pw_sublist);
			break;
		} else if(strcmp(node->name, "PwItem") == 0){
			pwlist_read_node(node, current_pw_sublist);
			break;
		}
	}
	xmlFreeDoc(doc);
	return 0;
}

Added pwman.1.

























































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
.TH PWMAN 1 "March 26, 2002"
.nh
.SH NAME
pwman \- curses based password storage program
.SH SYNOPSIS
.B pwman
[ \fB--help\fP | \fB--version\fP | \fB--gpg-path <path>\fP | \fB--gpg-id\fP <id> | \fB--file\fP <file> | \fB--passphrase-timeout <time in minutes> ] 
.SH DESCRIPTION
This manual page documents briefly the
.B pwman
program.
.PP
.B pwman
is a curses based password storage application. It uses GnuPG to encrypt and decrypt the password file.
The curses user interface was inspired by Jaako Heinonen's abook. 
.SH OPTIONS
.TP
\fB\-\-help\fP
Show usage.
.TP
\fB\-\-version\fP
Show version information.
.TP
\fB\-\-gpg-path\fP <path>
Specify path to GnuPG Executable.
.TP
\fB\-\-gpg-id\fP <id>
Specify GnuPG key to use while encrypting.

This can either be a key ID, or an email address.
.TP
\fB\-\-file\fP <file>
File to read passwords from.
.TP
\fB\-\-passphrase-timeout\fP <time in minutes>
Time before passphrase times out.
.TP
Press '\fB?\fP' during use to get a list of commands.
.SH SEE ALSO
.BR gpg (1),
.br
.SH AUTHOR
.B pwman 
was written by Ivan Kelly <ivan@ivankelly.net>

Added pwman.c.





























































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "pwman.h"
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdarg.h>

static void pwman_parse_command_line(int argc, char **argv);
static void pwman_show_usage();
static void pwman_show_version();
static void pwman_quit();


static int
pwman_check_lock_file()
{
	char fn[STRING_LONG];
	FILE *fp;
	
	snprintf(fn, STRING_LONG, "%s.lock", options->password_file);
	if(access(fn, F_OK) == 0){
		return 1;
	} else {
		return 0;
	}
}

static int
pwman_create_lock_file()
{
	char fn[STRING_LONG];
		
	snprintf(fn, STRING_LONG, "%s.lock", options->password_file);
	creat(fn, S_IRWXU);
}

static int
pwman_delete_lock_file()
{
	char fn[STRING_LONG];
	
	snprintf(fn, STRING_LONG, "%s.lock", options->password_file);
	unlink(fn);
}

static void
pwman_init(int argc, char *argv[])
{
	char c;
	int load_worked, gpg_id_valid;

	signal(SIGKILL, pwman_quit);
	signal(SIGTERM, pwman_quit);

	umask(DEFAULT_UMASK);

	/* get options from .pwmanrc */
	options = options_new();
	if(options_read() == -1){
		options_get();
	}

	/* parse command line options */
	pwman_parse_command_line(argc, argv);

	/* check to see if another instance of pwman is open */
	if(!options->readonly && pwman_check_lock_file()){
		fprintf(stderr, "It seems %s is already opened by an instance of pwman\n",
				options->password_file);
		fprintf(stderr, "Two instances of pwman should not be open the same file at the same time\n");
		fprintf(stderr, "If you are sure pwman is not already open you can delete the file.\n");
		fprintf(stderr,"Alternatively, you can open the file readonly by answering 'r'\n");
		fprintf(stderr,"Delete file %s.lock? [y/n/r]\n",
				options->password_file);
		c = getchar();
		fprintf(stderr,"\n");
		switch (tolower(c)) {
			case 'y':
				pwman_delete_lock_file();
				break;
			case 'r':
				options->readonly = TRUE;
				break;
			default:
				exit(-1);
		}
	}

	// Check that the gpg id is valid, if given
	if(strlen(options->gpg_id)) {
		gpg_id_valid = gnupg_check_id(options->gpg_id);
		if(gpg_id_valid == -1) {
			fprintf(stderr, "Your GPG key with id of '%s' could not be found\n", options->gpg_id);
			fprintf(stderr, "You will be prompted for the correct key when saving\n");
			fprintf(stderr, "\n(press any key to continue)\n");
			c = getchar();
		}
		if(gpg_id_valid == -2) {
			fprintf(stderr, "Your GPG key with id of '%s' has expired!\n", options->gpg_id);
			fprintf(stderr, "Please change the expiry date of your key, or switch to a new one\n");
			exit(-1);
		}
	}
	
	// Start up our UI
	if( ui_init() ){
		exit(1);
	}

	ui_refresh_windows();

	/* get pw database */
	pwlist_init();
	load_worked = pwlist_read_file();
	if(load_worked != 0) {
		debug("Failed to load the database, error was %d", load_worked);
		// Did they cancel out, or is it a new file?
		if(load_worked < 0) {
			pwlist = pwlist_new("Main");
			current_pw_sublist = pwlist;
		} else {
			// Quit, hard!
			ui_end();
			fprintf(stderr, "\n\nGPG read cancelled, exiting\n");
			exit(1);
		}
	}
	if (!options->readonly){
		pwman_create_lock_file();
	}

	ui_refresh_windows();
}

static void
pwman_quit()
{
	pwlist_write_file();
	pwlist_free_all();
	pwman_delete_lock_file();
	
	ui_end();
	options_write();
	
	exit(0);
}

int
main(int argc, char *argv[])
{
	pwman_init(argc, argv);

	ui_run();

	pwman_quit();
	return 0;
}

static void
pwman_parse_command_line(int argc, char **argv)
{
	int i;

	for(i = 1; i < argc; i++){
		if( !strcmp(argv[i], "--help") || !strcmp(argv[i], "-h") ){
			pwman_show_usage(argv[0]);
			exit(1);
		} else if( !strcmp(argv[i], "--version") || !strcmp(argv[i], "-v") ){
			pwman_show_version();
			exit(1);
		} else if( !strcmp(argv[i], "--gpg-path") ){
			write_options = FALSE;
			strncpy(options->gpg_path, argv[i + 1], STRING_LONG);
			i++;
		}else if( !strcmp(argv[i], "--gpg-id") ){
			write_options = FALSE;
			strncpy(options->gpg_id, argv[i + 1], STRING_LONG);
			i++;
		} else if( !strcmp(argv[i], "--file") || !strcmp(argv[i], "-f") ){
			write_options = FALSE;
			strncpy(options->password_file, argv[i + 1], STRING_LONG);
			i++;
		} else if( !strcmp(argv[i], "--passphrase-timeout") || !strcmp(argv[i], "-t") ){
			write_options = FALSE;
			options->passphrase_timeout = atoi(argv[i + 1]);
			i++;
		} else if ( !strcmp(argv[i], "--readonly") || !strcmp(argv[i], "-r") ){
			write_options = FALSE;
			options->readonly = TRUE;
		} else {
			printf("option %s not recognised\n", argv[i]);
			printf("try %s --help for more info\n", argv[0]);
			exit(1);
		}
	}
}

static void
pwman_show_version()
{
	puts(PACKAGE " v " VERSION);
	puts("Written by Ivan Kelly <ivan@ivankelly.net>\n");
	puts("Copyright (C) 2002 Ivan Kelly");
	puts("This program is free software; you can redistribute it and/or modify");
	puts("it under the terms of the GNU General Public License as published by");
	puts("the Free Software Foundation; either version 2 of the License, or");
	puts("(at your option) any later version.\n");

	puts("This program is distributed in the hope that it will be useful,");
	puts("but WITHOUT ANY WARRANTY; without even the implied warranty of");
	puts("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
	puts("GNU General Public License for more details.\n");

	puts("You should have received a copy of the GNU General Public License");
	puts("along with this program; if not, write to the Free Software");
	puts("Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.\n");
}

static void
pwman_show_usage(char *argv_0)
{
	printf("Usage: %s [OPTIONS]...\n", argv_0);
	puts("Store you passwords securely using public key encryption\n");
	puts("  --help                 show usage");
	puts("  --version              display version information");
	puts("  --gpg-path <path>      Path to GnuPG executable");
	puts("  --gpg-id <id>          GnuPG ID to use");
	puts("  --file <file>          file to read passwords from");
	puts("  --passphrase-timeout <mins>    time before app forgets passphrase(in minutes)");
	puts("  --readonly             open the database readonly\n\n");
	puts("Report bugs to <ivan@ivankelly.net>");
}

Added pwman.h.





















































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifndef PW_MINDER_H
#define PW_MINDER_H

#include <curses.h>
#include <stdio.h>
#include <string.h>
#include <config.h>
#include <time.h>
#include <stdarg.h>

#define CONF_FILE 	".pwmanrc" 
/*
#define NAME_LEN	40
#define HOST_LEN	40
#define USER_LEN	40
#define PASS_LEN	40
#define LAUNCH_LEN	40

#define SHORT_STR	20
#define	MED_STR		30
#define LONG_STR	40
#define V_LONG_STR	256
*/

/* string lengths */
#define STRING_SHORT	64
#define STRING_MEDIUM	128
#define STRING_LONG	256

#define MAIN_HELPLINE 	"q:quit  ?:help  a:add  e:edit  d:delete"
#define READONLY_MSG	"RO"

#define MAX_SEARCH_DEPTH 25

#define DEFAULT_UMASK 066


#define FF_VERSION 3 

struct _PW {
	int id;
	char *name;
	char *host;
	char *user;
	char *passwd;
	char *launch;
	struct _PW *next;
};
typedef struct _PW Pw;

struct _PWList {
	char *name;
	Pw *list;
	struct _PWList *parent;
	struct _PWList *sublists;
	struct _PWList *next;

	/* ui stuff, shouldn't be here but this is a quick hack */
	int current_item;
};
typedef struct _PWList PWList;

struct _PWSearchResult {
	/* Always has a sublist, whether the list or child matches */
	PWList *sublist;
	/* If the entry itself matches, will be present */
	Pw *entry;

	/* The next one along, as with other structs */
	struct _PWSearchResult* next;
};
typedef struct _PWSearchResult PWSearchResult;


typedef struct {
	int field;
	char *filter;
} PwFilter;

typedef struct {
	char *search_term;
} PwSearch;

typedef struct {
	char *gpg_id;
	char *gpg_path;
	char *password_file;
	int passphrase_timeout;
	PwFilter *filter;
	PwSearch *search;
	int readonly;
} Options;

Options *options;
int write_options;
PWList *pwlist;
PWList *current_pw_sublist;
PWSearchResult *search_results;
time_t time_base;

char *trim_ws(char*);
void debug(char*, ...);
void pw_abort(char*, ...);
int ui_init();
int ui_run();
int ui_end();

PwFilter * filter_new();
PwSearch * search_new();
Options * options_new();

void search_get();
int search_remove();

int pwlist_add_ptr(PWList*, Pw*);
Pw* pwlist_new_pw();
PWList *pwlist_new(char*);
#endif

Added search.c.



















































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <string.h>
#include <pwman.h>
#include <ui.h>

/*xtern int curitem;*/

PwSearch *
search_new()
{
	PwSearch *new;

	new = malloc(sizeof(PwSearch));
	if(new == NULL) {
		pw_abort("Failed to allocate memory to hold search details!");
	}

	new->search_term = malloc(STRING_LONG);
	if(new->search_term == NULL) {
		pw_abort("Failed to allocate memory to hold search term!");
	}
	new->search_term[0] = 0;

	return new;
}

/*
 * String checking only case insensitive using gnu glibc
 */
static char*
search_strcasestr(char *haystack, char *needle){
	// Never matches if null/empty string given
	if(haystack == NULL) {
		return 0;
	}
	if(strlen(haystack) == 0) {
		return 0;
	}

#ifdef HAVE_STRCASESTR
	return (char*)strcasestr(haystack, needle);
#else
	return (char*)strstr(haystack, needle);
#endif
}


PWSearchResult* 
_search_add_if_matches(PWSearchResult* current, Pw* entry, PWList* list) {
	PWSearchResult* next = NULL;

	// Did we get an entry of a list?
	if(entry != NULL) {
		if(search_strcasestr(entry->name, options->search->search_term)
			 || search_strcasestr(entry->host, options->search->search_term)
			 || search_strcasestr(entry->user, options->search->search_term)
			 || search_strcasestr(entry->passwd, options->search->search_term)
			 || search_strcasestr(entry->launch, options->search->search_term)
		) {
			next = malloc( sizeof(PWSearchResult) );
			next->entry = entry;
			next->sublist = list;
			debug("Matched entry on host '%s'", entry->host);
		}
	} else {
		if(search_strcasestr(list->name, options->search->search_term)) {
			next = malloc( sizeof(PWSearchResult) );
			next->sublist = list;
			next->entry = NULL;
			debug("Matched sublist '%s'", list->name);
		}
	}

	// If we matched, append
	if(next == NULL) {
		return current;
	} else {
		if(current == NULL) {
			// First hit
			search_results = next;
		} else {
			// Additional hit, append
			current->next = next;
		}
		// For now, nothing follows us
		next->next = NULL;
		// We are the new current entry
		return next;
	}
}


int
search_apply()
{
	PWList *stack[MAX_SEARCH_DEPTH];
	PWList *tmpList = NULL; 
	Pw *tmp = NULL; 
	int depth;
	int stepping_back;

	PWSearchResult *cur = NULL;

	// Tidy up any existing search results
	if(search_results != NULL) {
		_search_free();
	}
	// If no search term, then nothing to do!
	if( search_active(options->search) == 0 ) {
		return 1;
	}

	// Make sure we have a clean search stack so we won't get confused
	for(depth=0; depth<MAX_SEARCH_DEPTH; depth++) {
		stack[depth] = NULL;
	}

	// Setup for start
	depth = 0;
	tmpList = pwlist;
	stepping_back = 0;

	// Find anything we like the look of
	while(depth >= 0) {
		// Any sublists?
		if(!stepping_back && 
				tmpList->sublists != NULL && depth < MAX_SEARCH_DEPTH) {
			// Prepare to descend
			stack[depth] = tmpList;
			depth++;
			tmpList = tmpList->sublists;

			// Test first child
			cur = _search_add_if_matches(cur, NULL, tmpList);

			// Descend into first child
			continue;
		}
		stepping_back = 0;

		// Any entries?
		if(tmpList->list) {
			tmp = tmpList->list;
			while(tmp != NULL) {
				// Test this entry
				cur = _search_add_if_matches(cur, tmp, tmpList);
				// Next entry
				tmp = tmp->next;
			}
		}

		// Next sibling if there is one
		if(tmpList->next != NULL) {
			tmpList = tmpList->next;
			// Test sibling
			cur = _search_add_if_matches(cur, NULL, tmpList);
			// Process sibling
			continue;
		}

		// Otherwise step up
		depth--;
		stepping_back = 1;
		if(depth >= 0) {
			tmpList = stack[depth];
			stack[depth] = NULL;
		}
	}
	
	// All done
	return 1;
}

int 
search_remove()
{
	// Put things back how they should have been
	current_pw_sublist = pwlist;
	current_pw_sublist->current_item = -1;

	// Free the memory held by the search results
	_search_free();

	// Clear the search term too
	options->search->search_term[0] = 0;

	// Back to the old screen
	uilist_refresh();
}

int 
_search_free()
{
	PWSearchResult *cur;
	PWSearchResult *next;

	// Free the memory held by the search results
	cur = search_results;
	while(cur != NULL) {
		next = cur->next;
		free(cur);
		cur = next;
	}
	search_results = NULL;
}

void
search_get()
{
	char c;
	if(options->search == NULL) {
		debug("No options->search");
	} else {
		if(options->search->search_term == NULL) {
			debug("No options->search->search_term");
		} else {
			debug("Len was %d", strlen(options->search->search_term));
		}
	}

	ui_statusline_ask_str("String to search for: ", options->search->search_term, STRING_MEDIUM);

	search_apply();

	current_pw_sublist->current_item = -1;
	uilist_refresh();
}


int
search_alert(PwSearch* srch)
{
	char alert[80];	

	if( search_active(srch) == 0 ) {
		return 1;
	}

	if(search_results == NULL) {
		sprintf(alert, " (No results found for '%s')", srch->search_term);
	} else {
		sprintf(alert, " (Search results for '%s')", srch->search_term);
	}

	ui_statusline_clear();
	ui_statusline_msg(alert);
}


int search_active(PwSearch* srch)
{
	if( (srch == NULL) || (srch->search_term == NULL) ){
		/* no search object */
		return 0;
	}
	if( strlen(srch->search_term) == 0 ){
		/* no search */
		return 0;
	}
	return 1;
}

Deleted src/actions.c.

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
/*
 *  PWman - Password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <ui.h>
#include <pwman.h>
#include <gnupg.h>

extern Pw * uilist_get_highlighted_item();
extern PWList * uilist_get_highlighted_sublist();
extern PWList * pwlist_new(char*);
extern PWSearchResult * uilist_get_highlighted_searchresult();
extern char *pwgen_ask();

int disp_h = 15, disp_w = 60;
extern int curitem;
extern WINDOW *bottom;

int
action_list_add_pw()
{
	Pw *pw;
	InputField fields[] = {
		{"Name:\t", NULL, STRING_MEDIUM, STRING},
		{"Host:\t", NULL, STRING_MEDIUM, STRING},
		{"User:\t", NULL, STRING_MEDIUM, STRING},
		{"Password:\t", NULL, STRING_SHORT, STRING, pwgen_ask},
		{"Launch Command:\t", NULL, STRING_LONG, STRING}
	};
	int i, x;

	pw = pwlist_new_pw(); 
	ui_statusline_ask_str(fields[0].name, pw->name, STRING_MEDIUM);
	ui_statusline_ask_str(fields[1].name, pw->host, STRING_MEDIUM);
	ui_statusline_ask_str(fields[2].name, pw->user, STRING_MEDIUM);
/*
		int x = strlen(msg) + 5;

	if(input == NULL){
		input = malloc(len);
	}
	statusline_clear();
	statusline_msg(msg);

	echo();
	show_cursor();
	mvwgetnstr(bottom, 1, x, input, len);
	noecho();
	hide_cursor();

	statusline_clear();*/

	ui_statusline_ask_str_with_autogen(fields[3].name, pw->passwd, STRING_SHORT, fields[3].autogen, 0x07);
/*	statusline_msg(fields[3].name);
	x = strlen(fields[3].name) + 5;

	if((i = getch()) == 0x07){
		pw->passwd = fields[3].autogen();
	} else {
		echo();
		show_cursor();
		mvwgetnstr(bottom, 1, x, pw->passwd, PASS_LEN);
		mvwaddch(bottom, 1, x, i);
		wmove(bottom, 1, x+1);
		noecho();
		hide_cursor();
		statusline_clear();
	}*/
	
	ui_statusline_ask_str(fields[4].name, pw->launch, STRING_LONG);
	
	fields[0].value = pw->name;
	fields[1].value = pw->host;
	fields[2].value = pw->user;
	fields[3].value = pw->passwd;
	fields[4].value = pw->launch;

	i = action_yes_no_dialog(fields, (sizeof(fields)/sizeof(InputField)), NULL, "Add this entry");

	if(i){
		pwlist_add_ptr(current_pw_sublist, pw);
		ui_statusline_msg("New password added");
	} else {
		pwlist_free_pw(pw);
		ui_statusline_msg("New password cancelled");
	}

	uilist_refresh();
}

int
action_edit_pw(Pw *pw)
{
	InputField fields[] = {
		{"Name:\t", NULL, STRING_MEDIUM, STRING},
		{"Host:\t", NULL, STRING_MEDIUM, STRING},
		{"User:\t", NULL, STRING_MEDIUM, STRING},
		{"Password:\t", NULL, STRING_SHORT, STRING, pwgen_ask},
		{"Launch Command:\t", NULL, STRING_LONG, STRING}
	};

	if(pw == NULL){
		return -1;
	}
	/*
	 * Get specified password
	 */

	fields[0].value = pw->name;
	fields[1].value = pw->host;
	fields[2].value = pw->user;
	fields[3].value = pw->passwd;
	fields[4].value = pw->launch;

	/*
	 * initialize the info window
	 */

	action_input_dialog(fields, (sizeof(fields)/sizeof(InputField)), "Edit Password");
}

int 
action_list_rename()
{
	Pw* curpw;
	PWList* curpwl;
	char *new_name;

	new_name = malloc(STRING_MEDIUM);

	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			curpw = uilist_get_highlighted_item();
			if(curpw){
				ui_statusline_ask_str("New Name", new_name, STRING_MEDIUM);
				if(strlen(new_name) > 0) {
					pwlist_rename_item(curpw, new_name);
				}
			}
			break;
		case PW_SUBLIST:
			curpwl = uilist_get_highlighted_sublist();
			if(curpwl){
				ui_statusline_ask_str("New Sublist Name", new_name, STRING_MEDIUM);
				if(strlen(new_name) > 0) {
					pwlist_rename_sublist(curpwl, new_name);
				}
			}
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}

	uilist_refresh();
}

int
action_edit_options()
{
	InputField fields[] = {
		{"GnuPG Path:\t", options->gpg_path, STRING_LONG, STRING},
		{"GnuPG ID:\t", options->gpg_id, STRING_LONG, STRING},
		{"Password File:\t", options->password_file, STRING_LONG, STRING},
		{"Passphrase Timeout(in minutes):\t", &options->passphrase_timeout, STRING_SHORT, INT}
	};

	action_input_dialog(fields, (sizeof(fields)/sizeof(InputField)), "Edit Preferences");

	write_options = TRUE;
}

int 
action_input_dialog_draw_items(WINDOW* dialog_win, InputField *fields, 
		int num_fields, char *title, char *msg)
{
	int i, h = 0;

	wclear(dialog_win);
	
	box(dialog_win, 0, 0);

	if(title){
		wattron(dialog_win, A_BOLD);
		i = strlen(title);
		h += 2;
		mvwaddstr(dialog_win, h, (disp_w - i)/2, title);
		wattroff(dialog_win, A_BOLD);
	}

	/* loop through fields */
	for(i = 0; i < num_fields; i++){
		h += 2;
		if(fields[i].type == STRING){
			mvwprintw(dialog_win, h, 3,
				"%d - %s %s", (i+1), fields[i].name, (char*)fields[i].value);
		} else if(fields[i].type == INT){
			mvwprintw(dialog_win, h, 3,
				"%d - %s %d", (i+1), fields[i].name, *((int*)fields[i].value) );
		} else if(fields[i].type == INFORMATION){
			mvwprintw(dialog_win, h, 3,
				"%d - %s", (i+1), fields[i].name);
		}
	}

	wattron(dialog_win, A_BOLD);

	if(msg){
		i = strlen(msg);
		h += 2;
		mvwaddstr(dialog_win, h, (disp_w - i)/2, msg);
	}

	wattroff(dialog_win, A_BOLD);

	/*
	 * do final stuff the put all together
	 */
	wrefresh(dialog_win);
}

int 
action_input_dialog(InputField *fields, int num_fields, char *title)
{
	int ch, i;
	char *ret;
	WINDOW *dialog_win;
	char msg[] = "(press 'q' to return to list)";
	char msg2[80];
	/*
	 * initialize the info window
	 */
	if(title){
		disp_h = ((num_fields+2) * 2) + 3;
	} else {
		disp_h = ((num_fields+1) * 2) + 3;
	}
	
	dialog_win = newwin(disp_h, disp_w, (LINES - disp_h)/2, (COLS - disp_w)/2);
	keypad(dialog_win, TRUE);

	action_input_dialog_draw_items(dialog_win, fields, num_fields, title, msg);
	/*
	 * actions loop
	 */
	while((ch = wgetch(dialog_win)) != 'q'){
		if(!options->readonly) {
			if( (ch >= '1') && (ch <= NUM_TO_CHAR(num_fields)) ){
				i = CHAR_TO_NUM(ch);
				if(fields[i].autogen != NULL){
					fields[i].value = (char*)ui_statusline_ask_str_with_autogen(
								fields[i].name, (char*)fields[i].value, 
								fields[i].max_length, fields[i].autogen, 0x07); 
				} else if(fields[i].type == STRING){
					fields[i].value = (char*)ui_statusline_ask_str(fields[i].name, 
								(char*)fields[i].value, fields[i].max_length);
				} else if(fields[i].type == INT){
					ui_statusline_ask_num(fields[i].name, (int*)fields[i].value);
				} else if(fields[i].type == INFORMATION){
					// Easy, do nothing!
				}
				action_input_dialog_draw_items(dialog_win, fields, num_fields, title, msg);
			} else if(ch == 'l'){
				delwin(dialog_win);
				action_list_launch();
				break;
			}	
		} else {
			statusline_readonly();
		}
	}
	/*
	 * clean up
	 */
	delwin(dialog_win);
	uilist_refresh();
}

int 
action_input_gpgid_dialog(InputField *fields, int num_fields, char *title)
{
	int i, valid_id;
	int ch = '1', first_time = 1;
	char *ret;
	WINDOW *dialog_win;
	char msg[] = "(press 'q' when export recipient list is complete)";
	char msg2[80];
	/*
	 * initialize the info window
	 */
	disp_h = ((num_fields+2) * 2) + 3;
	dialog_win = newwin(disp_h, disp_w, (LINES - disp_h)/2, (COLS - disp_w)/2);
	keypad(dialog_win, TRUE);

	action_input_dialog_draw_items(dialog_win, fields, num_fields, title, msg);

	/*
	 * actions loop - ignore read only as not changing main state
	 */
	while(first_time || ((ch = wgetch(dialog_win)) != 'q')){
		// On first loop, drop straight into recipient 1
		first_time = 0;

		if( (ch >= '1') && (ch <= NUM_TO_CHAR(num_fields)) ){
			i = CHAR_TO_NUM(ch);
			fields[i].value = (char*)ui_statusline_ask_str(fields[i].name, 
								(char*)fields[i].value, fields[i].max_length);
			
			// Now verify it's a valid recipient
			if(strlen(fields[i].value)) {
				valid_id = gnupg_check_id(fields[i].value);
				if(valid_id == 0) {
					// Good, valid id
				} else {
					// Invalid id. Warn and blank
					if(valid_id == -2) {
					   snprintf(msg2, 80, "Key expired for '%s'", (char*)fields[i].value);
					} else {
					   snprintf(msg2, 80, "Invalid recipient '%s'", (char*)fields[i].value);
					}
					ui_statusline_msg(msg2);
					snprintf(fields[i].value, STRING_LONG, "");
				}

				// Redraw display
				action_input_dialog_draw_items(dialog_win, fields, num_fields, title, msg);
			}
		}
	}

	/*
	 * clean up
	 */
	delwin(dialog_win);
	uilist_refresh();
}

int 
action_yes_no_dialog(InputField *fields, int num_fields, char *title, char *question)
{
	int ch, i;
	char *ret;
	WINDOW *dialog_win;

	/*
	 * initialize the info window
	 */
	if(title){
		disp_h = ((num_fields+2) * 2) + 3;
	} else {
		disp_h = ((num_fields+1) * 2) + 3;
	}
	
	dialog_win = newwin(disp_h, disp_w, (LINES - disp_h)/2, (COLS - disp_w)/2);
	keypad(dialog_win, TRUE);

	action_input_dialog_draw_items(dialog_win, fields, num_fields, title, NULL);
	
	i = ui_statusline_yes_no(question, 1);

	/*
	 * clean up
	 */
	delwin(dialog_win);
	uilist_refresh();

	return i;
}

int
action_list_add_sublist()
{
	char *name;
	PWList *sublist, *iter;

	name = malloc(STRING_MEDIUM);
	ui_statusline_ask_str("Sublist Name:", name, STRING_MEDIUM);
	for(iter = current_pw_sublist->sublists; iter != NULL; iter = iter->next){
		if( strcmp(iter->name, name) == 0){
			free(name);
			return -1;
		}
	}
	sublist = pwlist_new(name);

	pwlist_add_sublist(current_pw_sublist, sublist);
	uilist_refresh();
}

int
action_list_at_top_level()
{
	if(current_pw_sublist->parent){
		action_list_up_one_level();
		uilist_refresh();
		return 0;
	} else {
		return 1;
	}
}

int
action_list_select_item()
{
	Pw* curpw;
	PWList* curpwl;
	PWSearchResult* cursearch;

	// Are they searching, or in normal mode?
	if(search_results != NULL) {
		cursearch = uilist_get_highlighted_searchresult();
		curpwl = cursearch->sublist;
		curpw = cursearch->entry;

		if(curpw){
			action_edit_pw(curpw);
		} else if(curpwl){
			// Quite out of searching
			search_remove();

			// Now display the selected sublist
			current_pw_sublist = curpwl;
			uilist_refresh();
		}
	} else {
		switch(uilist_get_highlighted_type()){
			case PW_ITEM:
				curpw = uilist_get_highlighted_item();
				if(curpw){
					action_edit_pw(curpw);
				}
				break;
			case PW_SUBLIST:
				curpwl = uilist_get_highlighted_sublist();
				if(curpwl){
					current_pw_sublist = curpwl;
					uilist_refresh();
				}
				break;
			case PW_UPLEVEL:
				action_list_up_one_level();
				break;
			case PW_NULL:
			default:
				/* do nothing */
				break;
		}
	}
}

int
action_list_delete_item()
{
	Pw* curpw;
	PWList* curpwl;
	int i;
	char str[STRING_LONG];
	
	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			curpw = uilist_get_highlighted_item();
			if(curpw){
				snprintf(str, STRING_LONG, "Really delete \"%s\"", curpw->name);
				i = ui_statusline_yes_no(str, 0);
				if(i){
					pwlist_delete_pw(current_pw_sublist, curpw);
					ui_statusline_msg("Password deleted");
				} else {
					ui_statusline_msg("Password not deleted");
				}	
			}
			break;
		case PW_SUBLIST:
			curpwl = uilist_get_highlighted_sublist();
			if(curpwl){
				snprintf(str, STRING_LONG, "Really delete Sublist \"%s\"", curpwl->name);
				i = ui_statusline_yes_no(str, 0);
				if(i){
					pwlist_delete_sublist(curpwl->parent, curpwl);
					ui_statusline_msg("Password Sublist deleted");
				} else {
					ui_statusline_msg("Password not deleted");
				}
			}
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}
	uilist_refresh();
}

int
action_list_move_item()
{
	Pw* curpw;
	PWList *curpwl, *iter;
	int i;
	char str[STRING_LONG];
	char answer[STRING_MEDIUM];

	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			curpw = uilist_get_highlighted_item();
			if(curpw){
				while(1){
					snprintf(str, STRING_LONG, "Move \"%s\" to where?", curpw->name);
					ui_statusline_ask_str(str, answer, STRING_MEDIUM);
					
					/* if user just enters nothing do nothing */
					if(answer[0] == 0){
						return 0;
					}
					
					for(iter = current_pw_sublist->sublists; iter != NULL; iter = iter->next){
						if( strcmp(iter->name, answer) == 0 ){
							pwlist_detach_pw(current_pw_sublist, curpw);
							pwlist_add_ptr(iter, curpw);
							uilist_refresh();
							return 0;
						}
					}
					ui_statusline_msg("Sublist does not exist, try again");
					getch();
				}
			}
			break;
		case PW_SUBLIST:
			curpwl = uilist_get_highlighted_sublist();
			if(curpwl){
				while(1){
					snprintf(str, STRING_LONG, "Move sublist \"%s\" to where?", curpwl->name);
					ui_statusline_ask_str(str, answer, STRING_MEDIUM);
					
					/* if user just enters nothing, do nothing */
					if(answer[0] == 0){
						return 0;
					}
					if( strcmp(answer, curpwl->name) == 0 ){
						return 0;
					}

					for(iter = current_pw_sublist->sublists; iter != NULL; iter = iter->next){
						if( strcmp(iter->name, answer) == 0 ){
							pwlist_detach_sublist(current_pw_sublist, curpwl);
							pwlist_add_sublist(iter, curpwl);
							uilist_refresh();
							return 0;
						}
					}
					ui_statusline_msg("Sublist does not exist, try again");
					getch();
				}
			}
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}
}

int
action_list_move_item_up_level()
{
	Pw* curpw;
	PWList *curpwl, *iter;
	int i;
	char str[STRING_LONG];
	char answer[STRING_MEDIUM];

	// Do nothing if searching
	if(search_results != NULL) {
		return;
	}

	// Do the right thing based on type
	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			curpw = uilist_get_highlighted_item();
			if(curpw && current_pw_sublist->parent){
				pwlist_detach_pw(current_pw_sublist, curpw);
				pwlist_add_ptr(current_pw_sublist->parent, curpw);
				uilist_refresh();
			}
			break;
		case PW_SUBLIST:
			curpwl = uilist_get_highlighted_sublist();
			if(curpwl && current_pw_sublist->parent){
				pwlist_detach_sublist(current_pw_sublist, curpwl);
				pwlist_add_sublist(current_pw_sublist->parent, curpwl);
				uilist_refresh();
			}
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}
}

int
action_list_up_one_level()
{
	/* move up one sublist */
	if(current_pw_sublist->parent){
		current_pw_sublist = current_pw_sublist->parent;
		uilist_refresh();
	}
}
	
int
action_list_export()
{
	Pw* curpw;
	PWList *curpwl;

	debug("list_export: enter switch");
	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			debug("list_export: is a pw");
			curpw = uilist_get_highlighted_item();
			if(curpw){
				pwlist_export_passwd(curpw);
			}
			break;
		case PW_SUBLIST:
			debug("list_export: is a pwlist");
			curpwl = uilist_get_highlighted_sublist();
			if(curpwl){
				pwlist_export_list(curpwl);
			}
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}
}

void _create_information_field(char* name, InputField* field)
{
	field->name = name;
	field->value = NULL;
	field->max_length = 0;
	field->type = INFORMATION;
}

int
action_list_locate()
{
	int depth = 0, count = 0;
	char* currentName;
	InputField* fields;
	Pw* curpw = NULL;
	PWList *curpwl = NULL;
	PWList *parent = NULL;
	PWSearchResult* cursearch;

	if(search_results != NULL) {
		cursearch = uilist_get_highlighted_searchresult();
		curpwl = cursearch->sublist;
		curpw = cursearch->entry;

		if(curpw) {
			parent = curpwl;
		} else {
			parent = curpwl->parent;
		}
	} else {
		parent = current_pw_sublist;
		switch(uilist_get_highlighted_type()){
			case PW_ITEM:
				curpw = uilist_get_highlighted_item();
				break;
			case PW_SUBLIST:
				curpwl = uilist_get_highlighted_sublist();
				break;
			default:
				/* do nothing */
				break;
		}
	}

	if(curpw) {
		currentName = curpw->name;
		depth = 1;
	} else if(curpwl) {
		currentName = curpwl->name;
		depth = 1;
	}

	// Figure out how many parents we have
	curpwl = parent;
	while(curpwl){
		curpwl = curpwl->parent;
		depth++;
	}
	count = depth;

	// Now grab their names
	fields = calloc(sizeof(InputField), depth);
	if(currentName){
		depth--;
		_create_information_field(currentName, &fields[depth]);
	}
	curpwl = parent;
	while(curpwl){
		depth--;
		_create_information_field(curpwl->name, &fields[depth]);
		curpwl = curpwl->parent;
	}

	// Have it rendered
	action_input_dialog(fields, count, "Location of Item");

	// All done, tidy up
	free(fields);
}

int
action_list_launch()
{
	int i;
	Pw* curpw;
	char msg[STRING_LONG];

	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			debug("list_launch: is a pw");
			curpw = uilist_get_highlighted_item();
			if(curpw){
				i = launch(curpw);
				snprintf(msg, STRING_LONG, "Application exited with code %d", i);
				ui_statusline_msg(msg);
			}
			break;
		case PW_SUBLIST:
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}
}

int
action_list_read_file()
{
	pwlist_free_all();
	if(pwlist_read_file() != 0){
		pwlist = pwlist_new("Main");
		current_pw_sublist = pwlist;
	}
	uilist_refresh();
	return -1;
}

int
action_list_move_item_up()
{
	Pw* curpw;
	PWList *curpwl;
	int worked = 0;

	// Do nothing if searching
	if(search_results != NULL) {
		return;
	}

	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			curpw = uilist_get_highlighted_item();
			worked = pwlist_change_item_order(curpw, current_pw_sublist, 1);
			break;
		case PW_SUBLIST:
			curpwl = uilist_get_highlighted_sublist();
			worked = pwlist_change_list_order(curpwl, 1);
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}

	if(worked) {
		uilist_up();
	}
}

int 
action_list_move_item_down()
{
	Pw* curpw;
	PWList *curpwl;
	int worked = 0;

	// Do nothing if searching
	if(search_results != NULL) {
		return;
	}

	switch(uilist_get_highlighted_type()){
		case PW_ITEM:
			curpw = uilist_get_highlighted_item();
			worked = pwlist_change_item_order(curpw, current_pw_sublist, 0);
			break;
		case PW_SUBLIST:
			curpwl = uilist_get_highlighted_sublist();
			worked = pwlist_change_list_order(curpwl, 0);
			break;
		case PW_UPLEVEL:
		case PW_NULL:
		default:
			/* do nothing */
			break;
	}

	if(worked) {
		uilist_down();
	}
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted src/convert_pwdb.c.

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
/*
 *  Convert_PWDB - Convert old pwman files into the new format
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#define STR_LEN 255
#define CONVERT_DB_PACKAGE "Convert_PWDB"
#define CONVERT_DB_VERSION "0.1.0"

#include <libxml/parser.h>
#include <stdlib.h>
#include <stdio.h>
#include <pwman.h>

static void show_version();
static void show_usage(char*);

struct ConvertDB_Options {
	char *gpg_id;
	char *infile;
	char *outfile;
} convertdb_options;

int export = 0;

void
debug(char *fmt, ... )
{
#ifdef DEBUG
	va_list ap;
	int d, c;
	char *s;

	fputs("Convert_PWDB Debug% ", stderr);
	
	va_start(ap, fmt);
	while(*fmt){
		if(*fmt == '%'){
			switch(*++fmt){
				case 's': 	/* string */
					s = va_arg(ap, char*);
					fputs(s, stderr);
					break;
				case 'd':	/* int */
					d = va_arg(ap, int);
					fprintf(stderr, "%d", d);
					break;
				case 'c':	/* char */
					c = va_arg(ap, int);
					fputc(c, stderr);
					break;
				default:
					fputc('%', stderr);
					fputc(*fmt, stderr);
					break;
			}
		} else {
			fputc(*fmt, stderr);
		}
		*fmt++;
	}
	va_end(ap);
	fputc('\n', stderr);
#endif
}

PWList *
new_pwlist(char *name)
{
	PWList *new;
	new = malloc( sizeof(PWList) );
	new->name = malloc(STRING_MEDIUM);
	strncpy(new->name, name, STRING_MEDIUM);
	new->parent = NULL;
	new->list = NULL;
	new->sublists = NULL;
	debug("new_pwlist: %s", name);

	return new;
}

int 
free_pwlist(PWList *old)
{
	Pw *current, *next;
	PWList *curlist, *nlist;

	if(old == NULL){
		return 0;
	}
	for(current = old->list; current != NULL; current = next){
		next = current->next;

		free_pw(current);
	}
	for(curlist = old->sublists; curlist != NULL; curlist = nlist){
		nlist = curlist->next;

		free_pwlist(curlist);
	}
	
	free(old->name);
	free(old);
	old = NULL;
	return 0;
}

Pw*
new_pw()
{
	Pw *new;
	new = malloc(sizeof(Pw));
	new->id = 0;
	new->name = malloc(STRING_MEDIUM);
	new->host = malloc(STRING_MEDIUM);
	new->user = malloc(STRING_MEDIUM);
	new->passwd = malloc(STRING_SHORT);
	new->launch = malloc(STRING_LONG);

	memset(new->name, 0, STRING_MEDIUM);
	memset(new->host, 0, STRING_MEDIUM);
	memset(new->user, 0, STRING_MEDIUM);
	memset(new->passwd, 0, STRING_SHORT);
	memset(new->launch, 0, STRING_LONG);
	
	return new;
}

int
free_pw(Pw *old)
{
	free(old->name);
	free(old->user);
	free(old->host);
	free(old->passwd);
	free(old->launch);
	free(old);
}

int
add_pw_ptr(PWList *list, Pw *new)
{
	Pw *current;
	
	if(list == NULL){
		debug("add_pw_ptr : Bad PwList");
		return -1;
	}
	if(new == NULL){
		debug("add_pw_ptr : Bad Pw");
		return -1;
	}
	if(list->list == NULL){
		list->list = new;
		new->next = NULL;
		return 0;
	}

	debug("add_pw_ptr: add to list");
	current = list->list;
	while(current->next != NULL){
		current = current->next;
	}
	current->next = new;
	new->next = NULL;

	return 0;
}


int 
write_password_node(xmlNodePtr root, Pw *pw)
{
	xmlNodePtr node;

	node = xmlNewChild(root, NULL, (xmlChar*)"PwItem", NULL);
	xmlNewChild(node, NULL, (xmlChar*)"name", (xmlChar*)pw->name);
	xmlNewChild(node, NULL, (xmlChar*)"host", (xmlChar*)pw->host);
	xmlNewChild(node, NULL, (xmlChar*)"user", (xmlChar*)pw->user);
	xmlNewChild(node, NULL, (xmlChar*)"passwd", (xmlChar*)pw->passwd);
	xmlNewChild(node, NULL, (xmlChar*)"launch", (xmlChar*)pw->launch);
}

int
write_pwlist(xmlNodePtr parent, PWList *pwlist)
{
	xmlNodePtr node;
	Pw* iter;

	node = xmlNewChild(parent, NULL, (xmlChar*)"PwList", NULL);
	xmlSetProp(node, (xmlChar*)"name", (xmlChar*)pwlist->name);

	for(iter = pwlist->list; iter != NULL; iter = iter->next){
		write_password_node(node, iter);
	}
}

xmlDocPtr
write_new_doc(PWList *pwlist)
{
	char vers[5];
	xmlDocPtr doc;
	xmlNodePtr root;

	if(pwlist == NULL){
		puts("write_new_doc: bad password data");
		exit(-1);
	}
	snprintf(vers, 5, "%d", FF_VERSION);
	doc = xmlNewDoc((xmlChar*)"1.0");

	if(!export){
		root = xmlNewDocNode(doc, NULL, (xmlChar*)"PWMan_PasswordList", NULL);
		xmlSetProp(root, "version", vers);
		write_pwlist(root, pwlist);
	} else {
		root = xmlNewDocNode(doc, NULL, (xmlChar*)"PWMan_Export", NULL);
		xmlSetProp(root, "version", vers);
		write_password_node(root, pwlist->list);	
	}

	xmlDocSetRootElement(doc, root);

	return doc;
}

Pw *
read_pw_node(xmlNodePtr parent)
{
	Pw *new;
	xmlNodePtr node;
	char *text;

	new = new_pw();

	for(node = parent->children; node != NULL; node = node->next){
		if(!node || !node->name){
			debug("read_pw_node: fucked node");
		} else if( strcmp((char*)node->name, "name") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->name, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "user") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->user, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "passwd") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->passwd, text, STRING_SHORT);
		} else if( strcmp((char*)node->name, "host") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->host, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "launch") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->launch, text, STRING_LONG);
		} else {
			debug("read_pw_node: unrecognised node \"%s\"", node->name);
		}
	}
	return new;
}

PWList*
parse_old_doc(xmlDocPtr doc)
{
	PWList *pwlist;
	Pw *pw;
	xmlNodePtr root, node;

	pwlist = new_pwlist("Main");

	if(!doc){
		debug("parse_old_doc: Bad xmlDocPtr");
		return NULL;
	}
	root = xmlDocGetRootElement(doc);
	
	if(!root || !root->name){
		debug("parse_old_doc: Badly formed data");
		return NULL;
	}
	if( strcmp(root->name, "PWMan_Export") == 0){
		export = 1;
	} else if( strcmp(root->name, "PWMan_List") == 0){
		export = 0;
	} else {
		debug("parse_old_doc: Not a pwman file");
		return NULL;
	}
	for(node = root->children; node != NULL; node = node->next){
		if(!node || !node->name){
			debug("parse_old_doc: Bad xml Node");
		} else if( strcmp((char*)node->name, "PW_Item") == 0){
			pw = read_pw_node(node);
			add_pw_ptr(pwlist, pw);
		} else {
			debug("parse_old_doc: Unrecognised xml Node - \"%s\"", node->name);
		}
	}

	if(pwlist->list){
		return pwlist;
	} else {
		fputs("Unrecognised file format\n", stderr);
		exit(-1);
	}
}

char *
add_to_buf(char *buf, char *new)
{
	size_t size;

	if(new == NULL){
		return buf;
	} 
	if(buf == NULL){
		buf = malloc(strlen(new)+1);
		strncpy(buf, new, strlen(new)+1);
		return buf;
	}

	size = strlen(buf) + strlen(new) + 1;
	buf = (char*)realloc(buf, size);
	strncat(buf, new, size);

	return buf;
}

xmlDocPtr
get_data()
{
	FILE *fp;
	char *cmd;
	char *data;
	char buf[STR_LEN];
	xmlDocPtr doc;

	data = NULL;
	cmd = malloc(STR_LEN);
	snprintf(cmd, STR_LEN, "gpg -d %s", convertdb_options.infile);
	debug(cmd);
	fp = popen(cmd, "r");

	while( fgets(buf, STR_LEN, fp) != NULL ){
		data = add_to_buf(data, buf);
	}
	pclose(fp);

	if(!data){
		exit(-1);
	}

	doc = xmlParseMemory(data, strlen(data));

	return doc;
}

void
put_data(xmlDocPtr doc)
{
	FILE *fp;
	char *cmd;

	cmd = malloc(STR_LEN);
	snprintf(cmd, STR_LEN, "gpg -e -r %s -o %s", convertdb_options.gpg_id, convertdb_options.outfile);
	debug(cmd);
	fp = popen(cmd, "w");

#if XML_VERSION >= 20423
	xmlDocFormatDump(fp, doc, TRUE);
#else
	xmlDocDump(fp, doc);
#endif
	
	pclose(fp);
}

void
free_convertdb_options()
{
	free(convertdb_options.infile);
	free(convertdb_options.outfile);
	free(convertdb_options.gpg_id);
}

char *
ask(char *msg)
{
	char * input;

	input = malloc(STR_LEN);

	fputs(msg, stdout);
	fputc('\t', stdout);
	fgets(input, STR_LEN, stdin);

	input[ strlen(input) - 1] = 0;

	return input;
}

void
get_options(int argc, char *argv[])
{
	int i;

	for(i = 0; i < argc; i++){
		if( !strcmp(argv[i], "--help") || !strcmp(argv[i], "-h") ){
			show_usage(argv[0]);
			exit(1);
		} else if( !strcmp(argv[i], "--version") || !strcmp(argv[i], "-v") ){
			show_version();
			exit(1);
		}
	}
	
	if(argc > 1){
		convertdb_options.gpg_id = malloc(STR_LEN);
		strncpy(convertdb_options.gpg_id, argv[1], STR_LEN);
	} else {
		convertdb_options.gpg_id = ask("ID to encrypt new file to:");
	}
	if(argc > 2){
		convertdb_options.infile = malloc(STR_LEN);
		strncpy(convertdb_options.infile, argv[2], STR_LEN);
	} else {
		convertdb_options.infile = ask("File in old format:");
	}
	if(argc > 3){
		convertdb_options.outfile = malloc(STR_LEN);
		strncpy(convertdb_options.outfile, argv[3], STR_LEN);
	} else {
		convertdb_options.outfile = ask("File to write new format to:");
	}
}

int
main(int argc, char *argv[])
{
	xmlDocPtr doc;
	PWList *pwlist;
	
	get_options(argc, argv);

	doc = get_data();
	pwlist = parse_old_doc(doc);
	xmlFreeDoc(doc);
	
	doc = write_new_doc(pwlist);
	put_data(doc);
	xmlFreeDoc(doc);

	free_convertdb_options();
	return 0;
}

static void
show_version()
{
	puts(CONVERT_DB_PACKAGE " v " CONVERT_DB_VERSION);
	puts("Written by Ivan Kelly <ivan@ivankelly.net>\n");
	puts("Copyright (C) 2002 Ivan Kelly");
	puts("This program is free software; you can redistribute it and/or modify");
	puts("it under the terms of the GNU General Public License as published by");
	puts("the Free Software Foundation; either version 2 of the License, or");
	puts("(at your option) any later version.\n");

	puts("This program is distributed in the hope that it will be useful,");
	puts("but WITHOUT ANY WARRANTY; without even the implied warranty of");
	puts("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
	puts("GNU General Public License for more details.\n");

	puts("You should have received a copy of the GNU General Public License");
	puts("along with this program; if not, write to the Free Software");
	puts("Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.\n");
}

static void
show_usage(char *argv_0)
{
	printf("Usage: %s [<gnupg_id> [<oldfile> [<newfile>]]]\n", argv_0);
	puts("Convert Password Database from PWMan versions >= 0.2.1 to new format 0.3.0+\n");
	puts("  --help                 show usage");
	puts("  --version              display version information");
	puts("  <gnupg_id>             GnuPG ID to encrypt new password database to");
	puts("  <oldfile>              password database file in old format");
	puts("  <newfile>              password database file to write in new format\n\n");
	puts("Report bugs to <ivan@ivankelly.net>");
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted src/filter.c.

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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <string.h>
#include <pwman.h>
#include <ui.h>

/*xtern int curitem;*/

PwFilter *
filter_new()
{
	PwFilter *new;

	new = malloc(sizeof(PwFilter));
	if(new == NULL) {
		pw_abort("Failed to allocate memory to hold filtering details!");
	}

	new->field = -1;
	new->filter = malloc(STRING_LONG);
	if(new == NULL) {
		pw_abort("Failed to allocate memory to hold filtering term!");
	}
	new->filter[0] = 0;

	return new;
}

/*
 * String checking only case insensitive using gnu glibc
 */
static char*
filter_strcasestr(char *haystack, char *needle){
	// Never matches if null/empty string given
	if(haystack == NULL) {
		return 0;
	}
	if(strlen(haystack) == 0) {
		return 0;
	}

#ifdef HAVE_STRCASESTR
	return (char*)strcasestr(haystack, needle);
#else
	return (char*)strstr(haystack, needle);
#endif
}

int
filter_apply(Pw *pw, PwFilter* fil)
{
	if( (fil == NULL) || (fil->filter == NULL) ){
		/* no filter object */
		return 1;
	}
	if( strlen(fil->filter) == 0 ){
		/* no filter */
		return 1;
	}
	switch(fil->field){
		case 0:
			if( filter_strcasestr(pw->name, fil->filter) ){
				return 1;
			}					
			break;
		case 1:
			if( filter_strcasestr(pw->host, fil->filter) ){
				return 1;
			}
			break;
		case 2:
			if( filter_strcasestr(pw->user, fil->filter) ){
				return 1;
			}
			break;
		case 3:
			if( filter_strcasestr(pw->launch, fil->filter) ){
				return 1;
			}
			break;
		default:
/*			fprintf(stderr, "Invalid filter field %d\n", fil->field);*/
			break;
	}
	return 0;
}

void
filter_get()
{
	char c;

	ui_statusline_ask_char("Filter which field? (n)ame (h)ost (u)ser (l)aunch n(o)ne", &c, "nhulo\n");
	switch(c){
		case 'n':
			options->filter->field = 0;
			break;
		case 'h':
			options->filter->field = 1;
			break;
		case 'u':
			options->filter->field = 2;
			break;
		case 'l':
			options->filter->field = 3;
			break;
		case 'o':
		default:
			options->filter->field = -1;
			options->filter->filter[0] = 0;

			uilist_refresh();
			return;
			break;
	}
	ui_statusline_ask_str("String to search for: ", options->filter->filter, STRING_MEDIUM);

	current_pw_sublist->current_item = -1;
	uilist_refresh();
}


int
filter_alert(PwFilter* fil)
{
	char alert[80];	

	if( (fil == NULL) || (fil->filter == NULL) ){
		/* no filter object */
		return 1;
	}
	if( strlen(fil->filter) == 0 ){
		/* no filter */
		return 1;
	}
	switch(fil->field){
		case 0:
			sprintf(alert, " (Filtering on name with '%s')", fil->filter);
			break;
		case 1:
			sprintf(alert, " (Filtering on host with '%s')", fil->filter);
			break;
		case 2:
			sprintf(alert, " (Filtering on user with '%s')", fil->filter);
		case 3:
			sprintf(alert, " (Filtering on launch with '%s')", fil->filter);
		default:
/*			fprintf(stderr, "Invalid filter field %d\n", fil->field);*/
			break;
	}

	ui_statusline_clear();
	ui_statusline_msg(alert);
}


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































































































































































































































































































Deleted src/gnupg.c.

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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */


/*
 * define for strings to check for with regex
 * should allow for internationalization
 */

#define GPG_ERR_CANTWRITE	"file create error"
#define GPG_ERR_CANTOPEN 	"can't open"
#define GPG_ERR_BADPASSPHRASE	"bad passphrase"
#define GPG_ERR_NOSECRETKEY	"secret key not available"

/* end defines */

#include <sys/stat.h>
#include <pwman.h>
#include <ui.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <regex.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>

#define STDOUT 0
#define STDIN 1
#define STDERR 2

int passphrase_good = 0;
extern int errno;
extern int write_options;

int gnupg_hit_sigpipe = 0;
static void gnupg_sigpipe_handler()
{
	gnupg_hit_sigpipe = 1;
}

static char *
gnupg_add_to_buf(char *buf, char *new)
{
	size_t size;

	if(new == NULL){
		return buf;
	}
	if(buf == NULL){
		buf = malloc(strlen(new)+1);
		strncpy(buf, new, strlen(new)+1);
		return buf;
	}
	
	size = strlen(buf) + strlen(new) + 1;
	buf = (char*)realloc(buf, size);
	strncat(buf, new, size);
	
	return buf;
}

static int
gnupg_str_in_buf(char *buf, char *check)
{
	regex_t reg;

	debug("str_in_buf: start checking");
	
	if( (buf == NULL) || (check == NULL) ){
		return 0;
	}
	regcomp(&reg, check ,0);
	if(regexec(&reg, buf, 0, NULL , 0) == 0){
		regfree(&reg);
		return 1;
	} else {
		regfree(&reg);
		return 0;
	}
}

static char *
gnupg_expand_filename(char *filename)
{
	char *buf = malloc(STRING_LONG);
	
	if((filename[0] == '~') && getenv("HOME")){
		snprintf(buf, STRING_LONG, "%s%s\0", getenv("HOME"), filename+1);
		strncpy(filename, buf, STRING_LONG);
	}
	free(buf);

	return filename;
}

static int 
gnupg_exec(char *path, char *args[], FILE *stream[3])
{
	int stdin_fd[2];
	int stdout_fd[2];
	int stderr_fd[2];
	int pid, ret;

	pipe(stdin_fd);
	pipe(stdout_fd);
	pipe(stderr_fd);

	pid = fork();

	if( (path == NULL) || (args == NULL) ){
		return -1;
	}

	// Do the right thing with the fork
	if(pid == 0){
		close(stdout_fd[0]);
		close(stdin_fd[1]);
		close(stderr_fd[0]);

		dup2(stdout_fd[1], fileno(stdout));
		dup2(stdin_fd[0], fileno(stdin));
		dup2(stderr_fd[1], fileno(stderr));

		ret = execv(path, args);
		if(ret) {
			pw_abort("Failed to run %s, aborted with error code %d", path, errno);
		}
	} else {
		close(stdout_fd[1]);
		close(stdin_fd[0]);
		close(stderr_fd[1]);

		if(stream != NULL){
			stream[STDOUT] = fdopen(stdout_fd[0], "r");
			stream[STDIN] = fdopen(stdin_fd[1], "w");
			stream[STDERR] = fdopen(stderr_fd[0], "r");
		}
		
		// Mark us as not having had a sigpipe yet
		gnupg_hit_sigpipe = 0;
		signal(SIGPIPE, gnupg_sigpipe_handler);

		return pid;
	}
}

static void
gnupg_exec_end(int pid, FILE *stream[3])
{
	char buf[STRING_LONG];

	// If we hit a problem, report that
	if(gnupg_hit_sigpipe) {
		fputs("GPG hit an error and died...\n", stderr);
		while( fgets(buf, STRING_LONG - 1, stream[STDOUT]) != NULL ){
			fputs(buf, stderr);
		}
		while( fgets(buf, STRING_LONG - 1, stream[STDERR]) != NULL ){
			fputs(buf, stderr);
		}
		// TODO - figure out why we don't get the real error message from
		//  GPG displayed here like one might expect
	}
	signal(SIGPIPE, NULL);

	// Close up
	debug("gnupg_exec_end : close streams");
	if(stream[0]){ fclose(stream[0]); }
	if(stream[1]){ fclose(stream[1]); }
	if(stream[2]){ fclose(stream[2]); }

	debug("waiting for pid %d", pid);
	waitpid(pid, NULL, 0);

	// Bail out if gpg broke
	if(gnupg_hit_sigpipe) {
		exit(-1);
	}
}

static char*
gnupg_find_recp(char *str)
{
	char *user;
	char *start;
	char *end;
	int size;
	debug(str);

	// Is it "<id>" ?
	start = strstr(str,"\"");
	if(start != NULL) {
		start += 1;
		end = strstr(start,"\"");
	} else {
		// Is it ID <id>\n?
		start = strstr(str,"ID");
		if(start != NULL) {
			start += 3;
			end = strstr(start,"\n");
		} else {
			// No idea
			user = "(not sure)";
			return user;
		}
	}

	size = end - start;
	user = malloc(size+1);
	strncpy(user, start, size);
	debug("Recipient is %s", user);
	return user;
}

// Returns 0 if found, -1 if not found, and -2 if found but expired
int
gnupg_check_id(char *id)
{	
	regex_t reg;
	regex_t expired_reg;
	int pid;
	char text[STRING_LONG], idstr[STRING_LONG], keyid[STRING_LONG];
   char exp[STRING_LONG], *args[4];
	FILE *streams[3];
	int id_is_key_id = 0;
	int key_found = 0;
	int key_is_expired = -1;
	
	debug("check_gnupg_id: check gnupg id\n");

	// Check we're given nice input
	if( strchr(id, '%') ){ 
		/* hmm, could be format string bug so tell get lost */
		return -1;
	}

	// Build our expired key matching regexp
	snprintf(exp, STRING_LONG, "^(pub|sub):e:");
	regcomp(&expired_reg, exp, REG_EXTENDED);

	// Is the supplied ID really a key ID?
	// (If it is, it's 8 chars long, and 0-9A-F)
	snprintf(keyid, STRING_LONG, "^[0-9A-Z]{8}$");
	regcomp(&reg, keyid,REG_EXTENDED);
	if(regexec(&reg, id, 0, NULL , 0) == 0) {
		// The supplied ID is a key ID
		id_is_key_id = 1;
		debug("check_gnupg_id: supplied ID was a gnupg key id\n");
	} else {
		debug("check_gnupg_id: supplied ID taken to be an email address\n");
	}

	if(id_is_key_id == 1) {
		// Match on "pub:.:SIZE:type:FULLID:DATE"
		// Where FULLID is 8 chars then the 8 chars we expected
		snprintf(idstr, STRING_LONG, "^pub:.:[0-9]+:[0-9]+:[0-9a-zA-Z]{8}%s:", id);
	} else {
		// Match on "(pub|uid) .... NAME <EMAIL ADDRESS>"
		snprintf(idstr, STRING_LONG, "[^<]*<%s>", id);
	}

	// Fire off GPG to find all our keys
	args[0] = "gpg";
	args[1] = "--with-colons";
	args[2] = "--list-keys";
	args[3] = NULL;

	pid = gnupg_exec(options->gpg_path, args, streams);

	while( fgets(text, STRING_LONG, streams[STDOUT]) ){
		regcomp(&reg, idstr, REG_EXTENDED);
		if(regexec(&reg, text, 0, NULL , 0) == 0){
			// Found the key!
         key_found = 1;

			// Check it isn't also expired
			if(regexec(&expired_reg, text, 0, NULL , 0) == 0) {
            // Only mark as expired if we haven't found another
            //  version that isn't expired
            if(key_is_expired == -1) {
   				key_is_expired = 1;
            }
			} else {
				key_is_expired = 0;
         }
		}
	}
	
   // Tidy up
	gnupg_exec_end(pid, streams);

   // If we found it, return found / found+expired
   if(key_found) {
		if(key_is_expired) {
			return -2; 
		}
		return 0; 
   }

   // Didn't find it
	return -1;
}

/**
 * Get a single GnuPG Recipient ID
 */
void
gnupg_get_id(char *id)
{
	while(1){
		id = ui_statusline_ask_str("GnuPG Recipient ID:", id, STRING_LONG);
		if(id[0] == 0){
			return;
		}
		if(gnupg_check_id(id) == 0){
			return;
		}
		debug("get_gnupg_id: if here is reached id is bad");
		ui_statusline_msg("Bad Recipient, Try again"); getch();
	}
}

/**
 * Get multiple GnuPG Recipient IDs
 */
void
gnupg_get_ids(char **ids, int max_id_num)
{
	InputField fields[max_id_num];
	char names[max_id_num][STRING_LONG];
	int i;

	for(i=0; i<max_id_num; i++) {
		fields[i].name = names[i]; // Needs a local string to write into
		snprintf(fields[i].name, STRING_LONG, "Recipient %d: ", (i+1));
		fields[i].value = ids[i]; // String to write into comes from caller
		fields[i].max_length = STRING_LONG;
		fields[i].type = STRING;
	}

	// Prompt to edit the recipients
	// This will verify the IDs for us
	action_input_gpgid_dialog(fields, max_id_num, "Edit Recipients");
}

char *
gnupg_get_filename(char *filename, char rw)
{
	if(rw == 'r'){
		filename = ui_statusline_ask_str("File to read from:", filename, STRING_LONG);
	} else if(rw == 'w'){
		filename = ui_statusline_ask_str("File to write to:", filename, STRING_LONG);
	} else {
		pw_abort("File request must be for read or write, got '%s'", rw);
	}
}

static const char *
gnupg_get_passphrase()
{
	static char *passphrase = NULL;

/*	passphrase == malloc(V_LONG_STR);*/
	if((time_base >= (time(NULL) - (options->passphrase_timeout*60))) && (passphrase_good == 1)){
		return passphrase;
	}
	
	passphrase_good = 0;

	passphrase = ui_statusline_ask_passwd("Enter GnuPG passphrase (^G to Cancel):", passphrase, 
			STRING_LONG, 0x07); /* 0x07 == ^G */
	passphrase_good = 1;

	return passphrase;
}

void
gnupg_forget_passphrase()
{
	passphrase_good = 0;

	debug("forget_passphrase: passphrase forgotten");
	ui_statusline_msg("Passphrase forgotten");
}

static int 
gnupg_check_executable()
{
	FILE *streams[3];
	char *args[3];
	int pid, count, version[3];
	
	debug("check_gnupg: start");
	if(options->gpg_path == NULL){
		return -1;
	}

	args[0] = "gpg";
	args[1] = "--version";
	args[2] = NULL;
	
	pid = gnupg_exec(options->gpg_path, args, streams);

	/* this might do version checking someday if needed */
	count = fscanf(streams[STDOUT], "gpg (GnuPG) %d.%d.%d", 
			&version[0], &version[1], &version[2]);
	gnupg_exec_end(pid, streams);

	debug("exec ended");
	if(count != 3){
		ui_statusline_msg("WARNING! GnuPG Executable not found"); getch();
		return -1;
	} else {
		debug("check_gnupg: Version %d.%d.%d", version[0], version[1], version[2]);	
		return 0;
	}
}

int
gnupg_write_many(xmlDocPtr doc, char** ids, int num_ids, char* filename)
{
	FILE *streams[3];
	char buf[STRING_LONG];
	char *args[10];
	char *err;
	int pid, i, pos, num_valid_ids;

	debug("gnupg_write: do some checks");	
	if((gnupg_check_executable() != 0) || !filename || (filename[0] == 0)){
		debug("gnupg_write: no gnupg or filename not set");
		return -1;
	}

	// Ensure all IDs are valid, and we have enough
	num_valid_ids = 0;
	for(i=0; i<num_ids; i++) {
		if(ids[i][0] != 0) {
			if(gnupg_check_id(ids[i]) != 0) {
				gnupg_get_id(ids[i]);
				
				if(ids[i][0] == 0) {
					return -1;
				}
			}

			num_valid_ids++;
		}
	}
	debug("gnupg_write: writing to %d recipients", num_valid_ids);
	if(num_valid_ids == 0) {
		return -1;
	}

	debug("gnupg_write: start writing");

	err = NULL;
	args[0] = "gpg";
	args[1] = "-e";
	args[2] = "-a";
	args[3] = "--always-trust"; /* gets rid of error when moving 
				       keys from other machines */
	args[4] = "--yes";
	args[5] = "-o";
	args[6] = gnupg_expand_filename( filename );

	// Add in all the recipients
	pos = 7;
	for(i=0; i<num_ids; i++) {
		if(ids[i][0] != 0) {
			args[pos] = "-r";
			pos++;
			args[pos] = ids[i];
			pos++;
		}
	}
	args[pos] = NULL;

	while(1){
		/* clear err buffer */
		if(err != NULL){ free(err); err = NULL; }

		pid = gnupg_exec(options->gpg_path, args, streams);

#if XML_VERSION >= 20423
		xmlDocFormatDump(streams[STDIN], doc, TRUE);
#else
		xmlDocDump(streams[STDIN], doc);
#endif
		close( fileno(streams[STDIN]) );
		
		while( fgets(buf, STRING_LONG - 1, streams[STDERR]) != NULL ){
			err = gnupg_add_to_buf(err, buf);
		}
		gnupg_exec_end(pid, streams);
		
		debug("gnupg_write: start error checking");
		/*
		 * check for errors(no key, bad pass, no file etc etc)
		 */
		if( gnupg_str_in_buf(err, GPG_ERR_CANTWRITE) ){
			debug("gnupg_write: cannot write to %s", filename);

			snprintf(buf, STRING_LONG, "Cannot write to %s", filename);
			ui_statusline_msg(buf); getch();

			filename = gnupg_get_filename(filename, 'w');
			if(filename[0] == 0){
				return -1;
			}
			continue;
		}
		break;
	}

	ui_statusline_msg("List Saved");
	debug("gnupg_write: file write sucessful");
	
	return 0;
}

int
gnupg_write(xmlDocPtr doc, char* id, char* filename)
{
	return gnupg_write_many(doc, &id, 1, filename);
}

int
gnupg_read(char *filename, xmlDocPtr *doc)
{
	char *args[9], *passphrase, *data, *err, buf[STRING_LONG], *user;
	FILE *streams[3];
	int pid;
	int ret = 0;
	
	if(gnupg_check_executable() != 0){
		*doc = xmlNewDoc((xmlChar*)"1.0");
		return -1;
	}
/*
	if(check_gnupg_passphrase(filename) == -1){
		return -1;
	}*/

	data = NULL;
	err = NULL;
	user = NULL;
	args[0] = "gpg";
	args[1] = "--passphrase-fd";
	args[2] = "0";
	args[3] = "--no-verbose";
	args[4] = "--batch";
	args[5] = "--output";
	args[6] = "-";
	args[7] = gnupg_expand_filename( filename );
	args[8] = NULL;
	
	while(1){
		/* clear buffers */
		if(err != NULL){ free(err); err = NULL; }
		if(data != NULL){ free(data); data = NULL; }
		
		passphrase = (char*)gnupg_get_passphrase();

		if(passphrase == NULL){
			// They hit cancel on the password prompt
			write_options = 0;
			filename[0] = 0;
			ret = 255;
			break;
		}

		pid = gnupg_exec(options->gpg_path, args, streams);

		fputs( passphrase, streams[STDIN]);
		fputc( '\n' , streams[STDIN]);
		fclose(streams[STDIN]);
		streams[STDIN] = NULL;

		debug("gnupg_read: start reading data");
		while( fgets(buf, STRING_LONG - 1, streams[STDOUT]) != NULL ){
			data = gnupg_add_to_buf(data, buf);
		}
		while( fgets(buf, STRING_LONG - 1, streams[STDERR]) != NULL ){
			err = gnupg_add_to_buf(err, buf);
		}
	
		gnupg_exec_end(pid, streams);

		debug("gnupg_read: start error checking");
		debug(err);
		/*
		 * check for errors(no key, bad pass, no file etc etc)
		 */
		if( gnupg_str_in_buf(err, GPG_ERR_BADPASSPHRASE) ){
			debug("gnupg_read: bad passphrase");
			ui_statusline_msg("Bad Passphrase, please re-enter");
			getch();

			passphrase_good = 0;
			continue;
		}
		if( gnupg_str_in_buf(err, GPG_ERR_CANTOPEN) ){
			debug("gnupg_read: cannot open %s", filename);
			snprintf(buf, STRING_LONG, "Cannot open file \"%s\"", filename);
			ui_statusline_msg(buf); getch();

			ret = -1;
			break;
		}
		if( gnupg_str_in_buf(err, GPG_ERR_NOSECRETKEY) ){
			debug("gnupg_read: secret key not available!");
			user = gnupg_find_recp(err);
			snprintf(buf, STRING_LONG, "You do not have the secret key for %s", user);
			ui_statusline_msg(buf); getch();

			ret = 254;
			break;
		}
		break;
	}


	debug("gnupg_read: finished read");
	if(data != NULL){
		debug("gnupg_read: data != NULL");
		*doc = xmlParseMemory(data, strlen(data));
		free(data);
	} else {
		debug("gnupg_read: data is null");
		*doc = xmlNewDoc((xmlChar*)"1.0");
	}
	if(err != NULL){ free(err); }
	if(user != NULL){ free(user); }

	debug("gnupg_read: finished all");

	return ret;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted src/gnupg.h.

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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifndef PW_GNUPG_H
#define PW_GNUPG_H

#include <libxml/tree.h>
#include <libxml/parser.h>

void gnupg_forget_passphrase();

int gnupg_check_id(char*);
void gnupg_get_id(char*);
void gnupg_get_ids(char **, int);

char* gnupg_get_filename(char*, char);
const char* gnupg_get_passphrase();

int gnupg_read(char*, xmlDocPtr*);
int gnupg_write(xmlDocPtr, char*, char*);
int gnupg_write_many(xmlDocPtr, char**, int, char*);

#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































Deleted src/help.h.

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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifndef HELP_H 
#define HELP_H

static char *help[] = {
	"	?		help\n",
	"	q/Q		quit\n",
	"	^L		refresh windows\n",
	"\n",
	"	arrows / j,k	scroll list\n",
	"	enter/space/e	view/edit item\n",
	"	U		move up a level\n",
	"\n",
	"	a		add item\n",
	"	A		add sublist\n",
	"	m		move item/sublist\n",
	"	M		move item/sublist up one level\n",
	"	[		move item up the list\n",
	"	]		move item down the list\n",
	"	r		rename item/sublist\n",
	"	d/del		delete item/sublist\n",
	"	L		locate item/sublist (prints path)\n",
	"\n",
	"	f		enable / disable filtering\n",
	"	/		enable / disable searching\n",
	"\n",
	"	l		launch item\n",
	"	Format:		%u = user\n",
	"			%h = host\n",
	"			%p = password\n",
	"	e.g.	mysql -Dmydb -u%u -p%p -h%h\n",
	"\n",
	"	Editor Help\n",
	"	[#]		edit field denoted by #\n",
	"	i.e.	press 3 to edit field 3\n",
	"\n",
	"	Misc Help\n",
	"	o		edit options\n",
	"	^W		write database to file (save)\n",
	"	^R		read database from file (reload)\n",
	"	I		import password from file\n",
	"	E		export password to file\n",
	"	^G		Generate password\n",
	"	^F		Forget passphrase\n",
	NULL
};

#endif


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































Deleted src/import_export.c.

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
/*
 *  PWMan - password application manager
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <pwman.h>
#include <ui.h>
#include <stdlib.h>
#include <libxml/tree.h>
#include <libxml/parser.h>

int
export_passwd(Pw *pw)
{
	char vers[5];
	char id[STRING_LONG], file[STRING_LONG];
	
	xmlDocPtr doc;
	xmlNodePtr root;

	if(check_gnupg() != 0){
		debug("export_passwd: gnupg not found");
		return -1;
	}
	if(!pw){
		debug("export_passwd: bad password");
		statusline_msg("Bad password");
		return -1;
	}

	get_gnupg_id(id);
	if(id[0] == 0){
		debug("export_passwd: cancel because id is blank");
		return -1;
	}
	
	get_filename(file, 'w');

	debug("export_passwd: construct xml doc");
	snprintf(vers, 5, "%d", FF_VERSION);
	doc = xmlNewDoc((xmlChar*)"1.0");
	
	root = xmlNewDocNode(doc, NULL, (xmlChar*)"PWMan_Export", NULL);

	xmlSetProp(root, "version", vers);
	
	write_password_node(root, pw);

	xmlDocSetRootElement(doc, root);

	gnupg_write(doc, id, file);
	
	xmlFreeDoc(doc);
	return 0;
}

int
export_passwd_list(PWList *pwlist)
{
	char vers[5];
	char id[STRING_LONG], file[STRING_LONG];
	
	xmlDocPtr doc;
	xmlNodePtr root;

	if(check_gnupg() != 0){
		debug("export_passwd_list: gnupg not found");
		return -1;
	}
	if(!pwlist){
		debug("export_passwd_list: bad password");
		statusline_msg("Bad password");
		return -1;
	}

	get_gnupg_id(id);
	if(id[0] == 0){
		debug("export_passwd_list: cancel because id is blank");
		return -1;
	}
	
	get_filename(file, 'w');

	debug("export_passwd_list: construct xml doc");
	snprintf(vers, 5, "%d", FF_VERSION);
	doc = xmlNewDoc((xmlChar*)"1.0");
	
	root = xmlNewDocNode(doc, NULL, (xmlChar*)"PWMan_Export", NULL);

	xmlSetProp(root, "version", vers);
	
	write_pwlist(root, pwlist);

	xmlDocSetRootElement(doc, root);

	gnupg_write(doc, id, file);
	
	xmlFreeDoc(doc);
	return 0;
}

int
import_passwd()
{
	char file[STRING_LONG], *buf, *cmd, *s, *text;
	int i = 0;
	xmlNodePtr node, root;
	xmlDocPtr doc;

	get_filename(file, 'r');

	gnupg_read(file, &doc);	
	
	if(!doc){
		debug("import_passwd: bad data");
		return -1;
	}
	root = xmlDocGetRootElement(doc);
	if(!root || !root->name	|| (strcmp((char*)root->name, "PWMan_Export") != 0) ){
		statusline_msg("Badly Formed password data");
		return -1;
	}
	if( buf = xmlGetProp(root, (xmlChar*)"version") ){
		i = atoi( buf );
	} else {
		i = 0;
	}
	if(i < FF_VERSION){
		statusline_msg("Password Export File in older format, use convert_pwdb");
		return -1;
	}
	
	for(node = root->children; node != NULL; node = node->next){
		if(strcmp(node->name, "PwList") == 0){
			read_pwlist(node, current_pw_sublist);
			break;
		} else if(strcmp(node->name, "PwItem") == 0){
			read_password_node(node, current_pw_sublist);
			break;
		}
	}
	xmlFreeDoc(doc);
	return 0;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































































































































































































































































Deleted src/launch.c.

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
/*
 *  PWman - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <pwman.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>

char * 
launch_find_replace(char *haystack, char* needle, char* cow)
{
	char *pos;
	int len,i;
	char *ret, *ret_p;

	pos = strstr(haystack, needle);
	if(pos == NULL){
		return haystack;
	}

	/*
	 * real ugly shit for 
	 * replacing the strings
	 */
	len = (strlen(haystack) - strlen(needle)) + strlen(cow) + 1;
	ret = malloc(len);
	ret_p = ret;
	i = pos - &haystack[0];
	strncpy(ret_p, haystack, i);
	ret_p += i;
	strcpy(ret_p, cow);
	ret_p += strlen(cow);
	pos += strlen(needle);
	strcpy(ret_p, pos);

	return ret;
}

int 
launch_execute(char *cmd) {
	int pid, status;
	char *argv[4];

	if (cmd == NULL){
		return 1;
	}
	
	pid = fork();
	if (pid == -1){
		return -1;
	}
	if (pid == 0) {
		argv[0] = "pwman_exec";
		argv[1] = "-c";
		argv[2] = cmd;
		argv[3] = NULL;

		execv("/bin/sh", argv);
		exit(127);
	}
	do {
		if (waitpid(pid, &status, 0) == -1) {
			if (errno != EINTR){
				return -1;
			} 
		}else {
			return status;
		}
	} while(1);
}

int
launch(Pw *pw)
{
	int i;
	char *cmd;
	char **cmd_array;

	if((pw == NULL) || (pw->launch == NULL)){
		return -1;
	}
	cmd = launch_find_replace(pw->launch, "%h", pw->host);
	cmd = launch_find_replace(cmd, "%u", pw->user);
	cmd = launch_find_replace(cmd, "%p", pw->passwd);

	def_prog_mode();
	ui_end();

	i = launch_execute(cmd);

	puts("Press any key to continue");
	getch();
	
	ui_init();
	reset_prog_mode();

	return i;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































Deleted src/misc.c.

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
/*
 *  PWMan - Password Management Software
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <pwman.h>
#include <ui.h>

void _stderr_print(char *fmt, va_list ap)
{
	int d, c;
	char *s;

	while(*fmt){
		if(*fmt == '%'){
			switch(*++fmt){
				case 's': 	/* string */
					s = va_arg(ap, char*);
					fputs(s, stderr);
					break;
				case 'd':	/* int */
					d = va_arg(ap, int);
					fprintf(stderr, "%d", d);
					break;
				case 'c':	/* char */
					c = va_arg(ap, int);
					fputc(c, stderr);
					break;
				default:
					fputc('%', stderr);
					fputc(*fmt, stderr);
					break;
			}
		} else {
			fputc(*fmt, stderr);
		}
		*fmt++;
	}
	va_end(ap);
	fputc('\n', stderr);
}

void
pw_abort(char *fmt, ... )
{
	va_list ap;
	va_start(ap, fmt);
	_stderr_print(fmt, ap);
	exit(1);
}

void
debug(char *fmt, ... )
{
#ifdef DEBUG
	va_list ap;
	fputs("PWMan Debug% ", stderr);
	va_start(ap, fmt);
	_stderr_print(fmt, ap);
#endif
}

char *
trim_ws(char *str)
{
	int i;

	for(i = (strlen(str) - 1); i >= 0; i--){
		if(str[i] != ' '){
			return str;
		} else {
			str[i] = 0;
		}
	}
	ui_statusline_msg(str);
}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































































































Deleted src/options.c.

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
/*
 *  PWman - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <pwman.h>
#include <stdlib.h>
#include <libxml/tree.h>
#include <libxml/parser.h>

Options*
options_new()
{
	Options *new;

	new = malloc(sizeof(Options));
	new->gpg_id = malloc(STRING_LONG);
	new->gpg_path = malloc(STRING_LONG);
	new->password_file = malloc(STRING_LONG);
	new->passphrase_timeout = 180;
	new->readonly = FALSE;

	new->filter = filter_new();
	new->search = search_new();

	return new;
}

char*
options_get_file()
{
	char *conf_file;

	conf_file = malloc(STRING_LONG);
	
	if(!getenv("HOME")){
		return NULL;
	} else {
		snprintf(conf_file, STRING_LONG, "%s/%s", getenv("HOME"), CONF_FILE);
	}

	return conf_file;
}

int
options_read()
{
	char *file, *text;
	xmlDocPtr doc;
	xmlNodePtr node, root;
	
	file = options_get_file();
	if(file == NULL){
		return -1;
	}

	doc = xmlParseFile(file);
	if(!doc){
		return -1;
	}

	root = xmlDocGetRootElement(doc);

	if(!root || !root->name || (strcmp((char*)root->name, "pwm_config") != 0) ){
		fprintf(stderr,"PWM-Warning: Badly Formed .pwmanrc\n");
		return -1;
	}

	for(node = root->children; node != NULL; node = node->next){
		if(!node || !node->name){
			debug("read_config: Fucked up xml node");
		} else if( strcmp((char*)node->name, "gpg_id") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(options->gpg_id, text, STRING_LONG);
		} else if( strcmp((char*)node->name, "gpg_path") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(options->gpg_path, text, STRING_LONG);
		} else if( strcmp((char*)node->name, "password_file") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(options->password_file, text, STRING_LONG);
		} else if( strcmp((char*)node->name, "passphrase_timeout") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text){ options->passphrase_timeout = atoi(text); }
		} else if( strcmp((char*)node->name, "filter") == 0){
			options->filter->field = atoi( (char*)xmlGetProp(node, "field") );
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(options->filter->filter, text, STRING_LONG);
		} else if( strcmp((char*)node->name, "readonly") == 0){
			options->readonly = TRUE;
		} else if( strcmp((char*)node->name, "text") == 0){
			// Safe to ignore. This is whitespace etc
		} else {
			debug("read_config: Unrecognised xml node '%s'", (char*)node->name);
		}
	}
	write_options = TRUE;
	xmlFreeDoc(doc);
	return 0;
}

int
options_write()
{
	char *file;
	char text[STRING_SHORT];
	xmlDocPtr doc;
	xmlNodePtr node, root;

	if(!write_options){
		return 0;
	}
	file = options_get_file();
	if(file == NULL){
		return -1;
	}

	if(!options){
		return -1;
	}
	doc = xmlNewDoc((xmlChar*) "1.0");
	root = xmlNewDocNode(doc, NULL, (xmlChar*)"pwm_config", NULL);
	xmlNewChild(root, NULL, (xmlChar*)"gpg_id", (xmlChar*)options->gpg_id);
	xmlNewChild(root, NULL, (xmlChar*)"gpg_path", (xmlChar*)options->gpg_path);
	xmlNewChild(root, NULL, (xmlChar*)"password_file", (xmlChar*)options->password_file);

	snprintf(text, STRING_SHORT, "%d", options->passphrase_timeout);
	xmlNewChild(root, NULL, (xmlChar*)"passphrase_timeout", (xmlChar*)text);

	snprintf(text, STRING_SHORT, "%d", options->filter->field);
	node = xmlNewChild(root, NULL, (xmlChar*)"filter", (xmlChar*)options->filter->filter);
	xmlSetProp(node, "field", text);

	// Note - search isn't serialised, but filter is

	xmlDocSetRootElement(doc, root);

	if( xmlSaveFormatFile(file, doc, TRUE) != -1 ){
		xmlFreeDoc(doc);
		return 0;
	} else {
		debug("write_options: couldn't write config file");
		xmlFreeDoc(doc);
		return -1;
	}
}

void
options_get()
{
	char pw_file[STRING_LONG];
	char text[STRING_SHORT];
	
	puts("Hmm... can't open ~/.pwmanrc, we'll create one manually now.");
	
	printf("GnuPG ID [you@yourdomain.com] or [012345AB]: ");
	fgets(options->gpg_id, STRING_LONG, stdin);
	if( strcmp(options->gpg_id, "\n") == 0 ){
		strncpy(options->gpg_id, "you@yourdomain.com", STRING_SHORT);
	} else {
		options->gpg_id[ strlen(options->gpg_id) - 1] = 0;
	}
	
	printf("Path to GnuPG [/usr/bin/gpg]: ");
	fgets(options->gpg_path, STRING_LONG, stdin);
	if( strcmp(options->gpg_path, "\n") == 0){
		strncpy(options->gpg_path, "/usr/bin/gpg", STRING_LONG);
	} else {
		options->gpg_path[ strlen(options->gpg_path) - 1] = 0;
	}
	
	snprintf(pw_file, STRING_LONG, "%s/.pwman.db", getenv("HOME") );
	printf("Password Database File [%s]: ", pw_file );
	fgets(options->password_file, STRING_LONG, stdin);
	if( strcmp(options->password_file, "\n") == 0){
		strncpy(options->password_file, pw_file, STRING_LONG);
	} else {
		options->password_file[ strlen(options->password_file) - 1] = 0;
	}
	
	printf("Passphrase Timeout(in minutes) [180]: ");
	fgets(text, STRING_SHORT, stdin);
	if( strcmp(text, "\n") == 0){
		options->passphrase_timeout = 180;
	} else {
		options->passphrase_timeout = atoi(text);
	}

	write_options = TRUE;
	options_write();
}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































































































































































































































































































































































Deleted src/pwdb2csv.c.

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
/*
 *  PWDB2CSV - Convert pwman database files into Comma Separated Values
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#define STR_LEN 255
#define PWDB2CSV_PACKAGE "PWDB2CSV"
#define PWDB2CSV_VERSION "0.1.0"

#include <libxml/parser.h>
#include <stdlib.h>
#include <stdio.h>
#include <pwman.h>

static void show_version();
static void show_usage(char*);

struct PWDB2CSV_Options {
	char *gpg_id;
	char *infile;
	char *outfile;
} pwdb2csv_options;

void
debug(char *fmt, ... )
{
#ifdef DEBUG
	va_list ap;
	int d, c;
	char *s;

	fputs("PWDB2CSV Debug% ", stderr);
	
	va_start(ap, fmt);
	while(*fmt){
		if(*fmt == '%'){
			switch(*++fmt){
				case 's': 	/* string */
					s = va_arg(ap, char*);
					fputs(s, stderr);
					break;
				case 'd':	/* int */
					d = va_arg(ap, int);
					fprintf(stderr, "%d", d);
					break;
				case 'c':	/* char */
					c = va_arg(ap, int);
					fputc(c, stderr);
					break;
				default:
					fputc('%', stderr);
					fputc(*fmt, stderr);
					break;
			}
		} else {
			fputc(*fmt, stderr);
		}
		*fmt++;
	}
	va_end(ap);
	fputc('\n', stderr);
#endif
}

PWList *
new_pwlist(char *name)
{
	PWList *new;

	new = malloc( sizeof(PWList) );
	new->name = malloc(STRING_MEDIUM);
	strncpy(new->name, name, STRING_MEDIUM);
	new->parent = NULL;
	new->list = NULL;
	new->sublists = NULL;
	debug("new_pwlist: %s", name);

	return new;
}

int 
free_pwlist(PWList *old)
{
	Pw *current, *next;
	PWList *curlist, *nlist;

	debug("free_pwlist: free a password list");
	if(old == NULL){
		return 0;
	}
	for(current = old->list; current != NULL; current = next){
		next = current->next;

		free_pw(current);
	}
	for(curlist = old->sublists; curlist != NULL; curlist = nlist){
		nlist = curlist->next;

		free_pwlist(curlist);
	}
	
	free(old->name);
	free(old);
	old = NULL;
	return 0;
}

Pw*
new_pw()
{
	Pw *new;
	new = malloc(sizeof(Pw));
	new->id = 0;
	new->name = malloc(STRING_MEDIUM);
	new->host = malloc(STRING_MEDIUM);
	new->user = malloc(STRING_MEDIUM);
	new->passwd = malloc(STRING_SHORT);
	new->launch = malloc(STRING_LONG);

	memset(new->name, 0, STRING_MEDIUM);
	memset(new->host, 0, STRING_MEDIUM);
	memset(new->user, 0, STRING_MEDIUM);
	memset(new->passwd, 0, STRING_SHORT);
	memset(new->launch, 0, STRING_LONG);
	
	return new;
}

int
free_pw(Pw *old)
{
	debug("free_pw: free a password");
	free(old->name);
	free(old->user);
	free(old->host);
	free(old->passwd);
	free(old->launch);
	free(old);
}

int
add_pw_ptr(PWList *list, Pw *new)
{
	Pw *current;
	
	if(list == NULL){
		debug("add_pw_ptr : Bad PwList");
		return -1;
	}
	if(new == NULL){
		debug("add_pw_ptr : Bad Pw");
		return -1;
	}
	if(list->list == NULL){
		list->list = new;
		new->next = NULL;
		return 0;
	}

	debug("add_pw_ptr: add to list");
	current = list->list;
	while(current->next != NULL){
		current = current->next;
	}
	current->next = new;
	new->next = NULL;

	return 0;
}

int
add_pw_sublist(PWList *parent, PWList *new)
{
	PWList *current;

	current = parent->sublists;
	new->parent = parent;
	if(current == NULL){
		parent->sublists = new;
		new->next = NULL;
		return 0;
	} 
	while(current->next != NULL){
		current = current->next;
	}
	current->next = new;
	new->next = NULL;

	return 0;
}

char *
escape_string(char *str)
{
	char *str2, *iter, *iter2, *c;
	int i = 0;
	
	str2 = malloc( strlen(str) + 100 ); /* any string with 100 quotes is a pisstake , it's just here for safety */
	
	for(iter = str, iter2 = str2; iter != 0, i < 100; iter++, iter2++, i++){
		if(*iter != '"'){
			*iter2 = *iter;
		} else {
			*iter2 = '\\'; iter2++;
			*iter2 = *iter;
		}
	}
	
	free(str);
	str = str2;

	return str;
}

int 
write_password_node(FILE *fp, Pw *pw)
{
	fprintf(fp, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n", escape_string(pw->name), escape_string(pw->host), 
			escape_string(pw->user), escape_string(pw->passwd), escape_string(pw->launch));
}

int
write_pwlist(FILE *fp, PWList *pwlist)
{
	Pw* iter;
	PWList *pwliter;
	
	for(pwliter = pwlist->sublists; pwliter != NULL; pwliter = pwliter->next){
		write_pwlist(fp, pwliter);
	}
	for(iter = pwlist->list; iter != NULL; iter = iter->next){
		write_password_node(fp, iter);
	}

	return 0;
}

void
read_password_node(xmlNodePtr parent, PWList *list)
{
	Pw *new;
	xmlNodePtr node;
	char *text;

	new = new_pw();

	for(node = parent->children; node != NULL; node = node->next){
		if(!node || !node->name){
			debug("read_pw_node: fucked node");
		} else if( strcmp((char*)node->name, "name") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->name, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "user") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->user, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "passwd") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->passwd, text, STRING_SHORT);
		} else if( strcmp((char*)node->name, "host") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->host, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "launch") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->launch, text, STRING_LONG);
		} else {
			debug("read_pw_node: unrecognised node \"%s\"", node->name);
		}
	}
	add_pw_ptr(list, new);
}

int
read_pwlist(xmlNodePtr parent, PWList *parent_list)
{
	xmlNodePtr node;
	PWList *new;

	char name[STRING_MEDIUM];
	if(!parent || !parent->name){
		return -1;
	} 
	debug("Parent name is %s\n", parent->name);

	if(strcmp((char*)parent->name, "PwList") == 0){
		strncpy(name, xmlGetProp(parent, (xmlChar*)"name"), STRING_MEDIUM);
		new = new_pwlist(name);

		for(node = parent->children; node != NULL; node = node->next){
			debug("Child name is %s\n", node->name);	
			if(!node) {
				fprintf(stderr, "read_pwlist: messed up node - null\n");
			// Doesn't appear to be a problem
//			} else if(!node->next){
//				fprintf(stderr, "read_pwlist: messed up node - no next sibling\n");
			} else if(strcmp(node->name, "PwList") == 0){
				read_pwlist(node, new);
			} else if(strcmp(node->name, "PwItem") == 0){
				read_password_node(node, new);
			}
		}
	}

	if(parent_list == NULL){
		parent_list = new;
	} else {
		add_pw_sublist(parent_list, new);
	}
	return 0;
}

PWList*
parse_doc(xmlDocPtr doc)
{
	PWList *pwlist = NULL;
	xmlNodePtr root, node;
	char *buf;
	int i;
	
	if(!doc){
		return NULL;
	}

	root = xmlDocGetRootElement(doc);
	if(!root || !root->name || (strcmp((char*)root->name, "PWMan_PasswordList") != 0) ){
		return NULL;
	}
	if(buf = xmlGetProp(root, (xmlChar*)"version")){
		i = atoi( buf );
	} else {
		i = 0;
	}
	if(i < FF_VERSION){
		return NULL;
	}

	pwlist = new_pwlist("Main");
	for(node = root->children; node != NULL; node = node->next){
		if(strcmp(node->name, "PwList") == 0){
			read_pwlist(node, pwlist);

			break;
		}
	}
	xmlFreeDoc(doc);

	return pwlist;
}

char *
add_to_buf(char *buf, char *new)
{
	size_t size;

	if(new == NULL){
		return buf;
	} 
	if(buf == NULL){
		buf = malloc(strlen(new)+1);
		strncpy(buf, new, strlen(new)+1);
		return buf;
	}

	size = strlen(buf) + strlen(new) + 1;
	buf = (char*)realloc(buf, size);
	strncat(buf, new, size);

	return buf;
}

xmlDocPtr
get_data()
{
	FILE *fp;
	char *cmd;
	char *data;
	char buf[STR_LEN];
	xmlDocPtr doc;

	data = NULL;
	cmd = malloc(STR_LEN);
	snprintf(cmd, STR_LEN, "gpg -d %s", pwdb2csv_options.infile);
	debug(cmd);
	fp = popen(cmd, "r");

	while( fgets(buf, STR_LEN, fp) != NULL ){
		data = add_to_buf(data, buf);
	}
	pclose(fp);

	if(!data){
		exit(-1);
	}

	doc = xmlParseMemory(data, strlen(data));

	return doc;
}

void
put_data(PWList *pwlist)
{
	FILE *fp;

	fp = fopen(pwdb2csv_options.outfile, "w");

	if(!fp){
		fprintf(stderr, "write_pwlist: couldn't open file \"%s\"\n", pwdb2csv_options.outfile);
		return;
	}

	write_pwlist(fp, pwlist);

	fclose(fp);
}

void
free_pwdb2csv_options()
{
	debug("free_pwdb2csv_options: free options");
	free(pwdb2csv_options.infile);
	free(pwdb2csv_options.outfile);
}

char *
ask(char *msg)
{
	char * input;

	input = malloc(STR_LEN);

	fputs(msg, stdout);
	fputc('\t', stdout);
	fgets(input, STR_LEN, stdin);

	input[ strlen(input) - 1] = 0;

	return input;
}

void
get_options(int argc, char *argv[])
{
	int i;

	for(i = 0; i < argc; i++){
		if( !strcmp(argv[i], "--help") || !strcmp(argv[i], "-h") ){
			show_usage(argv[0]);
			exit(1);
		} else if( !strcmp(argv[i], "--version") || !strcmp(argv[i], "-v") ){
			show_version();
			exit(1);
		}
	}
	
	if(argc > 1){
		pwdb2csv_options.infile = malloc(STR_LEN);
		strncpy(pwdb2csv_options.infile, argv[1], STR_LEN);
	} else {
		pwdb2csv_options.infile = ask("Password Database:");
	}
	if(argc > 2){
		pwdb2csv_options.outfile = malloc(STR_LEN);
		strncpy(pwdb2csv_options.outfile, argv[2], STR_LEN);
	} else {
		pwdb2csv_options.outfile = ask("CSV file:");
	}
}

int
main(int argc, char *argv[])
{
	xmlDocPtr doc;
	PWList *pwlist;
	
	get_options(argc, argv);

	doc = get_data();
	pwlist = parse_doc(doc);
	
	put_data(pwlist);

	free_pwdb2csv_options();
	return 0;
}

static void
show_version()
{
	puts(PWDB2CSV_PACKAGE " v " PWDB2CSV_VERSION);
	puts("Written by Ivan Kelly <ivan@ivankelly.net>\n");
	puts("Copyright (C) 2002 Ivan Kelly");
	puts("This program is free software; you can redistribute it and/or modify");
	puts("it under the terms of the GNU General Public License as published by");
	puts("the Free Software Foundation; either version 2 of the License, or");
	puts("(at your option) any later version.\n");

	puts("This program is distributed in the hope that it will be useful,");
	puts("but WITHOUT ANY WARRANTY; without even the implied warranty of");
	puts("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
	puts("GNU General Public License for more details.\n");

	puts("You should have received a copy of the GNU General Public License");
	puts("along with this program; if not, write to the Free Software");
	puts("Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.\n");
}

static void
show_usage(char *argv_0)
{
	printf("Usage: %s [<pwdatabase> [<csvfile>]]\n", argv_0);
	puts("Convert Password Database from PWMan Encrypted Format to Comma Separated Values\n");
	puts("  --help                 show usage");
	puts("  --version              display version information");
	puts("  <pwdatabase>           password database file in encrypted");
	puts("  <csvfile>              file to write to with comma separated values\n\n");
	puts("Report bugs to <ivan@ivankelly.net>");
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted src/pwgen.c.

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
/*
 *  PWMan - password manager application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * all code in this file is taken from pwgen
 * (c) 2001 Theodore Ts'o
 */

#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <pwman.h>
#include <ui.h>

struct pwgen_element {
	char	*str;
	int	flags;
};

/*
 * Flags for the pw_element
 */
#define CONSONANT	0x0001
#define VOWEL		0x0002
#define DIPTHONG	0x0004
#define NOT_FIRST	0x0008


struct pwgen_element elements[] = {
	{ "a",	VOWEL },
	{ "ae", VOWEL | DIPTHONG },
	{ "ah",	VOWEL | DIPTHONG },
	{ "ai", VOWEL | DIPTHONG },
	{ "b",  CONSONANT },
	{ "c",	CONSONANT },
	{ "ch", CONSONANT | DIPTHONG },
	{ "d",	CONSONANT },
	{ "e",	VOWEL },
	{ "ee", VOWEL | DIPTHONG },
	{ "ei",	VOWEL | DIPTHONG },
	{ "f",	CONSONANT },
	{ "g",	CONSONANT },
	{ "gh", CONSONANT | DIPTHONG | NOT_FIRST },
	{ "h",	CONSONANT },
	{ "i",	VOWEL },
	{ "ie", VOWEL | DIPTHONG },
	{ "j",	CONSONANT },
	{ "k",	CONSONANT },
	{ "l",	CONSONANT },
	{ "m",	CONSONANT },
	{ "n",	CONSONANT },
	{ "ng",	CONSONANT | DIPTHONG | NOT_FIRST },
	{ "o",	VOWEL },
	{ "oh",	VOWEL | DIPTHONG },
	{ "oo",	VOWEL | DIPTHONG},
	{ "p",	CONSONANT },
	{ "ph",	CONSONANT | DIPTHONG },
	{ "qu",	CONSONANT | DIPTHONG},
	{ "r",	CONSONANT },
	{ "s",	CONSONANT },
	{ "sh",	CONSONANT | DIPTHONG},
	{ "t",	CONSONANT },
	{ "th",	CONSONANT | DIPTHONG},
	{ "u",	VOWEL },
	{ "v",	CONSONANT },
	{ "w",	CONSONANT },
	{ "x",	CONSONANT },
	{ "y",	CONSONANT },
	{ "z",	CONSONANT }
};

#define NUM_ELEMENTS (sizeof(elements) / sizeof (struct pwgen_element))

char *pwgen(char *buf, int size)
{
	int	c, i, len, flags, feature_flags;
	int	prev, should_be, first;
	char	*str;

	if(buf == NULL){
		buf = malloc(size);
	}

	c = 0;
	prev = 0;
	should_be = 0;
	first = 1;

	should_be = pwgen_random_number(1) ? VOWEL : CONSONANT;
	
	while (c < size) {
		i = pwgen_random_number(NUM_ELEMENTS);
		str = elements[i].str;
		len = strlen(str);
		flags = elements[i].flags;
		/* Filter on the basic type of the next element */
		if ((flags & should_be) == 0)
			continue;
		/* Handle the NOT_FIRST flag */
		if (first && (flags & NOT_FIRST))
			continue;
		/* Don't allow VOWEL followed a Vowel/Dipthong pair */
		if ((prev & VOWEL) && (flags & VOWEL) &&
		    (flags & DIPTHONG))
			continue;
		/* Don't allow us to overflow the buffer */
		if (len > size-c)
			continue;
		/*
		 * OK, we found an element which matches our criteria,
		 * let's do it!
		 */
		strcpy(buf+c, str);

		/* Handle PW_ONE_CASE */
		if ((first || flags & CONSONANT) && (pwgen_random_number(10) < 3)) {
			buf[c] = toupper(buf[c]);
		}
		
		c += len;
		
		/* Time to stop? */
		if (c >= size)
			break;
		
		/*
		 * Handle PW_ONE_NUMBER
		 */
		if (!first && (pwgen_random_number(10) < 3)) {
			buf[c++] = pwgen_random_number(9)+'0';
			buf[c] = 0;
				
			first = 1;
			prev = 0;
			should_be = pwgen_random_number(1) ? VOWEL : CONSONANT;
			continue;
		}
				
		/*
		 * OK, figure out what the next element should be
		 */
		if (should_be == CONSONANT) {
			should_be = VOWEL;
		} else { /* should_be == VOWEL */
			if ((prev & VOWEL) ||
			    (flags & DIPTHONG) ||
			    (pwgen_random_number(10) > 3))
				should_be = CONSONANT;
			else
				should_be = VOWEL;
		}
		prev = flags;
		first = 0;
	}

	return buf;
}

#ifdef HAVE_DRAND48
extern double drand48();
#endif

/* Borrowed/adapted from e2fsprogs's UUID generation code */
static int pwgen_get_random_fd(void)
{
	struct timeval	tv;
	static int	fd = -2;
	int		i;

	if (fd == -2) {
		gettimeofday(&tv, 0);
		fd = open("/dev/urandom", O_RDONLY);
		if (fd == -1)
			fd = open("/dev/random", O_RDONLY | O_NONBLOCK);
#ifdef HAVE_DRAND48
		srand48((tv.tv_sec<<9) ^ (getpgrp()<<15) ^
			(getpid()) ^ (tv.tv_usec>>11));
#else
		srandom((getpid() << 16) ^ (getpgrp() << 8) ^ getuid() 
		      ^ tv.tv_sec ^ tv.tv_usec);
#endif
	}
	/* Crank the random number generator a few times */
	gettimeofday(&tv, 0);
	for (i = (tv.tv_sec ^ tv.tv_usec) & 0x1F; i > 0; i--)
#ifdef HAVE_DRAND48
		drand48();
#else
		rand();
#endif
	return fd;
}

/*
 * Generate a random number n, where 0 <= n < max_num, using
 * /dev/urandom if possible.
 */
int pwgen_random_number(int max_num)
{
	int i, fd = pwgen_get_random_fd();
	int lose_counter = 0, nbytes=4;
	unsigned int rand;
	char *cp = (char *) &rand;

	if (fd >= 0) {
		while (nbytes > 0) {
			i = read(fd, cp, nbytes);
			if ((i < 0) &&
			    ((errno == EINTR) || (errno == EAGAIN)))
				continue;
			if (i <= 0) {
				if (lose_counter++ == 8)
					break;
				continue;
			}
			nbytes -= i;
			cp += i;
			lose_counter = 0;
		}
	}
	if (nbytes == 0)
		return (rand % max_num);

	/* OK, we weren't able to use /dev/random, fall back to rand/rand48 */

#ifdef RAND48
	return ((int) ((drand48() * max_num)));
#else
	return ((int) (random() / ((float) RAND_MAX) * max_num));
#endif
}

char 
*pwgen_ask(char *pw)
{
	int i;
	ui_statusline_ask_num("Length of Password(default 5):\t", &i);

	if(i == 0){
		i = 5;
	} else if(i > STRING_SHORT) {
		i = STRING_SHORT;
	}
	pw = pwgen(pw, i);

	return pw;
}

int 
pwgen_indep()
{
	char pass[STRING_SHORT], text[STRING_LONG];

	pwgen_ask(pass);

	snprintf(text, STRING_LONG, "Generated Password: %s", pass);
	ui_statusline_msg(text);
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































































































































































































































































































































Deleted src/pwlist.c.

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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <pwman.h>
#include <gnupg.h>
#include <ui.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <libxml/tree.h>
#include <libxml/parser.h>

int pwindex = 0;
extern int errno;
void pwlist_free_pw(Pw*);


PWList *
pwlist_new(char *name)
{
	PWList *new;
	new = malloc( sizeof(PWList) );
	new->name = malloc(STRING_MEDIUM);
	strncpy(new->name, name, STRING_MEDIUM);
	new->parent = NULL;
	new->list = NULL;
	new->next = NULL;
	new->sublists = NULL;
	debug("new_pwlist: %s", name);

	return new;
}

int
pwlist_init()
{
	pwindex = 0;
	pwlist = NULL;
	current_pw_sublist = NULL;
	return 0;
}

int 
pwlist_free(PWList *old)
{
	Pw *current, *next;
	PWList *curlist, *nlist;

	if(old == NULL){
		return 0;
	}
	for(current = old->list; current != NULL; current = next){
		next = current->next;

		pwlist_free_pw(current);
	}
	for(curlist = old->sublists; curlist != NULL; curlist = nlist){
		nlist = curlist->next;

		pwlist_free(curlist);
	}
	
	free(old->name);
	free(old);
	old = NULL;
	return 0;
}

int
pwlist_free_all()
{
	pwlist_free(pwlist);
	return 0;
}

Pw*
pwlist_new_pw()
{
	Pw *new;
	new = malloc(sizeof(Pw));
	new->id = 0;
	new->name = malloc(STRING_MEDIUM);
	new->host = malloc(STRING_MEDIUM);
	new->user = malloc(STRING_MEDIUM);
	new->passwd = malloc(STRING_SHORT);
	new->launch = malloc(STRING_LONG);

	memset(new->name, 0, STRING_MEDIUM);
	memset(new->host, 0, STRING_MEDIUM);
	memset(new->user, 0, STRING_MEDIUM);
	memset(new->passwd, 0, STRING_SHORT);
	memset(new->launch, 0, STRING_LONG);
	
	return new;
}

void
pwlist_free_pw(Pw *old)
{
	free(old->name);
	free(old->user);
	free(old->host);
	free(old->passwd);
	free(old->launch);
	free(old);
}

int
pwlist_change_item_order(Pw* pw, PWList *parent, int moveUp) {
	Pw *iter = NULL;
	Pw *pprev = NULL;
	Pw *prev = NULL;
	Pw *next = NULL;
	Pw *nnext = NULL;

	// Find us, in our parents list of children
	for(iter = parent->list; iter != NULL; iter = iter->next){
		if(iter == pw) {
			// Grab the next one, and the one after
			next = pw->next;
			if(next != NULL) {
				nnext = next->next;
			} else {
				nnext = NULL;
			}

			// Which way do we need to shuffle?
			if(moveUp) {
				// Up the list, if we can
				if(prev == NULL) { break; }

				// Are we going to the top?
				if(prev == parent->list) {
					parent->list = pw;
					pw->next = prev;
					prev->next = next;
				} else {
					pprev->next = pw;
					pw->next = prev;
					prev->next = next;
				}
				return 1;
			} else {
				// Down the list, if we can
				if(next == NULL) { break; }

				// Were we at the top?
				if(pw == parent->list) {
					parent->list = next;
					next->next = pw;
					pw->next = nnext;
				} else {
					prev->next = next;
					next->next = pw;
					pw->next = nnext;
				}
				return 1;
			}
		} else {
			// Update the running list of prev and pprev
			pprev = prev;
			prev = iter;
		}
	}

	return 0;
}

int
pwlist_change_list_order(PWList *pw, int moveUp) {
	// Grab the parent, assuming there is one
	PWList *parent = pw->parent;
	if(parent==NULL) { return 0; }


	// Find us
	PWList *iter = NULL;
	PWList *pprev = NULL;
	PWList *prev = NULL;
	PWList *next = NULL;
	PWList *nnext = NULL;

	// Find us, in our parents list of children
	for(iter = parent->sublists; iter != NULL; iter = iter->next){
		if(iter == pw) {
			// Grab the next one, and the one after
			next = pw->next;
			if(next != NULL) {
				nnext = next->next;
			} else {
				nnext = NULL;
			}

			// Which way do we need to shuffle?
			if(moveUp) {
				// Up the list, if we can
				if(prev == NULL) { break; }

				// Are we going to the top?
				if(prev == parent->sublists) {
					parent->sublists = pw;
					pw->next = prev;
					prev->next = next;
				} else {
					pprev->next = pw;
					pw->next = prev;
					prev->next = next;
				}
				return 1;
			} else {
				// Down the list, if we can
				if(next == NULL) { break; }

				// Were we at the top?
				if(pw == parent->sublists) {
					parent->sublists = next;
					next->next = pw;
					pw->next = nnext;
				} else {
					prev->next = next;
					next->next = pw;
					pw->next = nnext;
				}
				return 1;
			}
		} else {
			// Update the running list of prev and pprev
			pprev = prev;
			prev = iter;
		}
	}

	return 0;
}

void
pwlist_rename_item(Pw* pwitem, char* new_name) {
	strncpy(pwitem->name, new_name, STRING_MEDIUM);
}
void
pwlist_rename_sublist(PWList *pwlist, char* new_name) {
	strncpy(pwlist->name, new_name, STRING_MEDIUM);
}

int
pwlist_add(PWList *parent, char* name, char* host, char* user, char* passwd, char* launch)
{
	Pw* new = pwlist_new_pw();
	
	new->id = pwindex++;
	strncpy(new->name, name, STRING_MEDIUM);
	strncpy(new->host, host, STRING_MEDIUM);
	strncpy(new->user, user, STRING_MEDIUM);
	strncpy(new->passwd, passwd, STRING_SHORT);
	strncpy(new->launch, launch, STRING_LONG);

	pwlist_add_ptr(parent, new);

	return 0;
}

int 
pwlist_add_sublist(PWList *parent, PWList *new)
{
	PWList *current;

	current = parent->sublists;
	new->parent = parent;
	new->current_item = 1;

	if(current == NULL){
		debug("add_pw_sublist: current = NULL");
		parent->sublists = new;
		new->next = NULL;
		return 0;
	}
	while(current->next != NULL){
		current = current->next;
	}
	current->next = new;
	new->next = NULL;

	return 0;
}

int
pwlist_add_ptr(PWList *list, Pw *new)
{
	Pw *current;
	
	if(list == NULL){
		debug("add_pw_ptr : Bad PwList");
		return -1;
	}
	if(new == NULL){
		debug("add_pw_ptr : Bad Pw");
		return -1;
	}
	if(list->list == NULL){
		list->list = new;
		new->next = NULL;
		return 0;
	}

	debug("add_pw_ptr: add to list");
	current = list->list;
	while(current->next != NULL){
		current = current->next;
	}
	current->next = new;
	new->next = NULL;

	return 0;
}

void 
pwlist_detach_pw(PWList *list, Pw *pw)
{
	Pw *iter, *prev;

	prev = NULL;
	for(iter = list->list; iter != NULL; iter = iter->next){
		
		if(iter == pw){
			if(prev == NULL){
				list->list = iter->next;
			} else {
				prev->next = iter->next;
			}
			break;
		}
		prev = iter;
	}
}

void 
pwlist_delete_pw(PWList *list, Pw *pw)
{
	Pw *iter, *prev;

	prev = NULL;
	for(iter = list->list; iter != NULL; iter = iter->next){
		
		if(iter == pw){
			if(prev == NULL){
				list->list = iter->next;
			} else {
				prev->next = iter->next;
			}
			pwlist_free_pw(iter);
			break;
		}
		prev = iter;
	}
}

void 
pwlist_detach_sublist(PWList *parent, PWList *old)
{
	PWList *iter, *prev;

	prev = NULL;
	for(iter = parent->sublists; iter != NULL; iter = iter->next){

		if(iter == old){
			if(prev == NULL){
				parent->sublists = iter->next;
			} else {
				prev->next = iter->next;
			}
			break;
		}
		prev = iter;
	}
}

void
pwlist_delete_sublist(PWList *parent, PWList *old)
{
	PWList *iter, *prev;

	prev = NULL;
	for(iter = parent->sublists; iter != NULL; iter = iter->next){

		if(iter == old){
			if(prev == NULL){
				parent->sublists = iter->next;
			} else {
				prev->next = iter->next;
			}
			pwlist_free(iter);
			break;
		}
		prev = iter;
	}
}

void 
pwlist_write_node(xmlNodePtr root, Pw* pw)
{
	xmlNodePtr node;

	// We need to escape the strings before storing them
	// Otherwise, special characters (especially &) will
	//  end up broken!
	xmlChar *escapedName = 
		xmlEncodeSpecialChars(root->doc, (xmlChar*)pw->name);
	xmlChar *escapedHost =
		xmlEncodeSpecialChars(root->doc, (xmlChar*)pw->host);
	xmlChar *escapedUser =
		xmlEncodeSpecialChars(root->doc, (xmlChar*)pw->user);
	xmlChar *escapedPasswd = 
		xmlEncodeSpecialChars(root->doc, (xmlChar*)pw->passwd);
	xmlChar *escapedLaunch =
		xmlEncodeSpecialChars(root->doc, (xmlChar*)pw->launch);

	// Build the entry and add in our (escaped) contents
	node = xmlNewChild(root, NULL, (xmlChar*)"PwItem", NULL);

	xmlNewChild(node, NULL, (xmlChar*)"name", escapedName);
	xmlNewChild(node, NULL, (xmlChar*)"host", escapedHost);
	xmlNewChild(node, NULL, (xmlChar*)"user", escapedUser);
	xmlNewChild(node, NULL, (xmlChar*)"passwd", escapedPasswd);
	xmlNewChild(node, NULL, (xmlChar*)"launch", escapedLaunch);

	// Finally, we need to free all our escaped versions now we're done
	xmlFree(escapedName);
	xmlFree(escapedHost);
	xmlFree(escapedUser);
	xmlFree(escapedPasswd);
	xmlFree(escapedLaunch);
}

void
pwlist_write(xmlNodePtr parent, PWList *list)
{
	xmlNodePtr node;
	Pw *iter;
	PWList *pwliter;
	
	node = xmlNewChild(parent, NULL, (xmlChar*)"PwList", NULL);
	xmlSetProp(node, (xmlChar*)"name", (xmlChar*)list->name);
	
	for(iter = list->list; iter != NULL; iter = iter->next){
		pwlist_write_node(node, iter);
	}
	for(pwliter = list->sublists; pwliter != NULL; pwliter = pwliter->next){
		pwlist_write(node, pwliter);
	}
}

int
pwlist_write_file()
{
	char vers[5];
	xmlDocPtr doc;
	xmlNodePtr root;

	if(options->readonly){
		return 0;
	}

	if(!pwlist){
		debug("write_file: bad password file");
		ui_statusline_msg("Bad password list");
		return -1;
	}
	snprintf(vers, 5, "%d", FF_VERSION);
	doc = xmlNewDoc((xmlChar*)"1.0");
	
	root = xmlNewDocNode(doc, NULL, (xmlChar*)"PWMan_PasswordList", NULL);

	xmlSetProp(root, (xmlChar*)"version", (xmlChar*)vers);
	pwlist_write(root, pwlist);

	xmlDocSetRootElement(doc, root);

	gnupg_write(doc, options->gpg_id, options->password_file);
	
	xmlFreeDoc(doc);
	return 0;
}

void
pwlist_read_node(xmlNodePtr parent, PWList *list)
{
	Pw* new;
	xmlNodePtr node;
	char *text;
	
	new = pwlist_new_pw();

	for(node = parent->children; node != NULL; node = node->next){
		if(!node || !node->name){
			debug("Messed up xml node");
		} else if( strcmp((char*)node->name, "name") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->name, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "user") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->user, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "passwd") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->passwd, text, STRING_SHORT);
		} else if( strcmp((char*)node->name, "host") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->host, text, STRING_MEDIUM);
		} else if( strcmp((char*)node->name, "launch") == 0){
			text = (char*)xmlNodeGetContent(node);
			if(text) strncpy(new->launch, text, STRING_LONG);
		} 
	}
	pwlist_add_ptr(list, new);
}

int
pwlist_read(xmlNodePtr parent, PWList *parent_list)
{
	xmlNodePtr node;
	PWList *new;

	char name[STRING_MEDIUM];
	if(!parent || !parent->name){
		ui_statusline_msg("Messed up xml node");
		return -1;
	}
	if(strcmp((char*)parent->name,"PwList") == 0){
		strncpy(name, xmlGetProp(parent, (xmlChar*)"name"), STRING_MEDIUM);
		new = pwlist_new(name);

		for(node = parent->children; node != NULL; node = node->next){
			if(!node || !node->name){
				debug("read_pwlist: messed up child node");
			} else if(strcmp(node->name, "PwList") == 0){
				pwlist_read(node, new);
			} else if(strcmp(node->name, "PwItem") == 0){
				pwlist_read_node(node, new);
			}
		}
	}

	if(parent_list == NULL){
		pwlist = new;
		current_pw_sublist = pwlist;

		pwlist->current_item = 0;
	} else {
		pwlist_add_sublist(parent_list, new);
	}
	return 0;
}

int
pwlist_read_file()
{
    char fn[STRING_LONG];
	char *buf;
	int i = 0;
	int gnupg_worked = 0;
	xmlNodePtr node, root;
	xmlDocPtr doc;

	// Have the defined a file yet?
	if(!options->password_file){
		return -1;
	}
	// Do we need to create a new file?
	snprintf(fn, STRING_LONG, "%s", options->password_file);
	if(access(fn, F_OK) != 0){
		ui_statusline_msg("Database not found, created. Press any key to begin  "); getch();
		return -1;
	}

	// Try to load the file
	gnupg_worked = gnupg_read(options->password_file, &doc);	

	// Did it work?
	if(gnupg_worked != 0) {
		return gnupg_worked;
	}
	
	if(!doc){
		ui_statusline_msg("Bad xml Data");
		return -1;
	}
	root = xmlDocGetRootElement(doc);
	if(!root || !root->name	|| (strcmp((char*)root->name, "PWMan_PasswordList") != 0) ){
		ui_statusline_msg("Badly Formed password data");
		return -1;
	}
	if( buf = xmlGetProp(root, (xmlChar*)"version") ){
		i = atoi( buf );
	} else {
		i = 0;
	}
	if(i < FF_VERSION){
		ui_statusline_msg("Password File in older format, use convert_pwdb");
		return -1;
	}

	for(node = root->children; node != NULL; node = node->next){
		if(strcmp(node->name, "PwList") == 0){
			pwlist_read(node, NULL);

			break;
		}
	}
	xmlFreeDoc(doc);
	return 0;
}


int
pwlist_do_export(PWList *pwlist, Pw *pw)
{
	char vers[5];
	char file[STRING_LONG];
	int max_id_num = 5, i=0, valid_ids = 0;
	char *ids[max_id_num];
	
	xmlDocPtr doc;
	xmlNodePtr root;

	if(!pwlist && !pw) {
		debug("export_passwd: bad password");
		ui_statusline_msg("Bad password");
		return -1;
	}

	// We need the IDs to default to empty strings
	for(i=0; i<max_id_num; i++) {
		ids[i] = malloc(STRING_LONG);
		snprintf(ids[i], STRING_LONG, "");
	}

	// Fetch the IDs
	gnupg_get_ids(ids,max_id_num);

	// Check we really got one
	for(i=0; i<max_id_num; i++) {
		if(ids[i][0] != 0) {
			valid_ids++;
		}
	}

	if(valid_ids == 0){
		debug("export_passwd: cancel because id is blank");
		return -1;
	} else {
		debug("exporting to %d ids", valid_ids);
	}
	
	gnupg_get_filename(file, 'w');

	debug("export_passwd: construct xml doc");
	snprintf(vers, 5, "%d", FF_VERSION);
	doc = xmlNewDoc((xmlChar*)"1.0");
	
	root = xmlNewDocNode(doc, NULL, (xmlChar*)"PWMan_Export", NULL);

	xmlSetProp(root, "version", vers);
	
   if(pwlist) {
      pwlist_write(root, pwlist);
   } else {
      pwlist_write_node(root, pw);
   }

	xmlDocSetRootElement(doc, root);

	gnupg_write_many(doc, ids, max_id_num, file);
	
	xmlFreeDoc(doc);

	// All done.
	// Free our ID structures
	for(i=0; i<max_id_num; i++) {
		free(ids[i]);
	}
	
	return 0;
}

int
pwlist_export_passwd(Pw *pw)
{
   return pwlist_do_export(NULL, pw);
}
int
pwlist_export_list(PWList *pwlist)
{
   return pwlist_do_export(pwlist, NULL);
}


int
pwlist_import_passwd()
{
	char file[STRING_LONG], *buf;
	int i = 0;
	xmlNodePtr node, root;
	xmlDocPtr doc;

	gnupg_get_filename(file, 'r');

	gnupg_read(file, &doc);	
	
	if(!doc){
		debug("import_passwd: bad data");
		return -1;
	}
	root = xmlDocGetRootElement(doc);
	if(!root || !root->name	|| (strcmp((char*)root->name, "PWMan_Export") != 0) ){
		ui_statusline_msg("Badly Formed password data");
		return -1;
	}
	if( buf = xmlGetProp(root, (xmlChar*)"version") ){
		i = atoi( buf );
	} else {
		i = 0;
	}
	if(i < FF_VERSION){
		ui_statusline_msg("Password Export File in older format, use convert_pwdb");
		return -1;
	}
	
	for(node = root->children; node != NULL; node = node->next){
		if(strcmp(node->name, "PwList") == 0){
			pwlist_read(node, current_pw_sublist);
			break;
		} else if(strcmp(node->name, "PwItem") == 0){
			pwlist_read_node(node, current_pw_sublist);
			break;
		}
	}
	xmlFreeDoc(doc);
	return 0;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted src/pwman.c.

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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "pwman.h"
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdarg.h>

static void pwman_parse_command_line(int argc, char **argv);
static void pwman_show_usage();
static void pwman_show_version();
static void pwman_quit();


static int
pwman_check_lock_file()
{
	char fn[STRING_LONG];
	FILE *fp;
	
	snprintf(fn, STRING_LONG, "%s.lock", options->password_file);
	if(access(fn, F_OK) == 0){
		return 1;
	} else {
		return 0;
	}
}

static int
pwman_create_lock_file()
{
	char fn[STRING_LONG];
		
	snprintf(fn, STRING_LONG, "%s.lock", options->password_file);
	creat(fn, S_IRWXU);
}

static int
pwman_delete_lock_file()
{
	char fn[STRING_LONG];
	
	snprintf(fn, STRING_LONG, "%s.lock", options->password_file);
	unlink(fn);
}

static void
pwman_init(int argc, char *argv[])
{
	char c;
	int load_worked, gpg_id_valid;

	signal(SIGKILL, pwman_quit);
	signal(SIGTERM, pwman_quit);

	umask(DEFAULT_UMASK);

	/* get options from .pwmanrc */
	options = options_new();
	if(options_read() == -1){
		options_get();
	}

	/* parse command line options */
	pwman_parse_command_line(argc, argv);

	/* check to see if another instance of pwman is open */
	if(!options->readonly && pwman_check_lock_file()){
		fprintf(stderr, "It seems %s is already opened by an instance of pwman\n",
				options->password_file);
		fprintf(stderr, "Two instances of pwman should not be open the same file at the same time\n");
		fprintf(stderr, "If you are sure pwman is not already open you can delete the file.\n");
		fprintf(stderr,"Alternatively, you can open the file readonly by answering 'r'\n");
		fprintf(stderr,"Delete file %s.lock? [y/n/r]\n",
				options->password_file);
		c = getchar();
		fprintf(stderr,"\n");
		switch (tolower(c)) {
			case 'y':
				pwman_delete_lock_file();
				break;
			case 'r':
				options->readonly = TRUE;
				break;
			default:
				exit(-1);
		}
	}

	// Check that the gpg id is valid, if given
	if(strlen(options->gpg_id)) {
		gpg_id_valid = gnupg_check_id(options->gpg_id);
		if(gpg_id_valid == -1) {
			fprintf(stderr, "Your GPG key with id of '%s' could not be found\n", options->gpg_id);
			fprintf(stderr, "You will be prompted for the correct key when saving\n");
			fprintf(stderr, "\n(press any key to continue)\n");
			c = getchar();
		}
		if(gpg_id_valid == -2) {
			fprintf(stderr, "Your GPG key with id of '%s' has expired!\n", options->gpg_id);
			fprintf(stderr, "Please change the expiry date of your key, or switch to a new one\n");
			exit(-1);
		}
	}
	
	// Start up our UI
	if( ui_init() ){
		exit(1);
	}

	ui_refresh_windows();

	/* get pw database */
	pwlist_init();
	load_worked = pwlist_read_file();
	if(load_worked != 0) {
		debug("Failed to load the database, error was %d", load_worked);
		// Did they cancel out, or is it a new file?
		if(load_worked < 0) {
			pwlist = pwlist_new("Main");
			current_pw_sublist = pwlist;
		} else {
			// Quit, hard!
			ui_end();
			fprintf(stderr, "\n\nGPG read cancelled, exiting\n");
			exit(1);
		}
	}
	if (!options->readonly){
		pwman_create_lock_file();
	}

	ui_refresh_windows();
}

static void
pwman_quit()
{
	pwlist_write_file();
	pwlist_free_all();
	pwman_delete_lock_file();
	
	ui_end();
	options_write();
	
	exit(0);
}

int
main(int argc, char *argv[])
{
	pwman_init(argc, argv);

	ui_run();

	pwman_quit();
	return 0;
}

static void
pwman_parse_command_line(int argc, char **argv)
{
	int i;

	for(i = 1; i < argc; i++){
		if( !strcmp(argv[i], "--help") || !strcmp(argv[i], "-h") ){
			pwman_show_usage(argv[0]);
			exit(1);
		} else if( !strcmp(argv[i], "--version") || !strcmp(argv[i], "-v") ){
			pwman_show_version();
			exit(1);
		} else if( !strcmp(argv[i], "--gpg-path") ){
			write_options = FALSE;
			strncpy(options->gpg_path, argv[i + 1], STRING_LONG);
			i++;
		}else if( !strcmp(argv[i], "--gpg-id") ){
			write_options = FALSE;
			strncpy(options->gpg_id, argv[i + 1], STRING_LONG);
			i++;
		} else if( !strcmp(argv[i], "--file") || !strcmp(argv[i], "-f") ){
			write_options = FALSE;
			strncpy(options->password_file, argv[i + 1], STRING_LONG);
			i++;
		} else if( !strcmp(argv[i], "--passphrase-timeout") || !strcmp(argv[i], "-t") ){
			write_options = FALSE;
			options->passphrase_timeout = atoi(argv[i + 1]);
			i++;
		} else if ( !strcmp(argv[i], "--readonly") || !strcmp(argv[i], "-r") ){
			write_options = FALSE;
			options->readonly = TRUE;
		} else {
			printf("option %s not recognised\n", argv[i]);
			printf("try %s --help for more info\n", argv[0]);
			exit(1);
		}
	}
}

static void
pwman_show_version()
{
	puts(PACKAGE " v " VERSION);
	puts("Written by Ivan Kelly <ivan@ivankelly.net>\n");
	puts("Copyright (C) 2002 Ivan Kelly");
	puts("This program is free software; you can redistribute it and/or modify");
	puts("it under the terms of the GNU General Public License as published by");
	puts("the Free Software Foundation; either version 2 of the License, or");
	puts("(at your option) any later version.\n");

	puts("This program is distributed in the hope that it will be useful,");
	puts("but WITHOUT ANY WARRANTY; without even the implied warranty of");
	puts("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
	puts("GNU General Public License for more details.\n");

	puts("You should have received a copy of the GNU General Public License");
	puts("along with this program; if not, write to the Free Software");
	puts("Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.\n");
}

static void
pwman_show_usage(char *argv_0)
{
	printf("Usage: %s [OPTIONS]...\n", argv_0);
	puts("Store you passwords securely using public key encryption\n");
	puts("  --help                 show usage");
	puts("  --version              display version information");
	puts("  --gpg-path <path>      Path to GnuPG executable");
	puts("  --gpg-id <id>          GnuPG ID to use");
	puts("  --file <file>          file to read passwords from");
	puts("  --passphrase-timeout <mins>    time before app forgets passphrase(in minutes)");
	puts("  --readonly             open the database readonly\n\n");
	puts("Report bugs to <ivan@ivankelly.net>");
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































































































































































































































































































































































































































































Deleted src/pwman.h.

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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifndef PW_MINDER_H
#define PW_MINDER_H

#include <curses.h>
#include <stdio.h>
#include <string.h>
#include <config.h>
#include <time.h>
#include <stdarg.h>

#define CONF_FILE 	".pwmanrc" 
/*
#define NAME_LEN	40
#define HOST_LEN	40
#define USER_LEN	40
#define PASS_LEN	40
#define LAUNCH_LEN	40

#define SHORT_STR	20
#define	MED_STR		30
#define LONG_STR	40
#define V_LONG_STR	256
*/

/* string lengths */
#define STRING_SHORT	64
#define STRING_MEDIUM	128
#define STRING_LONG	256

#define MAIN_HELPLINE 	"q:quit  ?:help  a:add  e:edit  d:delete"
#define READONLY_MSG	"RO"

#define MAX_SEARCH_DEPTH 25

#define DEFAULT_UMASK 066


#define FF_VERSION 3 

struct _PW {
	int id;
	char *name;
	char *host;
	char *user;
	char *passwd;
	char *launch;
	struct _PW *next;
};
typedef struct _PW Pw;

struct _PWList {
	char *name;
	Pw *list;
	struct _PWList *parent;
	struct _PWList *sublists;
	struct _PWList *next;

	/* ui stuff, shouldn't be here but this is a quick hack */
	int current_item;
};
typedef struct _PWList PWList;

struct _PWSearchResult {
	/* Always has a sublist, whether the list or child matches */
	PWList *sublist;
	/* If the entry itself matches, will be present */
	Pw *entry;

	/* The next one along, as with other structs */
	struct _PWSearchResult* next;
};
typedef struct _PWSearchResult PWSearchResult;


typedef struct {
	int field;
	char *filter;
} PwFilter;

typedef struct {
	char *search_term;
} PwSearch;

typedef struct {
	char *gpg_id;
	char *gpg_path;
	char *password_file;
	int passphrase_timeout;
	PwFilter *filter;
	PwSearch *search;
	int readonly;
} Options;

Options *options;
int write_options;
PWList *pwlist;
PWList *current_pw_sublist;
PWSearchResult *search_results;
time_t time_base;

char *trim_ws(char*);
void debug(char*, ...);
void pw_abort(char*, ...);
int ui_init();
int ui_run();
int ui_end();

PwFilter * filter_new();
PwSearch * search_new();
Options * options_new();

void search_get();
int search_remove();

int pwlist_add_ptr(PWList*, Pw*);
Pw* pwlist_new_pw();
PWList *pwlist_new(char*);
#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































































































































Deleted src/search.c.

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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <string.h>
#include <pwman.h>
#include <ui.h>

/*xtern int curitem;*/

PwSearch *
search_new()
{
	PwSearch *new;

	new = malloc(sizeof(PwSearch));
	if(new == NULL) {
		pw_abort("Failed to allocate memory to hold search details!");
	}

	new->search_term = malloc(STRING_LONG);
	if(new->search_term == NULL) {
		pw_abort("Failed to allocate memory to hold search term!");
	}
	new->search_term[0] = 0;

	return new;
}

/*
 * String checking only case insensitive using gnu glibc
 */
static char*
search_strcasestr(char *haystack, char *needle){
	// Never matches if null/empty string given
	if(haystack == NULL) {
		return 0;
	}
	if(strlen(haystack) == 0) {
		return 0;
	}

#ifdef HAVE_STRCASESTR
	return (char*)strcasestr(haystack, needle);
#else
	return (char*)strstr(haystack, needle);
#endif
}


PWSearchResult* 
_search_add_if_matches(PWSearchResult* current, Pw* entry, PWList* list) {
	PWSearchResult* next = NULL;

	// Did we get an entry of a list?
	if(entry != NULL) {
		if(search_strcasestr(entry->name, options->search->search_term)
			 || search_strcasestr(entry->host, options->search->search_term)
			 || search_strcasestr(entry->user, options->search->search_term)
			 || search_strcasestr(entry->passwd, options->search->search_term)
			 || search_strcasestr(entry->launch, options->search->search_term)
		) {
			next = malloc( sizeof(PWSearchResult) );
			next->entry = entry;
			next->sublist = list;
			debug("Matched entry on host '%s'", entry->host);
		}
	} else {
		if(search_strcasestr(list->name, options->search->search_term)) {
			next = malloc( sizeof(PWSearchResult) );
			next->sublist = list;
			next->entry = NULL;
			debug("Matched sublist '%s'", list->name);
		}
	}

	// If we matched, append
	if(next == NULL) {
		return current;
	} else {
		if(current == NULL) {
			// First hit
			search_results = next;
		} else {
			// Additional hit, append
			current->next = next;
		}
		// For now, nothing follows us
		next->next = NULL;
		// We are the new current entry
		return next;
	}
}


int
search_apply()
{
	PWList *stack[MAX_SEARCH_DEPTH];
	PWList *tmpList = NULL; 
	Pw *tmp = NULL; 
	int depth;
	int stepping_back;

	PWSearchResult *cur = NULL;

	// Tidy up any existing search results
	if(search_results != NULL) {
		_search_free();
	}
	// If no search term, then nothing to do!
	if( search_active(options->search) == 0 ) {
		return 1;
	}

	// Make sure we have a clean search stack so we won't get confused
	for(depth=0; depth<MAX_SEARCH_DEPTH; depth++) {
		stack[depth] = NULL;
	}

	// Setup for start
	depth = 0;
	tmpList = pwlist;
	stepping_back = 0;

	// Find anything we like the look of
	while(depth >= 0) {
		// Any sublists?
		if(!stepping_back && 
				tmpList->sublists != NULL && depth < MAX_SEARCH_DEPTH) {
			// Prepare to descend
			stack[depth] = tmpList;
			depth++;
			tmpList = tmpList->sublists;

			// Test first child
			cur = _search_add_if_matches(cur, NULL, tmpList);

			// Descend into first child
			continue;
		}
		stepping_back = 0;

		// Any entries?
		if(tmpList->list) {
			tmp = tmpList->list;
			while(tmp != NULL) {
				// Test this entry
				cur = _search_add_if_matches(cur, tmp, tmpList);
				// Next entry
				tmp = tmp->next;
			}
		}

		// Next sibling if there is one
		if(tmpList->next != NULL) {
			tmpList = tmpList->next;
			// Test sibling
			cur = _search_add_if_matches(cur, NULL, tmpList);
			// Process sibling
			continue;
		}

		// Otherwise step up
		depth--;
		stepping_back = 1;
		if(depth >= 0) {
			tmpList = stack[depth];
			stack[depth] = NULL;
		}
	}
	
	// All done
	return 1;
}

int 
search_remove()
{
	// Put things back how they should have been
	current_pw_sublist = pwlist;
	current_pw_sublist->current_item = -1;

	// Free the memory held by the search results
	_search_free();

	// Clear the search term too
	options->search->search_term[0] = 0;

	// Back to the old screen
	uilist_refresh();
}

int 
_search_free()
{
	PWSearchResult *cur;
	PWSearchResult *next;

	// Free the memory held by the search results
	cur = search_results;
	while(cur != NULL) {
		next = cur->next;
		free(cur);
		cur = next;
	}
	search_results = NULL;
}

void
search_get()
{
	char c;
	if(options->search == NULL) {
		debug("No options->search");
	} else {
		if(options->search->search_term == NULL) {
			debug("No options->search->search_term");
		} else {
			debug("Len was %d", strlen(options->search->search_term));
		}
	}

	ui_statusline_ask_str("String to search for: ", options->search->search_term, STRING_MEDIUM);

	search_apply();

	current_pw_sublist->current_item = -1;
	uilist_refresh();
}


int
search_alert(PwSearch* srch)
{
	char alert[80];	

	if( search_active(srch) == 0 ) {
		return 1;
	}

	if(search_results == NULL) {
		sprintf(alert, " (No results found for '%s')", srch->search_term);
	} else {
		sprintf(alert, " (Search results for '%s')", srch->search_term);
	}

	ui_statusline_clear();
	ui_statusline_msg(alert);
}


int search_active(PwSearch* srch)
{
	if( (srch == NULL) || (srch->search_term == NULL) ){
		/* no search object */
		return 0;
	}
	if( strlen(srch->search_term) == 0 ){
		/* no search */
		return 0;
	}
	return 1;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































































































































































































































































































































































































































































































Deleted src/ui.c.

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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <pwman.h>
#include <ui.h>
#include <help.h>
#include <time.h>
#include <stdlib.h>

char * statusline_ask_str(char *, char*, int);
Pw *get_highlighted_item();

int should_resize = FALSE;
int can_resize = FALSE;


WINDOW *top = NULL, *bottom = NULL;
extern int curitem, lines;
extern WINDOW *list;

int
ui_draw_top()
{
	werase(top);
	mvwhline(top, 1, 0, ACS_HLINE, COLS);
	if( !options->readonly) {
		mvwprintw(top, 0, 0, "%s | %s", PACKAGE " " VERSION,
			  MAIN_HELPLINE);
	} else {
		mvwprintw(top, 0, 0, "%s | %s | %s", PACKAGE " " VERSION,
			  READONLY_MSG, MAIN_HELPLINE);
	}
	
	wrefresh(top);
}

int
ui_draw_bottom()
{
	werase(bottom);
	mvwhline(bottom, 0, 0, ACS_HLINE, COLS);
	mvwhline(bottom, 2, 0, ACS_HLINE, COLS);

	wrefresh(bottom);
}

int 
ui_refresh_windows()
{
	ui_draw_top();
	ui_draw_bottom();
	uilist_refresh();

	refresh();
}

int
ui_resize_windows()
{
	wresize(top, 2, COLS);
}

static void
ui_too_small_warning()
{
	clear();
	attron(A_BOLD);
	mvprintw(((LINES-2)/2),0,"Your window is too small\n\n"
			"Minimum size is %dx%d\n\n"
			"Please resize and press any key", MIN_LINES, MIN_COLS);
	attroff(A_BOLD);
	getch();
}

#ifdef SIGWINCH
static void
ui_resize()
{
	struct winsize winsz;
	ioctl (0, TIOCGWINSZ, &winsz);

	resizeterm(winsz.ws_row, winsz.ws_col);
	if((winsz.ws_col < MIN_COLS) || (winsz.ws_row < MIN_LINES)) {
		
		/*
		 * if window is too small notify user 
		 * until he changes it
		 */
		do {
			ui_too_small_warning();
			ioctl (0, TIOCGWINSZ, &winsz);
			resizeterm(winsz.ws_row, winsz.ws_col);
		} while ((winsz.ws_col < MIN_COLS) || (winsz.ws_row < MIN_LINES));

	} else {
		should_resize = FALSE;
		/*	resize_windows();
		resize_list();*/
		ui_free_windows();
		ui_init_windows();
		ui_refresh_windows();
	}
}
#endif

static void
ui_win_changed(int i)
{
	if( can_resize ){
		ui_resize();
		ui_refresh_windows(); /* dunno why i need this but it wont work without it */
	} else {
		should_resize = TRUE;
	}
}


int
ui_init_windows()
{
	top = newwin(2, COLS,0,0);
	bottom = newwin(3, COLS, LINES - 3, 0);

	uilist_init();
}

int 
ui_free_windows()
{
	uilist_free();

	erase();
	delwin(top);
	delwin(bottom);
}

int
ui_init()
{
	initscr();
	cbreak();
	noecho();
	nonl();

	intrflush(stdscr, FALSE);
	keypad(stdscr, TRUE);

	if((LINES < MIN_LINES) || (COLS < MIN_COLS)){
		clear(); refresh(); endwin();
		fprintf(stderr, "Your terminal is to small\n");
		fprintf(stderr, "Min size is %dx%d\n", MIN_COLS, MIN_LINES);

		return 1;
	}

#ifdef SIGWINCH
	signal(SIGWINCH, ui_win_changed);
#endif

	ui_init_windows();
	ui_refresh_windows();
}

int
ui_run()
{
	Pw *current_item;
	int ch;
	int i = 0;
	int load_worked = 0;
#ifdef DEBUG
	int debug_i = 0;
#endif
	char msg[80];

	time_base = time(NULL);

	while(1){
		can_resize = TRUE;
		if( should_resize ){
			ui_resize();
		}
		ch = getch();
		ui_statusline_clear();
		can_resize = FALSE;

		if((time_base < (time(NULL) - (options->passphrase_timeout*60)))
				&& options->passphrase_timeout != 0 && tolower(ch) != 'q'){
			pwlist_write_file();
			pwlist_free_all();

			ui_statusline_msg("Passphrase has timed out and you must enter it again.");
			getch();
			
			load_worked = pwlist_read_file();
			if(load_worked != 0) {
				ui_statusline_msg("Error - unable to re-load the password file!");
				break;
			}

			time_base = time(NULL);
		}
		
		switch(ch){
			case 'Q':
			case 'q':
				if(search_results != NULL) {
					search_remove();
				} else {
					if(action_list_at_top_level()){
						return 0;
					}
				}
				break;
			case '?':
				ui_display_help();
				break;
			case KEY_PPAGE:
				uilist_page_up();
				break;
			case KEY_NPAGE:
				uilist_page_down();
				break;
			case KEY_UP:
			case 'k':
				uilist_up();
				break;
			case KEY_DOWN:
			case 'j':
				uilist_down();
				break;
			case 'A':
				if (!options->readonly){
					action_list_add_sublist();
				} else {
					statusline_readonly();
				}
				break;
			case 'U':
				action_list_up_one_level();
				break;
			case 'r':
				if (!options->readonly){
					action_list_rename();
					pwlist_write_file();
				} else {
					statusline_readonly();
				}
				break;
			case 'a':
				if (!options->readonly){
					action_list_add_pw();
					pwlist_write_file();
				} else {
					statusline_readonly();
				}
				break;
			case 'e':
			case ' ':
			case 13: /* return/enter key */
				action_list_select_item();
				/*current_item = get_current_item();
				if(current_item){
					edit_pw(current_item);
				}*/
				break;
			case 'd':
			case 0x14A: /* DEL key */
				if (!options->readonly){
					action_list_delete_item();
				} else {
					statusline_readonly();
				}
				break;
			case 'm':
				if (!options->readonly){
					action_list_move_item();
				} else {
					statusline_readonly();
				}
				break;
			case 'M':
				if (!options->readonly){
					action_list_move_item_up_level();
				} else {
					statusline_readonly();
				}
				break;
			case 'h':
				hide_cursor();
				break;
				case 's':
				show_cursor();
				break;
			case 'o':
				action_edit_options();
				break;
			case 0x17: /* control-w */
				if (!options->readonly){
					pwlist_write_file();
				} else {
					statusline_readonly();
				}
				break;
			case 0x12: /* control-r */
				action_list_read_file();
				break;
			case 0x07: /* control-g */
				pwgen_indep();
				break;
			case 0x06: /* control-f */
				gnupg_forget_passphrase();
				break;
			case 0x0C: /* control-l */
				ui_refresh_windows();
				break;
			case '/':
			case 'F':
				search_get();
				break;
			case 'f':
				filter_get();
				break;
			case 'E':
				action_list_export();
				break;
			case 'I':
				if (!options->readonly){
					pwlist_import_passwd();
					uilist_refresh();
				} else {
					statusline_readonly();
				}
				break;
			case 'L':
				action_list_locate();
				break;
			case 'l':
				action_list_launch();
				break;
			case 0x0B: /* control-k (up) */
			case '[':
				action_list_move_item_up();
				break;
			case 0x0A: /* control-j (down) */
			case ']':
				action_list_move_item_down();
				break;
#ifdef DEBUG
			case '$':
				debug_i++;
				snprintf(msg, 80, "Name %d", debug_i);
					
				pwlist_add(current_pw_sublist, msg, "myhost", "myuser", "mypasswd", "mylaucnh");
				uilist_refresh();
				break;
#endif
			default:
				break;
		}
	}
}

int
ui_end()
{
	ui_free_windows();
	clear();
	refresh();
	endwin();
	echo();
}

int 
ui_statusline_msg(char * msg)
{
	ui_statusline_clear();
	mvwaddstr(bottom, 1, 0, msg);
	refresh();
	wrefresh(bottom);
}

int 
ui_statusline_clear()
{
	wmove(bottom, 1, 0);
	wclrtoeol(bottom);
	wrefresh(bottom);
	refresh();
}

void
ui_statusline_ask_num(char *msg, int *i)
{
	int x = strlen(msg) + 5;
	char input[STRING_SHORT];

	ui_statusline_clear();
	ui_statusline_msg(msg);

	echo();
	show_cursor();

	mvwgetnstr(bottom, 1, x, input, STRING_SHORT);
	*i = atoi(input);
	
	noecho();
	hide_cursor();

	ui_statusline_clear();
}

void
ui_statusline_ask_char(char *msg, char *c, char* valid)
{
	int x = strlen(msg) + 5;
	char input[STRING_SHORT];

	*c = 0;
	do {
		ui_statusline_clear();
		if(*c != 0){
			ui_statusline_msg("Bad choice, press any key to try again");
			getch();
			ui_statusline_clear();
		}
		ui_statusline_msg(msg);

		echo();
		show_cursor();

		*c = mvwgetch(bottom, 1, x);

		noecho();
		hide_cursor();
		
	} while ( !strchr(valid, *c) );
	
	ui_statusline_clear();
}

char *
ui_statusline_ask_str(char *msg, char *input, int len)
{
	char *tmp;
	char *tmp2;
	char *tmp3;
	int x = strlen(msg) + 5;

	if(input == NULL){
		input = malloc(len);
	}
	ui_statusline_clear();
	ui_statusline_msg(msg);

	echo();
	show_cursor();
	mvwgetnstr(bottom, 1, x, input, len);
	noecho();
	hide_cursor();

	ui_statusline_clear();

	// Tabs don't play nicely with ncurses or xml
	// So, swap any for (a single) space
	tmp = input;
	while(*tmp != 0) {
		if(*tmp == 9) *tmp = ' ';
		tmp++;
	}

	// In some cases (eg when inside screen), the backspace
	// comes through to us. Handle it here if needed
	tmp = input;
	while(*tmp != 0) {
		if(*tmp == 8) {
         // tmp2 is where to copy to, tmp3 is where to copy from
         tmp3 = tmp + 1;
         if(tmp == input) {
            tmp2 = tmp;
         } else {
            tmp2 = tmp - 1;
         }

         // When we're done, start from the character
         //  we copied in to
         tmp = tmp2;

         // Process forward
         while(*tmp3 != 0) {
            *tmp2 = *tmp3;
            tmp2++;
            tmp3++;
         }
         *tmp2 = 0;
      } else {
   		tmp++;
      }
	}
	
	// All done
	return input;
}

char *
ui_statusline_ask_str_with_autogen(char *msg, char *input, int len, char *(*autogen)(char *), int ch)
{
	int i = 0;
	int c;
	char *text[2], *s;
	int x;

	if(input == NULL){
		input = malloc(len);
	}
	text[0] = malloc(STRING_MEDIUM);
	text[1] = malloc(STRING_SHORT);
	
	strncpy(text[1], msg, STRING_SHORT);
	if(s = strrchr(text[1], ':')){
		*s = 0;
	}
	snprintf(text[0], STRING_MEDIUM, "%s(%c for autogen):\t", text[1],ch);
	x = strlen(text[0]) + 5;

	ui_statusline_clear();
	ui_statusline_msg(text[0]);

	show_cursor();
	noecho();

	wmove(bottom, 1, x);

	while(i < len){
		c = wgetch(bottom);
		if(c == 0x7f){
			if(i){
				i--;
				mvwaddch(bottom, 1, x+i, ' ');
				wmove(bottom, 1, x+i);
			}
		} else if(c == 0xd){
			input[i] = 0;
			break;
		} else if(c == ch){
			input = autogen(input);
			break;
		} else {
			input[i] = c;
			mvwaddch(bottom, 1, x + i, c);
			i++;
		}
	}
	
	hide_cursor();
	
	ui_statusline_clear();

	free(text[0]);
	free(text[1]);

	return input;
}

char *
ui_statusline_ask_passwd(char *msg, char *input, int len, int cancel)
{
	int i = 0;
	int c;
	int x = strlen(msg) + 5;

	if(!input){
		input = malloc(len);
	}
	ui_statusline_clear();
	ui_statusline_msg(msg);

	show_cursor();
	noecho();

	wmove(bottom, 1, x);

	while(i < len){
		c = wgetch(bottom);
		if(c == 0x7f){ /* 0x7f = delete */
			if(i){
				i--;
				mvwaddch(bottom, 1, x+i, ' ');
				wmove(bottom, 1, x+i);
			}
		} else if(c == 0xd){ /* 0xd == enter/return */
			input[i] = 0;
			break;
		} else if(c == cancel){
			free(input);
			input = NULL;

			return input;
		} else {
			input[i] = c;
			mvwaddch(bottom, 1, x + i, '*');
			i++;
		}
	}
	
	hide_cursor();
	
	ui_statusline_clear();
	
	return input;
}

int 
ui_statusline_yes_no(char *msg, int def)
{
	int ret = -1, len;
	char *msg2;
	int ch;
	
	len = strlen(msg) + 10;
	msg2 = malloc(len);

	snprintf(msg2, len,  "%s%s", msg, def ? " (Y/n)?" : " (y/N)?", NULL);

	while(ret == -1){
		ui_statusline_msg(msg2);
		
		ch = getch();
		switch( ch ){
			case 'n':
			case 'N':
				ret = FALSE;
				break;
			case 'y':
			case 'Y':
				ret = TRUE;
				break;
			case 13:
				ret = def;
				break;
			default:
				ui_statusline_msg("Bad option, try again.");
				getch();
				break;
		}
	}

	free(msg2);
	ui_statusline_clear();

	return ret;
}

void
statusline_readonly()
{
	ui_statusline_msg("Password file is opened readonly");
}

int 
ui_display_help()
{
	int i;
	WINDOW *helpwin;

	helpwin = newwin(LINES - 5, COLS - 6, 3, 3);
	uilist_clear();

	for(i = 0; help[i] != NULL; i++){
		waddstr(helpwin, help[i]);
		if( !((i+1) % (LINES - 9)) || (help[i+1] == NULL) ){
	/*		refresh();*/
			wrefresh(helpwin);
			ui_statusline_msg("Press any key to continue...");
			getch();
			wclear(helpwin);
		}
	}
	uilist_refresh();
	ui_statusline_clear();
	delwin(helpwin);
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted src/ui.h.

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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifndef UI_H
#define UI_H

#include <curses.h>
#include <signal.h>
#include <ctype.h>

#ifdef HAVE_TERMIOS_H
#       include <termios.h>
#else   
#       ifdef HAVE_LINUX_TERMIOS_H
#               include <linux/termios.h>
#       endif
#endif
#ifdef HAVE_SYS_IOCTL_H
#       include <sys/ioctl.h>
#endif

#define MIN_LINES 22
#define MIN_COLS 60

#define LIST_TOP 3 
#define LIST_BOTTOM (LINES -3)
#define LIST_LINES (LIST_BOTTOM-LIST_TOP)

#define LAST_LIST_ITEM (first_list_item + LIST_LINES - 1)
#define NAMELEN (COLS/3)-1
#define NAMEPOS 2

#define HOSTLEN (COLS/3)-1
#define HOSTPOS (NAMEPOS + NAMELEN + 1)

#define USERLEN (COLS/3)-1
#define USERPOS (NAMEPOS + NAMELEN + HOSTLEN + 2)
#define hide_cursor() curs_set(0)
#define show_cursor() curs_set(1)

#define NUM_TO_CHAR(n) (n + 48)
#define CHAR_TO_NUM(n) (n - 49)

typedef enum {
	STRING,     // A regular string
	INT,        // An integer
	INFORMATION // Name only, no value, so read only
} TYPE;

typedef enum {
	PW_NULL,
	PW_ITEM,
	PW_SUBLIST,
	PW_UPLEVEL
} LIST_ITEM_TYPE;

typedef struct {
	char *name;
	void *value; // int* or char*
	int max_length;
	TYPE type;
	char *(*autogen)(char*);
} InputField;

int uilist_init();
int uilist_free();
int uilist_refresh();
int ui_statusline_clear();

int view_pw(int i);

int ui_statusline_yes_no(char *, int);
int ui_statusline_msg(char *msg);
void ui_statusline_ask_num(char *, int *);
void ui_statusline_ask_char(char *, char *, char*);
char * ui_statusline_ask_str(char *, char *, int len);
char * ui_statusline_ask_passwd(char *, char *, int, int);
char * ui_statusline_ask_str_with_autogen(char *msg, char *input, int len, char *(*autogen)(char *), int ch);

void statusline_readonly();
#endif


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































































Deleted src/uilist.c.

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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <ui.h>
#include <pwman.h>

WINDOW *list = NULL;
int lines = 0;
int first_list_item = 0;
//int curitem = 0;

int
uilist_init()
{
	char str[80];
	list = newwin(LIST_LINES, COLS, LIST_TOP, 0);
	
	scrollok(list, TRUE);
}
/*
int
resize_list()
{
	wresize(list, LIST_LINES, COLS);
}
*/

int
uilist_free()
{
	delwin(list);
	list = NULL;
}

int 
uilist_highlight_line(int line)
{
	wstandout(list);
/*	mvwchgat(list, i, 0, -1, A_STANDOUT, 0, NULL);*/
        scrollok(list, FALSE);
	        {
                int i;
                wmove(list, line, 0);
                for(i = 0; i < COLS; i++)
                        waddch(list, ' ');
	        /*wattrset(win, 0);*/
        }
        scrollok(list, TRUE);
}

PWSearchResult *
uilist_get_highlighted_searchresult() {
	PWSearchResult *srchiter;
	int i = -1;

	for(srchiter = search_results; (srchiter != NULL); srchiter = srchiter->next) {
		i++;
		if(i == current_pw_sublist->current_item){
			break;
		}
	}
	return srchiter;
}

PWList *
uilist_get_highlighted_sublist()
{
	PWList *iter;
	int i = -1;

	if(!current_pw_sublist){ return NULL; }
	if(current_pw_sublist->parent){ i++; }

	for(iter = current_pw_sublist->sublists; iter != NULL; iter = iter->next){
		i++;
		if(i == current_pw_sublist->current_item){
			break;
		}
	}
	return iter;
}

Pw *
uilist_get_highlighted_item()
{	
	Pw *iter;
	PWList *listiter;
	int i = -1;

	if(current_pw_sublist->parent){ i++; }
	
	for(listiter = current_pw_sublist->sublists; listiter != NULL; listiter = listiter->next){
		i++;
	}
		
	for(iter = current_pw_sublist->list; iter != NULL; iter = iter->next){
		if( filter_apply(iter, options->filter) ){
			i++;
		}
		if( i == current_pw_sublist->current_item ){
			debug("get_highlighted_item: found %d, break now", i);
			return iter;
		}
	}
/*	fprintf(stderr, "%d.", curitem);
	for(iter = pwlist; (iter != NULL) && i <= curitem; iter = iter->next){
		if( apply_filter(iter, options->filter) ){
			i++;	
		}	
	}*/
	debug("get_highlighted_item: nothing found, return NULL");
	return NULL;
}

LIST_ITEM_TYPE
uilist_get_highlighted_type()
{
	Pw *iter;
	PWList *listiter;
	int i = -1;

	if(current_pw_sublist->parent){
		if(current_pw_sublist->current_item == 0){
			return PW_UPLEVEL;
		}
		i++;
	}
	for(listiter = current_pw_sublist->sublists; listiter != NULL; listiter = listiter->next){
		i++;
		if(i == current_pw_sublist->current_item){
			return PW_SUBLIST;
		}
	}
		
	for(iter = current_pw_sublist->list; iter != NULL; iter = iter->next){
		if( filter_apply(iter, options->filter) ){
			i++;
		}
		if( i == current_pw_sublist->current_item ){
			return PW_ITEM;
		}
	}
	return PW_NULL;
}

// Draw a sublist on the screen
int
_uilist_render_sublist(PWList *sublist, int i, int num_shown)
{
	if((i >= first_list_item) && (i <= LAST_LIST_ITEM)){
		if(lines == current_pw_sublist->current_item){
			uilist_highlight_line(num_shown);
		} else {
			wattrset(list, A_BOLD);
		}
		mvwprintw(list, num_shown, NAMEPOS, "%s ->", sublist->name);
		wattrset(list, A_NORMAL);
		wstandend(list);
		num_shown++;
	}
	return num_shown;
}
// Draw an entry summary on the screen
int
_uilist_render_entry(Pw *entry, int i, int num_shown)
{
	if((i >= first_list_item) && (i <= LAST_LIST_ITEM)){
		if(lines == current_pw_sublist->current_item){
			uilist_highlight_line(num_shown);
		}
		mvwaddnstr(list, num_shown, NAMEPOS, entry->name, NAMELEN);
		mvwaddnstr(list, num_shown, HOSTPOS, entry->host, HOSTLEN);
		mvwaddnstr(list, num_shown, USERPOS, entry->user, USERLEN);
		wstandend(list);
		num_shown++;
	}
	return num_shown;
}

int
uilist_refresh()
{
	Pw *iter;
	PWList *listiter;
	PWSearchResult *srchiter;
	int i = 0;
	int num_shown = 0;

	debug("refresh_list: refreshing list");
	if(list == NULL){
		uilist_init();
	}
	if(current_pw_sublist == NULL){
		return -1;
	}

	uilist_clear();;
	first_list_item = 0;
	lines = 0;

	uilist_headerline();

	// Ensure we don't end up off the screen
	if(current_pw_sublist->current_item < 0){
		current_pw_sublist->current_item = 0;
	}
	if(current_pw_sublist->current_item < first_list_item){
		first_list_item = current_pw_sublist->current_item;		
	} else if((current_pw_sublist->current_item > LAST_LIST_ITEM)){
		first_list_item = current_pw_sublist->current_item - (LIST_LINES-1);
	}

	if(search_results == NULL) {
		// If we aren't at the top level, off the "Up One Level" item
		if(current_pw_sublist->parent && search_results == NULL){
			if((i >= first_list_item) && (i <= LAST_LIST_ITEM)){
				if(lines == current_pw_sublist->current_item){
					uilist_highlight_line(num_shown);
				} else {
					wattrset(list, A_BOLD);
				}
				mvwprintw(list, num_shown, NAMEPOS, "<Up One Level - \"%s\">", current_pw_sublist->parent->name);
				wattrset(list, A_NORMAL);
				wstandend(list);
				num_shown++;
			}
			i++; 
			lines++;
		}
		// Draw our sublists
		for(listiter = current_pw_sublist->sublists; listiter != NULL; listiter = listiter->next){
			num_shown = _uilist_render_sublist(listiter, i, num_shown);
			lines++;
			i++; 
		}
		// Draw our entries, if the filter says it's ok
		for(iter = current_pw_sublist->list; (iter != NULL); iter = iter->next){
			/*
			 * if line satifies filter criteria increment i and lines
			 */
			if( filter_apply(iter, options->filter) ){
				num_shown = _uilist_render_entry(iter, i, num_shown);
				lines++;
				i++;	
			}
		}
	} else {
		for(srchiter = search_results; (srchiter != NULL); srchiter = srchiter->next) {
			if(srchiter->entry != NULL) {
				num_shown = _uilist_render_entry(srchiter->entry, i, num_shown);
			} else {
				num_shown = _uilist_render_sublist(srchiter->sublist, i, num_shown);
			}
			lines++;
			i++;	
		}
	}

	wrefresh(list);
	hide_cursor();

	// Is the cursor off the screen, after moving up or down the tree?
	// (Don't trigger this if we have no entries yet)
	if(current_pw_sublist->current_item) {
		if((lines-1) < current_pw_sublist->current_item) {
			// Just adjust, then redraw
			current_pw_sublist->current_item = lines-1;
			uilist_refresh();
		}
	}

	// If we have filtering turned on, then warn the user of that
	if(options->filter) {
		filter_alert(options->filter);
	}

	// If we have searching active, then warn the user of that
	if(options->search) {
		search_alert(options->search);
	}

	debug("refresh_list: done refreshing list");
}

int
uilist_clear()
{
	int i;
	
	werase(list);
	for(i = 0; i < COLS; i++){
		mvaddch(2, i, ' ');
	}
}

int
uilist_headerline()
{
	int i;

	show_cursor();
	attrset(A_BOLD);

	mvaddnstr(2, NAMEPOS, "Name", NAMELEN);
	mvaddnstr(2, HOSTPOS, "Host", HOSTLEN);
	mvaddnstr(2, USERPOS, "Username", USERLEN);

	attrset(A_NORMAL);
	hide_cursor();
}

int 
uilist_page_up()
{
	current_pw_sublist->current_item -= (LIST_LINES - 1);

	if(current_pw_sublist->current_item < 1){
		current_pw_sublist->current_item = 0;
	}
	uilist_refresh();
}

int
uilist_page_down()
{
	current_pw_sublist->current_item += (LIST_LINES - 1);

	if(current_pw_sublist->current_item >= (lines - 1)){
		current_pw_sublist->current_item = lines -1;
	}
	uilist_refresh();
}

int
uilist_up()
{
	if(current_pw_sublist->current_item < 1){
		return;
	}

	current_pw_sublist->current_item--;
	
	uilist_refresh();
}

int
uilist_down()
{
	if(current_pw_sublist->current_item >= (lines-1)){
		return;
	}

	current_pw_sublist->current_item++;

	uilist_refresh();
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































































































































































































































































































































































































































































































Added ui.c.























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <pwman.h>
#include <ui.h>
#include <help.h>
#include <time.h>
#include <stdlib.h>

char * statusline_ask_str(char *, char*, int);
Pw *get_highlighted_item();

int should_resize = FALSE;
int can_resize = FALSE;


WINDOW *top = NULL, *bottom = NULL;
extern int curitem, lines;
extern WINDOW *list;

int
ui_draw_top()
{
	werase(top);
	mvwhline(top, 1, 0, ACS_HLINE, COLS);
	if( !options->readonly) {
		mvwprintw(top, 0, 0, "%s | %s", PACKAGE " " VERSION,
			  MAIN_HELPLINE);
	} else {
		mvwprintw(top, 0, 0, "%s | %s | %s", PACKAGE " " VERSION,
			  READONLY_MSG, MAIN_HELPLINE);
	}
	
	wrefresh(top);
}

int
ui_draw_bottom()
{
	werase(bottom);
	mvwhline(bottom, 0, 0, ACS_HLINE, COLS);
	mvwhline(bottom, 2, 0, ACS_HLINE, COLS);

	wrefresh(bottom);
}

int 
ui_refresh_windows()
{
	ui_draw_top();
	ui_draw_bottom();
	uilist_refresh();

	refresh();
}

int
ui_resize_windows()
{
	wresize(top, 2, COLS);
}

static void
ui_too_small_warning()
{
	clear();
	attron(A_BOLD);
	mvprintw(((LINES-2)/2),0,"Your window is too small\n\n"
			"Minimum size is %dx%d\n\n"
			"Please resize and press any key", MIN_LINES, MIN_COLS);
	attroff(A_BOLD);
	getch();
}

#ifdef SIGWINCH
static void
ui_resize()
{
	struct winsize winsz;
	ioctl (0, TIOCGWINSZ, &winsz);

	resizeterm(winsz.ws_row, winsz.ws_col);
	if((winsz.ws_col < MIN_COLS) || (winsz.ws_row < MIN_LINES)) {
		
		/*
		 * if window is too small notify user 
		 * until he changes it
		 */
		do {
			ui_too_small_warning();
			ioctl (0, TIOCGWINSZ, &winsz);
			resizeterm(winsz.ws_row, winsz.ws_col);
		} while ((winsz.ws_col < MIN_COLS) || (winsz.ws_row < MIN_LINES));

	} else {
		should_resize = FALSE;
		/*	resize_windows();
		resize_list();*/
		ui_free_windows();
		ui_init_windows();
		ui_refresh_windows();
	}
}
#endif

static void
ui_win_changed(int i)
{
	if( can_resize ){
		ui_resize();
		ui_refresh_windows(); /* dunno why i need this but it wont work without it */
	} else {
		should_resize = TRUE;
	}
}


int
ui_init_windows()
{
	top = newwin(2, COLS,0,0);
	bottom = newwin(3, COLS, LINES - 3, 0);

	uilist_init();
}

int 
ui_free_windows()
{
	uilist_free();

	erase();
	delwin(top);
	delwin(bottom);
}

int
ui_init()
{
	initscr();
	cbreak();
	noecho();
	nonl();

	intrflush(stdscr, FALSE);
	keypad(stdscr, TRUE);

	if((LINES < MIN_LINES) || (COLS < MIN_COLS)){
		clear(); refresh(); endwin();
		fprintf(stderr, "Your terminal is to small\n");
		fprintf(stderr, "Min size is %dx%d\n", MIN_COLS, MIN_LINES);

		return 1;
	}

#ifdef SIGWINCH
	signal(SIGWINCH, ui_win_changed);
#endif

	ui_init_windows();
	ui_refresh_windows();
}

int
ui_run()
{
	Pw *current_item;
	int ch;
	int i = 0;
	int load_worked = 0;
#ifdef DEBUG
	int debug_i = 0;
#endif
	char msg[80];

	time_base = time(NULL);

	while(1){
		can_resize = TRUE;
		if( should_resize ){
			ui_resize();
		}
		ch = getch();
		ui_statusline_clear();
		can_resize = FALSE;

		if((time_base < (time(NULL) - (options->passphrase_timeout*60)))
				&& options->passphrase_timeout != 0 && tolower(ch) != 'q'){
			pwlist_write_file();
			pwlist_free_all();

			ui_statusline_msg("Passphrase has timed out and you must enter it again.");
			getch();
			
			load_worked = pwlist_read_file();
			if(load_worked != 0) {
				ui_statusline_msg("Error - unable to re-load the password file!");
				break;
			}

			time_base = time(NULL);
		}
		
		switch(ch){
			case 'Q':
			case 'q':
				if(search_results != NULL) {
					search_remove();
				} else {
					if(action_list_at_top_level()){
						return 0;
					}
				}
				break;
			case '?':
				ui_display_help();
				break;
			case KEY_PPAGE:
				uilist_page_up();
				break;
			case KEY_NPAGE:
				uilist_page_down();
				break;
			case KEY_UP:
			case 'k':
				uilist_up();
				break;
			case KEY_DOWN:
			case 'j':
				uilist_down();
				break;
			case 'A':
				if (!options->readonly){
					action_list_add_sublist();
				} else {
					statusline_readonly();
				}
				break;
			case 'U':
				action_list_up_one_level();
				break;
			case 'r':
				if (!options->readonly){
					action_list_rename();
					pwlist_write_file();
				} else {
					statusline_readonly();
				}
				break;
			case 'a':
				if (!options->readonly){
					action_list_add_pw();
					pwlist_write_file();
				} else {
					statusline_readonly();
				}
				break;
			case 'e':
			case ' ':
			case 13: /* return/enter key */
				action_list_select_item();
				/*current_item = get_current_item();
				if(current_item){
					edit_pw(current_item);
				}*/
				break;
			case 'd':
			case 0x14A: /* DEL key */
				if (!options->readonly){
					action_list_delete_item();
				} else {
					statusline_readonly();
				}
				break;
			case 'm':
				if (!options->readonly){
					action_list_move_item();
				} else {
					statusline_readonly();
				}
				break;
			case 'M':
				if (!options->readonly){
					action_list_move_item_up_level();
				} else {
					statusline_readonly();
				}
				break;
			case 'h':
				hide_cursor();
				break;
				case 's':
				show_cursor();
				break;
			case 'o':
				action_edit_options();
				break;
			case 0x17: /* control-w */
				if (!options->readonly){
					pwlist_write_file();
				} else {
					statusline_readonly();
				}
				break;
			case 0x12: /* control-r */
				action_list_read_file();
				break;
			case 0x07: /* control-g */
				pwgen_indep();
				break;
			case 0x06: /* control-f */
				gnupg_forget_passphrase();
				break;
			case 0x0C: /* control-l */
				ui_refresh_windows();
				break;
			case '/':
			case 'F':
				search_get();
				break;
			case 'f':
				filter_get();
				break;
			case 'E':
				action_list_export();
				break;
			case 'I':
				if (!options->readonly){
					pwlist_import_passwd();
					uilist_refresh();
				} else {
					statusline_readonly();
				}
				break;
			case 'L':
				action_list_locate();
				break;
			case 'l':
				action_list_launch();
				break;
			case 0x0B: /* control-k (up) */
			case '[':
				action_list_move_item_up();
				break;
			case 0x0A: /* control-j (down) */
			case ']':
				action_list_move_item_down();
				break;
#ifdef DEBUG
			case '$':
				debug_i++;
				snprintf(msg, 80, "Name %d", debug_i);
					
				pwlist_add(current_pw_sublist, msg, "myhost", "myuser", "mypasswd", "mylaucnh");
				uilist_refresh();
				break;
#endif
			default:
				break;
		}
	}
}

int
ui_end()
{
	ui_free_windows();
	clear();
	refresh();
	endwin();
	echo();
}

int 
ui_statusline_msg(char * msg)
{
	ui_statusline_clear();
	mvwaddstr(bottom, 1, 0, msg);
	refresh();
	wrefresh(bottom);
}

int 
ui_statusline_clear()
{
	wmove(bottom, 1, 0);
	wclrtoeol(bottom);
	wrefresh(bottom);
	refresh();
}

void
ui_statusline_ask_num(char *msg, int *i)
{
	int x = strlen(msg) + 5;
	char input[STRING_SHORT];

	ui_statusline_clear();
	ui_statusline_msg(msg);

	echo();
	show_cursor();

	mvwgetnstr(bottom, 1, x, input, STRING_SHORT);
	*i = atoi(input);
	
	noecho();
	hide_cursor();

	ui_statusline_clear();
}

void
ui_statusline_ask_char(char *msg, char *c, char* valid)
{
	int x = strlen(msg) + 5;
	char input[STRING_SHORT];

	*c = 0;
	do {
		ui_statusline_clear();
		if(*c != 0){
			ui_statusline_msg("Bad choice, press any key to try again");
			getch();
			ui_statusline_clear();
		}
		ui_statusline_msg(msg);

		echo();
		show_cursor();

		*c = mvwgetch(bottom, 1, x);

		noecho();
		hide_cursor();
		
	} while ( !strchr(valid, *c) );
	
	ui_statusline_clear();
}

char *
ui_statusline_ask_str(char *msg, char *input, int len)
{
	char *tmp;
	char *tmp2;
	char *tmp3;
	int x = strlen(msg) + 5;

	if(input == NULL){
		input = malloc(len);
	}
	ui_statusline_clear();
	ui_statusline_msg(msg);

	echo();
	show_cursor();
	mvwgetnstr(bottom, 1, x, input, len);
	noecho();
	hide_cursor();

	ui_statusline_clear();

	// Tabs don't play nicely with ncurses or xml
	// So, swap any for (a single) space
	tmp = input;
	while(*tmp != 0) {
		if(*tmp == 9) *tmp = ' ';
		tmp++;
	}

	// In some cases (eg when inside screen), the backspace
	// comes through to us. Handle it here if needed
	tmp = input;
	while(*tmp != 0) {
		if(*tmp == 8) {
         // tmp2 is where to copy to, tmp3 is where to copy from
         tmp3 = tmp + 1;
         if(tmp == input) {
            tmp2 = tmp;
         } else {
            tmp2 = tmp - 1;
         }

         // When we're done, start from the character
         //  we copied in to
         tmp = tmp2;

         // Process forward
         while(*tmp3 != 0) {
            *tmp2 = *tmp3;
            tmp2++;
            tmp3++;
         }
         *tmp2 = 0;
      } else {
   		tmp++;
      }
	}
	
	// All done
	return input;
}

char *
ui_statusline_ask_str_with_autogen(char *msg, char *input, int len, char *(*autogen)(char *), int ch)
{
	int i = 0;
	int c;
	char *text[2], *s;
	int x;

	if(input == NULL){
		input = malloc(len);
	}
	text[0] = malloc(STRING_MEDIUM);
	text[1] = malloc(STRING_SHORT);
	
	strncpy(text[1], msg, STRING_SHORT);
	if(s = strrchr(text[1], ':')){
		*s = 0;
	}
	snprintf(text[0], STRING_MEDIUM, "%s(%c for autogen):\t", text[1],ch);
	x = strlen(text[0]) + 5;

	ui_statusline_clear();
	ui_statusline_msg(text[0]);

	show_cursor();
	noecho();

	wmove(bottom, 1, x);

	while(i < len){
		c = wgetch(bottom);
		if(c == 0x7f){
			if(i){
				i--;
				mvwaddch(bottom, 1, x+i, ' ');
				wmove(bottom, 1, x+i);
			}
		} else if(c == 0xd){
			input[i] = 0;
			break;
		} else if(c == ch){
			input = autogen(input);
			break;
		} else {
			input[i] = c;
			mvwaddch(bottom, 1, x + i, c);
			i++;
		}
	}
	
	hide_cursor();
	
	ui_statusline_clear();

	free(text[0]);
	free(text[1]);

	return input;
}

char *
ui_statusline_ask_passwd(char *msg, char *input, int len, int cancel)
{
	int i = 0;
	int c;
	int x = strlen(msg) + 5;

	if(!input){
		input = malloc(len);
	}
	ui_statusline_clear();
	ui_statusline_msg(msg);

	show_cursor();
	noecho();

	wmove(bottom, 1, x);

	while(i < len){
		c = wgetch(bottom);
		if(c == 0x7f){ /* 0x7f = delete */
			if(i){
				i--;
				mvwaddch(bottom, 1, x+i, ' ');
				wmove(bottom, 1, x+i);
			}
		} else if(c == 0xd){ /* 0xd == enter/return */
			input[i] = 0;
			break;
		} else if(c == cancel){
			free(input);
			input = NULL;

			return input;
		} else {
			input[i] = c;
			mvwaddch(bottom, 1, x + i, '*');
			i++;
		}
	}
	
	hide_cursor();
	
	ui_statusline_clear();
	
	return input;
}

int 
ui_statusline_yes_no(char *msg, int def)
{
	int ret = -1, len;
	char *msg2;
	int ch;
	
	len = strlen(msg) + 10;
	msg2 = malloc(len);

	snprintf(msg2, len,  "%s%s", msg, def ? " (Y/n)?" : " (y/N)?", NULL);

	while(ret == -1){
		ui_statusline_msg(msg2);
		
		ch = getch();
		switch( ch ){
			case 'n':
			case 'N':
				ret = FALSE;
				break;
			case 'y':
			case 'Y':
				ret = TRUE;
				break;
			case 13:
				ret = def;
				break;
			default:
				ui_statusline_msg("Bad option, try again.");
				getch();
				break;
		}
	}

	free(msg2);
	ui_statusline_clear();

	return ret;
}

void
statusline_readonly()
{
	ui_statusline_msg("Password file is opened readonly");
}

int 
ui_display_help()
{
	int i;
	WINDOW *helpwin;

	helpwin = newwin(LINES - 5, COLS - 6, 3, 3);
	uilist_clear();

	for(i = 0; help[i] != NULL; i++){
		waddstr(helpwin, help[i]);
		if( !((i+1) % (LINES - 9)) || (help[i+1] == NULL) ){
	/*		refresh();*/
			wrefresh(helpwin);
			ui_statusline_msg("Press any key to continue...");
			getch();
			wclear(helpwin);
		}
	}
	uilist_refresh();
	ui_statusline_clear();
	delwin(helpwin);
}

Added ui.h.









































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifndef UI_H
#define UI_H

#include <curses.h>
#include <signal.h>
#include <ctype.h>

#ifdef HAVE_TERMIOS_H
#       include <termios.h>
#else   
#       ifdef HAVE_LINUX_TERMIOS_H
#               include <linux/termios.h>
#       endif
#endif
#ifdef HAVE_SYS_IOCTL_H
#       include <sys/ioctl.h>
#endif

#define MIN_LINES 22
#define MIN_COLS 60

#define LIST_TOP 3 
#define LIST_BOTTOM (LINES -3)
#define LIST_LINES (LIST_BOTTOM-LIST_TOP)

#define LAST_LIST_ITEM (first_list_item + LIST_LINES - 1)
#define NAMELEN (COLS/3)-1
#define NAMEPOS 2

#define HOSTLEN (COLS/3)-1
#define HOSTPOS (NAMEPOS + NAMELEN + 1)

#define USERLEN (COLS/3)-1
#define USERPOS (NAMEPOS + NAMELEN + HOSTLEN + 2)
#define hide_cursor() curs_set(0)
#define show_cursor() curs_set(1)

#define NUM_TO_CHAR(n) (n + 48)
#define CHAR_TO_NUM(n) (n - 49)

typedef enum {
	STRING,     // A regular string
	INT,        // An integer
	INFORMATION // Name only, no value, so read only
} TYPE;

typedef enum {
	PW_NULL,
	PW_ITEM,
	PW_SUBLIST,
	PW_UPLEVEL
} LIST_ITEM_TYPE;

typedef struct {
	char *name;
	void *value; // int* or char*
	int max_length;
	TYPE type;
	char *(*autogen)(char*);
} InputField;

int uilist_init();
int uilist_free();
int uilist_refresh();
int ui_statusline_clear();

int view_pw(int i);

int ui_statusline_yes_no(char *, int);
int ui_statusline_msg(char *msg);
void ui_statusline_ask_num(char *, int *);
void ui_statusline_ask_char(char *, char *, char*);
char * ui_statusline_ask_str(char *, char *, int len);
char * ui_statusline_ask_passwd(char *, char *, int, int);
char * ui_statusline_ask_str_with_autogen(char *msg, char *input, int len, char *(*autogen)(char *), int ch);

void statusline_readonly();
#endif


Added uilist.c.













































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
 *  PWMan - password management application
 *
 *  Copyright (C) 2002  Ivan Kelly <ivan@ivankelly.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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <ui.h>
#include <pwman.h>

WINDOW *list = NULL;
int lines = 0;
int first_list_item = 0;
//int curitem = 0;

int
uilist_init()
{
	char str[80];
	list = newwin(LIST_LINES, COLS, LIST_TOP, 0);
	
	scrollok(list, TRUE);
}
/*
int
resize_list()
{
	wresize(list, LIST_LINES, COLS);
}
*/

int
uilist_free()
{
	delwin(list);
	list = NULL;
}

int 
uilist_highlight_line(int line)
{
	wstandout(list);
/*	mvwchgat(list, i, 0, -1, A_STANDOUT, 0, NULL);*/
        scrollok(list, FALSE);
	        {
                int i;
                wmove(list, line, 0);
                for(i = 0; i < COLS; i++)
                        waddch(list, ' ');
	        /*wattrset(win, 0);*/
        }
        scrollok(list, TRUE);
}

PWSearchResult *
uilist_get_highlighted_searchresult() {
	PWSearchResult *srchiter;
	int i = -1;

	for(srchiter = search_results; (srchiter != NULL); srchiter = srchiter->next) {
		i++;
		if(i == current_pw_sublist->current_item){
			break;
		}
	}
	return srchiter;
}

PWList *
uilist_get_highlighted_sublist()
{
	PWList *iter;
	int i = -1;

	if(!current_pw_sublist){ return NULL; }
	if(current_pw_sublist->parent){ i++; }

	for(iter = current_pw_sublist->sublists; iter != NULL; iter = iter->next){
		i++;
		if(i == current_pw_sublist->current_item){
			break;
		}
	}
	return iter;
}

Pw *
uilist_get_highlighted_item()
{	
	Pw *iter;
	PWList *listiter;
	int i = -1;

	if(current_pw_sublist->parent){ i++; }
	
	for(listiter = current_pw_sublist->sublists; listiter != NULL; listiter = listiter->next){
		i++;
	}
		
	for(iter = current_pw_sublist->list; iter != NULL; iter = iter->next){
		if( filter_apply(iter, options->filter) ){
			i++;
		}
		if( i == current_pw_sublist->current_item ){
			debug("get_highlighted_item: found %d, break now", i);
			return iter;
		}
	}
/*	fprintf(stderr, "%d.", curitem);
	for(iter = pwlist; (iter != NULL) && i <= curitem; iter = iter->next){
		if( apply_filter(iter, options->filter) ){
			i++;	
		}	
	}*/
	debug("get_highlighted_item: nothing found, return NULL");
	return NULL;
}

LIST_ITEM_TYPE
uilist_get_highlighted_type()
{
	Pw *iter;
	PWList *listiter;
	int i = -1;

	if(current_pw_sublist->parent){
		if(current_pw_sublist->current_item == 0){
			return PW_UPLEVEL;
		}
		i++;
	}
	for(listiter = current_pw_sublist->sublists; listiter != NULL; listiter = listiter->next){
		i++;
		if(i == current_pw_sublist->current_item){
			return PW_SUBLIST;
		}
	}
		
	for(iter = current_pw_sublist->list; iter != NULL; iter = iter->next){
		if( filter_apply(iter, options->filter) ){
			i++;
		}
		if( i == current_pw_sublist->current_item ){
			return PW_ITEM;
		}
	}
	return PW_NULL;
}

// Draw a sublist on the screen
int
_uilist_render_sublist(PWList *sublist, int i, int num_shown)
{
	if((i >= first_list_item) && (i <= LAST_LIST_ITEM)){
		if(lines == current_pw_sublist->current_item){
			uilist_highlight_line(num_shown);
		} else {
			wattrset(list, A_BOLD);
		}
		mvwprintw(list, num_shown, NAMEPOS, "%s ->", sublist->name);
		wattrset(list, A_NORMAL);
		wstandend(list);
		num_shown++;
	}
	return num_shown;
}
// Draw an entry summary on the screen
int
_uilist_render_entry(Pw *entry, int i, int num_shown)
{
	if((i >= first_list_item) && (i <= LAST_LIST_ITEM)){
		if(lines == current_pw_sublist->current_item){
			uilist_highlight_line(num_shown);
		}
		mvwaddnstr(list, num_shown, NAMEPOS, entry->name, NAMELEN);
		mvwaddnstr(list, num_shown, HOSTPOS, entry->host, HOSTLEN);
		mvwaddnstr(list, num_shown, USERPOS, entry->user, USERLEN);
		wstandend(list);
		num_shown++;
	}
	return num_shown;
}

int
uilist_refresh()
{
	Pw *iter;
	PWList *listiter;
	PWSearchResult *srchiter;
	int i = 0;
	int num_shown = 0;

	debug("refresh_list: refreshing list");
	if(list == NULL){
		uilist_init();
	}
	if(current_pw_sublist == NULL){
		return -1;
	}

	uilist_clear();;
	first_list_item = 0;
	lines = 0;

	uilist_headerline();

	// Ensure we don't end up off the screen
	if(current_pw_sublist->current_item < 0){
		current_pw_sublist->current_item = 0;
	}
	if(current_pw_sublist->current_item < first_list_item){
		first_list_item = current_pw_sublist->current_item;		
	} else if((current_pw_sublist->current_item > LAST_LIST_ITEM)){
		first_list_item = current_pw_sublist->current_item - (LIST_LINES-1);
	}

	if(search_results == NULL) {
		// If we aren't at the top level, off the "Up One Level" item
		if(current_pw_sublist->parent && search_results == NULL){
			if((i >= first_list_item) && (i <= LAST_LIST_ITEM)){
				if(lines == current_pw_sublist->current_item){
					uilist_highlight_line(num_shown);
				} else {
					wattrset(list, A_BOLD);
				}
				mvwprintw(list, num_shown, NAMEPOS, "<Up One Level - \"%s\">", current_pw_sublist->parent->name);
				wattrset(list, A_NORMAL);
				wstandend(list);
				num_shown++;
			}
			i++; 
			lines++;
		}
		// Draw our sublists
		for(listiter = current_pw_sublist->sublists; listiter != NULL; listiter = listiter->next){
			num_shown = _uilist_render_sublist(listiter, i, num_shown);
			lines++;
			i++; 
		}
		// Draw our entries, if the filter says it's ok
		for(iter = current_pw_sublist->list; (iter != NULL); iter = iter->next){
			/*
			 * if line satifies filter criteria increment i and lines
			 */
			if( filter_apply(iter, options->filter) ){
				num_shown = _uilist_render_entry(iter, i, num_shown);
				lines++;
				i++;	
			}
		}
	} else {
		for(srchiter = search_results; (srchiter != NULL); srchiter = srchiter->next) {
			if(srchiter->entry != NULL) {
				num_shown = _uilist_render_entry(srchiter->entry, i, num_shown);
			} else {
				num_shown = _uilist_render_sublist(srchiter->sublist, i, num_shown);
			}
			lines++;
			i++;	
		}
	}

	wrefresh(list);
	hide_cursor();

	// Is the cursor off the screen, after moving up or down the tree?
	// (Don't trigger this if we have no entries yet)
	if(current_pw_sublist->current_item) {
		if((lines-1) < current_pw_sublist->current_item) {
			// Just adjust, then redraw
			current_pw_sublist->current_item = lines-1;
			uilist_refresh();
		}
	}

	// If we have filtering turned on, then warn the user of that
	if(options->filter) {
		filter_alert(options->filter);
	}

	// If we have searching active, then warn the user of that
	if(options->search) {
		search_alert(options->search);
	}

	debug("refresh_list: done refreshing list");
}

int
uilist_clear()
{
	int i;
	
	werase(list);
	for(i = 0; i < COLS; i++){
		mvaddch(2, i, ' ');
	}
}

int
uilist_headerline()
{
	int i;

	show_cursor();
	attrset(A_BOLD);

	mvaddnstr(2, NAMEPOS, "Name", NAMELEN);
	mvaddnstr(2, HOSTPOS, "Host", HOSTLEN);
	mvaddnstr(2, USERPOS, "Username", USERLEN);

	attrset(A_NORMAL);
	hide_cursor();
}

int 
uilist_page_up()
{
	current_pw_sublist->current_item -= (LIST_LINES - 1);

	if(current_pw_sublist->current_item < 1){
		current_pw_sublist->current_item = 0;
	}
	uilist_refresh();
}

int
uilist_page_down()
{
	current_pw_sublist->current_item += (LIST_LINES - 1);

	if(current_pw_sublist->current_item >= (lines - 1)){
		current_pw_sublist->current_item = lines -1;
	}
	uilist_refresh();
}

int
uilist_up()
{
	if(current_pw_sublist->current_item < 1){
		return;
	}

	current_pw_sublist->current_item--;
	
	uilist_refresh();
}

int
uilist_down()
{
	if(current_pw_sublist->current_item >= (lines-1)){
		return;
	}

	current_pw_sublist->current_item++;

	uilist_refresh();
}