summaryrefslogtreecommitdiff
path: root/com32/modules/pxechn.c
blob: 26376900e6535a24df8dad5f1dabed2694ac4d75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
/* ----------------------------------------------------------------------- *
 *
 *   Copyright 2010-2012 Gene Cumm - All Rights Reserved
 *
 *   Portions from chain.c:
 *   Copyright 2003-2009 H. Peter Anvin - All Rights Reserved
 *   Copyright 2009-2010 Intel Corporation; author: H. Peter Anvin
 *   Significant portions copyright (C) 2010 Shao Miller
 *					[partition iteration, GPT, "fs"]
 *
 *   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, Inc., 53 Temple Place Ste 330,
 *   Boston MA 02111-1307, USA; either version 2 of the License, or
 *   (at your option) any later version; incorporated herein by reference.
 *
 * ----------------------------------------------------------------------- */

/*
 * pxechn.c
 *
 * PXE Chain Loader; Chain load to another PXE network boot program
 * that may be on another host.
 */

#include <stdio.h>
#include <stdlib.h>
#include <consoles.h>
#include <console.h>
#include <errno.h>
#include <string.h>
#include <syslinux/config.h>
#include <syslinux/loadfile.h>
#include <syslinux/bootrm.h>
#include <syslinux/video.h>
#include <com32.h>
#include <stdint.h>
#include <syslinux/pxe.h>
#include <sys/gpxe.h>
#include <unistd.h>
#include <getkey.h>
#include <dhcp.h>
#include <limits.h>


#ifdef DEBUG
#  define PXECHN_DEBUG 1
#else
#  define PXECHN_DEBUG 0
#endif

typedef union {
    uint64_t q;
    uint32_t l[2];
    uint16_t w[4];
    uint8_t b[8];
} reg64_t;

#define dprintf0(f, ...)		((void)0)

#ifndef dprintf
#  if (PXECHN_DEBUG > 0)
#    define dprintf			printf
#  else
#    define dprintf(f, ...)		((void)0)
#  endif
#endif

#if (PXECHN_DEBUG > 0)
#  define dpressanykey			pressanykey
#  define dprint_pxe_bootp_t		print_pxe_bootp_t
#  define dprint_pxe_vendor_blk		print_pxe_vendor_blk
#  define dprint_pxe_vendor_raw		print_pxe_vendor_raw
#else
#  define dpressanykey(tm)		((void)0)
#  define dprint_pxe_bootp_t(p, l)	((void)0)
#  define dprint_pxe_vendor_blk(p, l)	((void)0)
#  define dprint_pxe_vendor_raw(p, l)	((void)0)
#endif

#define dprintf_opt_cp		dprintf0
#define dprintf_opt_inj		dprintf0
#define dprintf_pc_pa		dprintf
#define dprintf_pc_so_s		dprintf0

#define t_PXENV_RESTART_TFTP	t_PXENV_TFTP_READ_FILE

#define STACK_SPLIT	11

/* same as pxelinux.asm REBOOT_TIME */
#define REBOOT_TIME	300

#define NUM_DHCP_OPTS		256
#define DHCP_OPT_LEN_MAX	256
#define PXE_VENDOR_RAW_PRN_MAX	0x7F
#define PXECHN_HOST_LEN		256	/* 63 bytes per label; 255 max total */

#define PXECHN_NUM_PKT_TYPE	3
#define PXECHN_NUM_PKT_AVAIL	2*PXECHN_NUM_PKT_TYPE
#define PXECHN_PKT_TYPE_START	PXENV_PACKET_TYPE_DHCP_DISCOVER

#define PXECHN_FORCE_PKT1	0x80000000
#define PXECHN_FORCE_PKT2	0x40000000
#define PXECHN_FORCE_ALL	(PXECHN_FORCE_PKT1 | PXECHN_FORCE_PKT2)
#define PXECHN_FORCE_ALL_1	0
#define STRASINT_str		('s' + (('t' + ('r' << 8)) << 8))

#define min(a,b) (((a) < (b)) ? (a) : (b))

const char app_name_str[] = "pxechn.c32";

struct pxelinux_opt {
    char *fn;	/* Filename as passed to us */
    in_addr_t fip;	/* fn's IP component */
    char *fp;	/* fn's path component */
    in_addr_t gip;	/* giaddr; Gateway/DHCP relay */
    uint32_t force;
    uint32_t wait;	/* Additional decision to wait before boot */
    int32_t wds;	/* WDS option/level */
    in_addr_t sip;	/* siaddr: Next Server IP Address */
    struct dhcp_option p[PXECHN_NUM_PKT_AVAIL];
	/* original _DHCP_DISCOVER, _DHCP_ACK, _CACHED_REPLY then modified packets */
    char host[PXECHN_HOST_LEN];
    struct dhcp_option opts[PXECHN_NUM_PKT_TYPE][NUM_DHCP_OPTS];
    char p_unpacked[PXECHN_NUM_PKT_TYPE];
};


/* from chain.c */
struct data_area {
    void *data;
    addr_t base;
    addr_t size;
};

/* From chain.c */
static inline void error(const char *msg)
{
    fputs(msg, stderr);
}

/* From chain.c */
static void do_boot(struct data_area *data, int ndata,
		    struct syslinux_rm_regs *regs)
{
    uint16_t *const bios_fbm = (uint16_t *) 0x413;
    addr_t dosmem = *bios_fbm << 10;	/* Technically a low bound */
    struct syslinux_memmap *mmap;
    struct syslinux_movelist *mlist = NULL;
    addr_t endimage;
    int i;

    mmap = syslinux_memory_map();

    if (!mmap) {
	error("Cannot read system memory map\n");
	return;
    }

    endimage = 0;
    for (i = 0; i < ndata; i++) {
	if (data[i].base + data[i].size > endimage)
	    endimage = data[i].base + data[i].size;
    }
    if (endimage > dosmem)
	goto too_big;

    for (i = 0; i < ndata; i++) {
	if (syslinux_add_movelist(&mlist, data[i].base,
				  (addr_t) data[i].data, data[i].size))
	    goto enomem;
    }


    /* Tell the shuffler not to muck with this area... */
    syslinux_add_memmap(&mmap, endimage, 0xa0000 - endimage, SMT_RESERVED);

    /* Force text mode */
    syslinux_force_text_mode();

    fputs("Booting...\n", stdout);
    syslinux_shuffle_boot_rm(mlist, mmap, 3, regs);
    error("Chainboot failed!\n");
    return;

too_big:
    error("Loader file too large\n");
    return;

enomem:
    error("Out of memory\n");
    return;
}

void usage(void)
{
    printf("USAGE:\n"
        "    %s [OPTIONS]... _new-nbp_\n"
	"    %s -r _new-nbp_    (calls PXE stack PXENV_RESTART_TFTP)\n"
	"OPTIONS:\n"
	"    [-c config] [-g gateway] [-p prefix] [-t reboot] [-u] [-w] [-W]"
	" [-o opt.ty=val]\n\n",
	app_name_str, app_name_str);
}

void pxe_error(int ierr, const char *evt, const char *msg)
{
    if (msg)
	printf("%s", msg);
    else if (evt)
	printf("Error while %s: ", evt);
    printf("%d:%s\n", ierr, strerror(ierr));
}

int pressanykey(clock_t tm) {
    int inc;

    printf("Press any key to continue. ");
    inc = get_key(stdin, tm);
    puts("");
    return inc;
}

int dhcp_find_opt(pxe_bootp_t *p, size_t len, uint8_t opt)
{
    int rv = -1;
    int i, vlen, oplen;
    uint8_t *d;
    uint32_t magic;

    if (!p) {
	dprintf("  packet pointer is null\n");
	return rv;
    }
    vlen = len - ((void *)&(p->vendor) - (void *)p);
    d = p->vendor.d;
    magic = ntohl(*((uint32_t *)d));
    if (magic != VM_RFC1048)	/* Invalid DHCP packet */
	vlen = 0;
    for (i = 4; i < vlen; i++) {
	if (d[i] == opt) {
	    dprintf("\n    @%03X-%2d\n", i, d[i]);
	    rv = i;
	    break;
	}
	if (d[i] == ((NUM_DHCP_OPTS) - 1))	/* End of list */
	    break;
	if (d[i]) {		/* Skip padding */
	    oplen = d[++i];
	    i += oplen;
	}
    }
    return rv;
}

void print_pxe_vendor_raw(pxe_bootp_t *p, size_t len)
{
    int i, vlen;

    if (!p) {
	printf("  packet pointer is null\n");
	return;
    }
    vlen = len - ((void *)&(p->vendor) - (void *)p);
    if (vlen > PXE_VENDOR_RAW_PRN_MAX)
	vlen = PXE_VENDOR_RAW_PRN_MAX;
    dprintf("  rawLen = %d", vlen);
    for (i = 0; i < vlen; i++) {
	if ((i & 0xf) == 0)
	    printf("\n  %04X:", i);
	printf(" %02X", p->vendor.d[i]);
    }
    printf("\n");
}

void print_pxe_vendor_blk(pxe_bootp_t *p, size_t len)
{
    int i, vlen, oplen, j;
    uint8_t *d;
    uint32_t magic;
    if (!p) {
	printf("  packet pointer is null\n");
	return;
    }
    vlen = len - ((void *)&(p->vendor) - (void *)p);
    printf("  Vendor Data:    Len=%d", vlen);
    d = p->vendor.d;
    magic = ntohl(*((uint32_t *)d));
    printf("    Magic: %08X", ntohl(*((uint32_t *)d)));
    if (magic != VM_RFC1048)	/* Invalid DHCP packet */
	vlen = 0;
    for (i = 4; i < vlen; i++) {
	if (d[i])	/* Skip the padding */
	    printf("\n    @%03X-%3d", i, d[i]);
	if (d[i] == ((NUM_DHCP_OPTS) - 1))	/* End of list */
	    break;
	if (d[i]) {
	    oplen = d[++i];
	    printf(" l=%3d:", oplen);
	    for (j = (++i + oplen); i < vlen && i < j; i++) {
		printf(" %02X", d[i]);
	    }
	    i--;
	}
    }
    printf("\n");
}

void print_pxe_bootp_t(pxe_bootp_t *p, size_t len)
{
    if (!p || len <= 0) {
	printf("  packet pointer is null\n");
	return;
    }
    printf("  op:%02X  hw:%02X  hl:%02X  gh:%02X  id:%08X se:%04X f:%04X"
	"  cip:%08X\n", p->opcode, p->Hardware, p->Hardlen, p->Gatehops,
	ntohl(p->ident), ntohs(p->seconds), ntohs(p->Flags), ntohl(p->cip));
    printf("  yip:%08X  sip:%08X  gip:%08X",
	ntohl(p->yip), ntohl(p->sip), ntohl(p->gip));
    printf("  caddr-%02X:%02X:%02X:%02X:%02X:%02X\n", p->CAddr[0],
	p->CAddr[1], p->CAddr[2], p->CAddr[3], p->CAddr[4], p->CAddr[5]);
    printf("  sName: '%s'\n", p->Sname);
    printf("  bootfile: '%s'\n", p->bootfile);
    dprint_pxe_vendor_blk(p, len);
}

void pxe_set_regs(struct syslinux_rm_regs *regs)
{
    com32sys_t tregs;

    regs->ip = 0x7C00;
    /* Plan A uses SS:[SP + 4] */
    /* sdi->pxe.stack is a usable pointer, not something that can be nicely
       and reliably split to SS:SP without causing issues */
    tregs.eax.l = 0x000A;
    __intcall(0x22, &tregs, &tregs);
    regs->ss = tregs.fs;
    regs->esp.l = tregs.esi.w[0] + sizeof(tregs);
    /* Plan B uses [ES:BX] */
    regs->es = tregs.es;
    regs->ebx = tregs.ebx;
    dprintf("\nsp:%04x    ss:%04x    es:%04x    bx:%04x\n", regs->esp.w[0],
	regs->ss, regs->es, regs->ebx.w[0]);
    /* Zero out everything else just to be sure */
    regs->cs = regs->ds = regs->fs = regs->gs = 0;
    regs->eax.l = regs->ecx.l = regs->edx.l = 0;
}

int hostlen_limit(int len)
{
    return min(len, ((PXECHN_HOST_LEN) - 1));
}

//FIXME: To a library
/* Parse a filename into an IPv4 address and filename pointer
 *	returns	Based on the interpretation of fn
 *		0 regular file name
 *		1 in format IP::FN
 *		2 TFTP URL
 *		3 HTTP URL
 *		4 FTP URL
 *		3 + 2^30 HTTPS URL
 *		-1 if fn is another URL type
 */
int pxechn_parse_fn(char fn[], in_addr_t *fip, char *host, char *fp[])
{
    in_addr_t tip = 0;
    char *csep, *ssep, *hsep;	/* Colon, Slash separator positions */
    int hlen, plen;	/* Hostname, protocol length */
    int rv = 0;

    csep = strchr(fn, ':');
    if (csep) {
	if (csep[1] == ':') {	/* assume IP::FN */
	    *fp = &csep[2];
	    rv = 1;
	    if (fn[0] != ':') {
		hlen = hostlen_limit(csep - fn);
		memcpy(host, fn, hlen);
		host[hlen] = 0;
	    }
	} else if ((csep[1] == '/') && (csep[2] == '/')) {
		/* URL: proto://host:port/path/file */
		/* proto://[user[:passwd]@]host[:port]/path/file */
	    ssep = strchr(csep + 3, '/');
	    if (ssep) {
		hlen = hostlen_limit(ssep - (csep + 3));
		*fp = ssep + 1;
	    } else {
		hlen = hostlen_limit(strlen(csep + 3));
	    }
	    memcpy(host, (csep + 3), hlen);
	    host[hlen] = 0;
	    plen = csep - fn;
	    if (strncmp(fn, "tftp", plen) == 0)
		rv = 2;
	    else if (strncmp(fn, "http", plen) == 0)
		rv = 3;
	    else if (strncmp(fn, "ftp", plen) == 0)
		rv = 4;
	    else if (strncmp(fn, "https", plen) == 0)
		rv = 3 + ( 1 << 30 );
	    else
		rv = -1;
	} else {
	    csep = NULL;
	}
    }
    if (!csep) {
	*fp = fn;
    }
    if (host[0]) {
	hsep = strchr(host, '@');
	if (!hsep)
	    hsep = host;
	tip = pxe_dns(hsep);
    }
    if (tip != 0)
	*fip = tip;
    dprintf0("  host '%s'\n  fp   '%s'\n  fip  %08x\n", host, *fp, ntohl(*fip));
    return rv;
}

void pxechn_opt_free(struct dhcp_option *opt)
{
    free(opt->data);
    opt->len = -1;
}

void pxechn_fill_pkt(struct pxelinux_opt *pxe, int ptype)
{
    int rv = -1;
    int p1, p2;
    if ((ptype < 0) || (ptype > PXECHN_NUM_PKT_TYPE))
	rv = -2;
    p1 = ptype - PXECHN_PKT_TYPE_START;
    p2 = p1 + PXECHN_NUM_PKT_TYPE;
    if ((rv >= -1) && (!pxe_get_cached_info(ptype,
	    (void **)&(pxe->p[p1].data), (size_t *)&(pxe->p[p1].len)))) {
	pxe->p[p2].data = malloc(2048);
	if (pxe->p[p2].data) {
	    memcpy(pxe->p[p2].data, pxe->p[p1].data, pxe->p[p1].len);
	    pxe->p[p2].len = pxe->p[p1].len;
	    rv = 0;
	    dprint_pxe_bootp_t((pxe_bootp_t *)(pxe->p[p1].data), pxe->p[p1].len);
	    dpressanykey(INT_MAX);
	} else {
	    printf("%s: ERROR: Unable to malloc() for second packet\n", app_name_str);
	}
    } else {
	printf("%s: ERROR: Unable to retrieve first packet\n", app_name_str);
    }
    if (rv <= -1) {
	pxechn_opt_free(&pxe->p[p1]);
    }
}

void pxechn_init(struct pxelinux_opt *pxe)
{
    /* Init for paranoia */
    pxe->fn = NULL;
    pxe->fp = NULL;
    pxe->force = 0;
    pxe->wait = 0;
    pxe->gip = 0;
    pxe->wds = 0;
    pxe->sip = 0;
    pxe->host[0] = 0;
    pxe->host[((NUM_DHCP_OPTS) - 1)] = 0;
    for (int j = 0; j < PXECHN_NUM_PKT_TYPE; j++){
	for (int i = 0; i < NUM_DHCP_OPTS; i++) {
	    pxe->opts[j][i].data = NULL;
	    pxe->opts[j][i].len = -1;
	}
	pxe->p_unpacked[j] = 0;
	pxe->p[j].data = NULL;
	pxe->p[j+PXECHN_NUM_PKT_TYPE].data = NULL;
	pxe->p[j].len = 0;
	pxe->p[j+PXECHN_NUM_PKT_TYPE].len = 0;
    }
    pxechn_fill_pkt(pxe, PXENV_PACKET_TYPE_CACHED_REPLY);
}

int pxechn_to_hex(char i)
{
    if (i >= '0' && i <= '9')
	return (i - '0');
    if (i >= 'A' && i <= 'F')
	return (i - 'A' + 10);
    if (i >= 'a' && i <= 'f')
	return (i - 'a' + 10);
    if (i == 0)
	return -1;
    return -2;
}

int pxechn_parse_2bhex(char ins[])
{
    int ret = -2;
    int n0 = -3, n1 = -3;
    /* NULL pointer */
    if (!ins) {
	ret = -1;
    /* pxechn_to_hex can handle the NULL character by returning -1 and
       breaking the execution of the statement chain */
    } else if (((n0 = pxechn_to_hex(ins[0])) >= 0)
	    && ((n1 = pxechn_to_hex(ins[1])) >= 0)) {
	ret = (n0 * 16) + n1;
    } else if (n0 == -1) {	/* Leading NULL char */
	ret = -1;
    }
    return ret;
}

int pxechn_optnum_ok(int optnum)
{
    if ((optnum > 0) && (optnum < ((NUM_DHCP_OPTS) - 1)))
	return 1;
    return 0;
}

int pxechn_optnum_ok_notres(int optnum)
{
    if ((optnum <= 0) && (optnum >= ((NUM_DHCP_OPTS) - 1)))
	return 0;
    switch(optnum){
    case 66: case 67:
	return 0;
	break;
    default:	return 1;
    }
}

int pxechn_optlen_ok(int optlen)
{
    if ((optlen >= 0) && (optlen < ((DHCP_OPT_LEN_MAX) - 1)))
	return 1;
    return 0;
}

int pxechn_setopt(struct dhcp_option *opt, void *data, int len)
{
    void *p;
    if (!opt || !data)
	return -1;
    if (len < 0) {
	return -3;
    }
    p = realloc(opt->data, len);
    if (!p && len) {	/* Allow for len=0 */
	pxechn_opt_free(opt);
	return -2;
    }
    opt->data = p;
    memcpy(opt->data, data, len);
    opt->len = len;
    return len;
}

int pxechn_setopt_str(struct dhcp_option *opt, void *data)
{
    return pxechn_setopt(opt, data, strnlen(data, DHCP_OPT_LEN_MAX));
}

int pxechn_parse_int(char *data, char istr[], int tlen)
{
    int terr = errno;

    if ((tlen == 1) || (tlen == 2) || (tlen == 4)) {
	errno = 0;
	uint32_t optval = strtoul(istr, NULL, 0);
	if (errno)
	    return -3;
	errno = terr;
	switch(tlen){
	case  1:
	    if (optval & 0xFFFFFF00)
		return -4;
	    break;
	case  2:
	    if (optval & 0xFFFF0000)
		return -4;
	    optval = htons(optval);
	    break;
	case  4:
	    optval = htonl(optval);
	    break;
	}
	memcpy(data, &optval, tlen);
    } else if (tlen == 8) {
	errno = 0;
	uint64_t optval = strtoull(istr, NULL, 0);
	if (errno)
	    return -3;
	errno = terr;
	optval = htonq(optval);
	memcpy(data, &optval, tlen);
    } else {
	return -2;
    }
    return tlen;
}

int pxechn_parse_hex_sep(char *data, char istr[], char sep)
{
    int len = 0;
    int ipos = 0, ichar;
    
    if (!data || !istr)
	return -1;
    while ((istr[ipos]) && (len < DHCP_OPT_LEN_MAX)) {
	dprintf(" %02X%02X", *((int *)(istr + ipos)) & 0xFF, *((int *)(istr + ipos +1)) & 0xFF);
	ichar = pxechn_parse_2bhex(istr + ipos);
	if (ichar >=0) {
	    data[len++] = ichar;
	} else {
	    return -EINVAL;
	}
	if (!istr[ipos+2]){
	    ipos += 2;
	} else if (istr[ipos+2] != sep) {
	    return -(EINVAL + 1);
	} else {
	    ipos += 3;
	}
    }
    return len;
}

int pxechn_parse_opttype(char istr[], int optnum)
{
    char *pos;
    int tlen, type, tmask;

    if (!istr)
	return -1;
    pos = strchr(istr, '=');
    if (!pos)
	return -2;
    if (istr[0] != '.') {
	if (!pxechn_optnum_ok(optnum))
	    return -3;
	return -3;	/* do lookup here */
    } else {
	tlen = pos - istr - 1;
	if ((tlen < 1) || (tlen > 4))
	    return -4;
	tmask = 0xFFFFFFFF >> (8 * (4 - tlen));
	type = (*(int*)(istr + 1)) & tmask;
    }
    return type;
}

int pxechn_parse_setopt(struct dhcp_option opts[], struct dhcp_option *iopt,
			char istr[])
{
    int rv = 0, optnum, opttype;
    char *cpos = NULL, *pos;

    if (!opts || !iopt || !(iopt->data))
	return -1;
    if (!istr || !istr[0])
	return -2;
    // -EINVAL;
    optnum = strtoul(istr, &cpos, 0);
    if (!pxechn_optnum_ok(optnum))
	return -3;
    pos = strchr(cpos, '=');
    if (!pos)
	return -4;
    opttype = pxechn_parse_opttype(cpos, optnum);
    pos++;
    switch(opttype) {
    case 'b':
	iopt->len = pxechn_parse_int(iopt->data, pos, 1);
	break;
    case 'l':
	iopt->len = pxechn_parse_int(iopt->data, pos, 4);
	break;
    case 'q':
	iopt->len = pxechn_parse_int(iopt->data, pos, 8);
	break;
    case 's':
    case STRASINT_str:
	iopt->len = strlen(pos);
	if (iopt->len > DHCP_OPT_LEN_MAX)
	    iopt->len = DHCP_OPT_LEN_MAX;
	memcpy(iopt->data, pos, iopt->len);
	dprintf_pc_so_s("s.len=%d\trv=%d\n", iopt->len, rv);
	break;
    case 'w':
	iopt->len = pxechn_parse_int(iopt->data, pos, 2);
	break;
    case 'x':
	iopt->len = pxechn_parse_hex_sep(iopt->data, pos, ':');
	break;
    default:
	return -6;
	break;
    }
    if (pxechn_optlen_ok(iopt->len)) {
	rv = pxechn_setopt(&(opts[optnum]), (void *)(iopt->data), iopt->len);
    }
    if((opttype == 's') || (opttype == STRASINT_str))
	dprintf_pc_so_s("rv=%d\n", rv);
    return rv;
}

int pxechn_parse_force(const char istr[])
{
    uint32_t rv = 0;
    char *pos;
    int terr = errno;

    errno = 0;
    rv = strtoul(istr, &pos, 0);
    if ((istr == pos ) || ((rv == ULONG_MAX) && (errno)))
	rv = 0;
    errno = terr;
    return rv;
}

int pxechn_uuid_set(struct pxelinux_opt *pxe)
{
    int ret = 0;

    if (!pxe->p_unpacked[0])
	ret = dhcp_unpack_packet((pxe_bootp_t *)(pxe->p[0].data),
				 pxe->p[0].len, pxe->opts[0]);
    if (ret) {
	error("Could not unpack packet\n");
	return -ret;	/* dhcp_unpack_packet always returns positive errors */
    }

    if (pxe->opts[0][97].len >= 0 )
	pxechn_setopt(&(pxe->opts[2][97]), pxe->opts[0][97].data, pxe->opts[0][97].len);
	return 1;
    return 0;
}

int pxechn_parse_args(int argc, char *argv[], struct pxelinux_opt *pxe,
			 struct dhcp_option opts[])
{
    int arg, optnum, rv = 0;
    char *p = NULL;
    const char optstr[] = "c:f:g:o:p:St:uwW";
    struct dhcp_option iopt;

    if (pxe->p[5].data)
	pxe->fip = ( (pxe_bootp_t *)(pxe->p[5].data) )->sip;
    else
	pxe->fip = 0;
    /* Fill */
    pxe->fn = argv[0];
    pxechn_parse_fn(pxe->fn, &(pxe->fip), pxe->host, &(pxe->fp));
    pxechn_setopt_str(&(opts[67]), pxe->fp);
    pxechn_setopt_str(&(opts[66]), pxe->host);
    iopt.data = malloc(DHCP_OPT_LEN_MAX);
    iopt.len = 0;
    while ((rv >= 0) && (arg = getopt(argc, argv, optstr)) >= 0) {
	dprintf_pc_pa("  Got arg '%c'/'%c' addr %08X val %s\n", arg == '?' ? optopt : arg, arg, (unsigned int)optarg, optarg ? optarg : "");
	switch(arg) {
	case 'c':	/* config */
	    pxechn_setopt_str(&(opts[209]), optarg);
	    break;
	case 'f':	/* force */
	    pxe->force = pxechn_parse_force(optarg);
	    break;
	case 'g':	/* gateway/DHCP relay */
	    pxe->gip = pxe_dns(optarg);
	    break;
	case 'n':	/* native */
	    break;
	case 'o':	/* option */
	    rv = pxechn_parse_setopt(opts, &iopt, optarg);
	    break;
	case 'p':	/* prefix */
	    pxechn_setopt_str(&(opts[210]), optarg);
	    break;
	case 'S':	/* sip from sName */
	    pxe->sip = 1;
	    break;
	case 't':	/* timeout */
	    optnum = strtoul(optarg, &p, 0);
	    if (p != optarg) {
		optnum = htonl(optnum);
		pxechn_setopt(&(opts[211]), (void *)(&optnum), 4);
	    } else {
		rv = -3;
	    }
	    break;
	case 'u':	/* UUID: copy option 97 from packet 1 if present */
	    pxechn_uuid_set(pxe);
	    break;
	case 'w':	/* wait */
	    pxe->wait = 1;
	    break;
	case 'W':	/* WDS */
	    pxe->wds = 1;
	    break;
	case '?':
	    rv = -'?';
	default:
	    break;
	}
	if (rv >= 0)	/* Clear it since getopt() doesn't guarentee it */
	    optarg = NULL;
    }
    if (iopt.data)
	pxechn_opt_free(&iopt);
/* FIXME: consider reordering the application of parsed command line options
       such that the new nbp may be at the end */
    if (rv >= 0) {
	rv = 0;
    } else if (arg != '?') {
	printf("Invalid argument for -%c: %s\n", arg, optarg);
    }
    dprintf("pxechn_parse_args rv=%d\n", rv);
    return rv;
}

int pxechn_args(int argc, char *argv[], struct pxelinux_opt *pxe)
{
    pxe_bootp_t *bootp0, *bootp1;
    int ret = 0;
    struct dhcp_option *opts;
    char *str;

    opts = pxe->opts[2];
    /* Start filling packet #1 */
    bootp0 = (pxe_bootp_t *)(pxe->p[2].data);
    bootp1 = (pxe_bootp_t *)(pxe->p[5].data);

    ret = dhcp_unpack_packet(bootp0, pxe->p[2].len, opts);
    if (ret) {
	error("Could not unpack packet\n");
	return -ret;
    }
    pxe->p_unpacked[2] = 1;
    pxe->gip = bootp1->gip;

    ret = pxechn_parse_args(argc, argv, pxe, opts);
    if (ret)
	return ret;
    if (pxe->sip > 0xFFFFFF) {	/* a real IPv4 address */
	bootp1->sip = pxe->sip;
    } else if ((pxe->sip == 1)
		&& (opts[66].len > 0)){
	/* unterminated? */
	if (strnlen(opts[66].data, opts[66].len) == (size_t)opts[66].len) {
	    str = malloc(opts[66].len + 1);
	    if (str) {
		memcpy(str, opts[66].data, opts[66].len);
		str[opts[66].len] = 0;
	    }	
	} else {
	    str = opts[66].data;
	}
	if (str) {
	    bootp1->sip = pxe_dns(str);
	    if (str != opts[66].data)
		free(str);
	} else {
	    bootp1->sip = pxe->fip;
	}
    } else {
	bootp1->sip = pxe->fip;
    }
    bootp1->gip = pxe->gip;

    ret = dhcp_pack_packet(bootp1, (size_t *)&(pxe->p[5].len), opts);
    if (ret) {
	error("Could not pack packet\n");
	return -ret;	/* dhcp_pack_packet always returns positive errors */
    }
    return ret;
}

/* dhcp_pkt2pxe: Copy packet to PXE's BC data for a ptype packet
 *	Input:
 *	p	Packet data to copy
 *	len	length of data to copy
 *	ptype	Packet type to overwrite
 */
int dhcp_pkt2pxe(pxe_bootp_t *p, size_t len, int ptype)
{
    com32sys_t reg;
    t_PXENV_GET_CACHED_INFO *ci;
    void *cp;
    int rv = -1;

    if (!(ci = lzalloc(sizeof(t_PXENV_GET_CACHED_INFO)))){
	dprintf("Unable to lzalloc() for PXE call structure\n");
	rv = 1;
	goto ret;
    }
    ci->Status = PXENV_STATUS_FAILURE;
    ci->PacketType = ptype;
    memset(&reg, 0, sizeof(reg));
    reg.eax.w[0] = 0x0009;
    reg.ebx.w[0] = PXENV_GET_CACHED_INFO;
    reg.edi.w[0] = OFFS(ci);
    reg.es = SEG(ci);
    __intcall(0x22, &reg, &reg);

    if (ci->Status != PXENV_STATUS_SUCCESS) {
	dprintf("PXE Get Cached Info failed: %d\n", ci->Status);
	rv = 2;
	goto ret;
    }

    cp = MK_PTR(ci->Buffer.seg, ci->Buffer.offs);
    if (!(memcpy(cp, p, len))) {
	dprintf("Failed to copy packet\n");
	rv = 3;
	goto ret;
    }
ret:
    lfree(ci);
   return rv;
}

int pxechn_mergeopt(struct pxelinux_opt *pxe, int d, int s)
{
    int ret = 0, i;

    if ((d >= PXECHN_NUM_PKT_TYPE) || (s >= PXECHN_NUM_PKT_TYPE) 
	    || (d < 0) || (s < 0)) {
	return -2;
    }
    if (!pxe->p_unpacked[s])
	ret = dhcp_unpack_packet(pxe->p[s].data, pxe->p[s].len, pxe->opts[s]);
    if (ret) {
	error("Could not unpack packet for merge\n");
	printf("Error %d (%d)\n", ret, EINVAL);
	if (ret == EINVAL) {
	    if (pxe->p[s].len < 240)
		printf("Packet %d is too short: %d (240)\n", s, pxe->p[s].len);
	    else if (((const struct dhcp_packet *)(pxe->p[s].data))->magic != htonl(DHCP_VENDOR_MAGIC))
		printf("Packet %d has no magic\n", s);
	    else
		error("Unknown EINVAL error\n");
	} else {
	    error("Unknown error\n");
	}
	return -ret;
    }
    for (i = 0; i < NUM_DHCP_OPTS; i++) {
	if (pxe->opts[d][i].len <= -1) {
	    if (pxe->opts[s][i].len >= 0)
		pxechn_setopt(&(pxe->opts[d][i]), pxe->opts[s][i].data, pxe->opts[s][i].len);
	}
    }
    return 0;
}

/* pxechn: Chainload to new PXE file ourselves
 *	Input:
 *	argc	Count of arguments passed
 *	argv	Values of arguments passed
 *	Returns	0 on success (which should never happen)
 *		1 on loadfile() error
 *		2 if DHCP Option 52 (Option Overload) used file field
 *		-1 on usage error
 */
int pxechn(int argc, char *argv[])
{
    struct pxelinux_opt pxe;
    pxe_bootp_t* p[(2 * PXECHN_NUM_PKT_TYPE)];
    int rv = 0;
    int i;
    struct data_area file;
    struct syslinux_rm_regs regs;

    pxechn_init(&pxe);
    for (i = 0; i < (2 * PXECHN_NUM_PKT_TYPE); i++) {
	p[i] = (pxe_bootp_t *)(pxe.p[i].data);
    }

    /* Parse arguments and patch packet 1 */
    rv = pxechn_args(argc, argv, &pxe);
    dpressanykey(INT_MAX);
    if (rv)
	goto ret;
    pxe_set_regs(&regs);
    /* Load the file late; it's the most time-expensive operation */
    printf("%s: Attempting to load '%s': ", app_name_str, pxe.fn);
    if (loadfile(pxe.fn, &file.data, &file.size)) {
	pxe_error(errno, NULL, NULL);
	rv = -2;
	goto ret;
    }
    puts("loaded.");
    /* we'll be shuffling to the standard location of 7C00h */
    file.base = 0x7C00;
    if ((pxe.wds) || 
	    ((pxe.force) && ((pxe.force & (~PXECHN_FORCE_ALL)) == 0))) {
	printf("Forcing behavior %08X\n", pxe.force);
	// P2 is the same as P3 if no PXE server present.
	if ((pxe.wds) ||
		(pxe.force & PXECHN_FORCE_PKT2)) {
	    pxechn_fill_pkt(&pxe, PXENV_PACKET_TYPE_DHCP_ACK);
	    rv = pxechn_mergeopt(&pxe, 2, 1);
	    if (rv) {
		dprintf("Merge Option returned %d\n", rv);
	    }
	    rv = dhcp_pack_packet(p[5], (size_t *)&(pxe.p[5].len), pxe.opts[2]);
	    rv = dhcp_pkt2pxe(p[5], pxe.p[5].len, PXENV_PACKET_TYPE_DHCP_ACK);
	}
	if (pxe.force & PXECHN_FORCE_PKT1) {
	    puts("Unimplemented force option utilized");
	}
    }
    rv = dhcp_pkt2pxe(p[5], pxe.p[5].len, PXENV_PACKET_TYPE_CACHED_REPLY);
    dprint_pxe_bootp_t(p[5], pxe.p[5].len);
    if ((pxe.wds) ||
	    ((pxe.force) && ((pxe.force & (~PXECHN_FORCE_ALL)) == 0))) {
	// printf("Forcing behavior %08X\n", pxe.force);
	// P2 is the same as P3 if no PXE server present.
	if ((pxe.wds) ||
		(pxe.force & PXECHN_FORCE_PKT2)) {
	    rv = dhcp_pkt2pxe(p[5], pxe.p[5].len, PXENV_PACKET_TYPE_DHCP_ACK);
	}
    } else if (pxe.force) {
	printf("FORCE: bad argument %08X\n", pxe.force);
    }
    printf("\n...Ready to boot:\n");
    if (pxe.wait) {
	pressanykey(INT_MAX);
    } else {
	dpressanykey(INT_MAX);
    }
    if (true) {
	puts("  Attempting to boot...");
	do_boot(&file, 1, &regs);
    }
    /* If failed, copy backup back in and abort */
    dhcp_pkt2pxe(p[2], pxe.p[2].len, PXENV_PACKET_TYPE_CACHED_REPLY);
    if (pxe.force && ((pxe.force & (~PXECHN_FORCE_ALL)) == 0)) {
	if (pxe.force & PXECHN_FORCE_PKT2) {
	    rv = dhcp_pkt2pxe(p[1], pxe.p[1].len, PXENV_PACKET_TYPE_DHCP_ACK);
	}
    }
ret:
    return rv;
}

/* pxe_restart: Restart the PXE environment with a new PXE file
 *	Input:
 *	ifn	Name of file to chainload to in a format PXELINUX understands
 *		This must strictly be TFTP or relative file
 */
int pxe_restart(char *ifn)
{
    int rv = 0;
    struct pxelinux_opt pxe;
    com32sys_t reg;
    t_PXENV_RESTART_TFTP *pxep;	/* PXENV callback Parameter */

    pxe.fn = ifn;
    pxechn_fill_pkt(&pxe, PXENV_PACKET_TYPE_CACHED_REPLY);
    if (pxe.p[5].data)
	pxe.fip = ( (pxe_bootp_t *)(pxe.p[5].data) )->sip;
    else
	pxe.fip = 0;
    rv = pxechn_parse_fn(pxe.fn, &(pxe.fip), pxe.host, &(pxe.fp));
    if ((rv > 2) || (rv < 0)) {
	printf("%s: ERROR: Unparsable filename argument: '%s'\n\n", app_name_str, pxe.fn);
	goto ret;
    }
    printf("  Attempting to boot '%s'...\n\n", pxe.fn);
    memset(&reg, 0, sizeof reg);
    if (sizeof(t_PXENV_TFTP_READ_FILE) <= __com32.cs_bounce_size) {
	pxep = __com32.cs_bounce;
	memset(pxep, 0, sizeof(t_PXENV_RESTART_TFTP));
    } else if (!(pxep = lzalloc(sizeof(t_PXENV_RESTART_TFTP)))){
	dprintf("Unable to lzalloc() for PXE call structure\n");
	goto ret;
    }
    pxep->Status = PXENV_STATUS_SUCCESS;	/* PXENV_STATUS_FAILURE */
    strcpy((char *)pxep->FileName, ifn);
    pxep->BufferSize = 0x8000;
    pxep->Buffer = (void *)0x7c00;
    pxep->ServerIPAddress = pxe.fip;
    dprintf("FN='%s'  %08X %08X %08X %08X\n\n", (char *)pxep->FileName,
	pxep->ServerIPAddress, (unsigned int)pxep,
	pxep->BufferSize, (unsigned int)pxep->Buffer);
    dprintf("PXENV_RESTART_TFTP status %d\n", pxep->Status);
    reg.eax.w[0] = 0x0009;
    reg.ebx.w[0] = PXENV_RESTART_TFTP;
    reg.edi.w[0] = OFFS(pxep);
    reg.es = SEG(pxep);

    __intcall(0x22, &reg, &reg);

    printf("PXENV_RESTART_TFTP returned %d\n", pxep->Status);
    if (pxep != __com32.cs_bounce)
	lfree(pxep);

ret:
    return rv;
}

/* pxechn_gpxe: Use gPXE to chainload a new NBP
 *	Input:
 *	argc	Count of arguments passed
 *	argv	Values of arguments passed
 *	Returns	0 on success (which should never happen)
 *		1 on loadfile() error
 *		-1 on usage error
 */
//FIXME:Implement
int pxechn_gpxe(int argc, char *argv[])
{
    int rv = 0;
    struct pxelinux_opt pxe;

    if (argc) {
	printf("%s\n", argv[0]);
	pxechn_args(argc, argv, &pxe);
    }
    return rv;
}

int main(int argc, char *argv[])
{
    int rv= -1;
    int err;
    const struct syslinux_version *sv;

    /* Initialization */
    err = errno;
    console_ansi_raw();	/* sets errno = 9 (EBADF) */
    /* printf("%d %d\n", err, errno); */
    errno = err;
    sv = syslinux_version();
    if (sv->filesystem != SYSLINUX_FS_PXELINUX) {
	printf("%s: May only run in PXELINUX\n", app_name_str);
	argc = 1;	/* prevents further processing to boot */
    }
    if (argc == 2) {
	if ((strcasecmp(argv[1], "-h") == 0) || ((strcmp(argv[1], "-?") == 0))
		|| (strcasecmp(argv[1], "--help") == 0)) {
	    argc = 1;
	} else {
	    rv = pxechn(argc - 1, &argv[1]);
	}
    } else if (argc >= 3) {
	if ((strcmp(argv[1], "-r") == 0)) {
	    if (argc == 3)
		rv = pxe_restart(argv[2]);
	} else {
	    rv = pxechn(argc - 1, &argv[1]);
	}
    }
    if (rv <= -1 ) {
	usage();
	rv = 1;
    }
    return rv;
}