aboutsummaryrefslogtreecommitdiffstats
path: root/core/pxe.c
blob: 86450d40da256e3a7b3538d330f49f490d82f732 (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
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
#include <stdio.h>
#include <string.h>
#include <core.h>
#include <pxe.h>
#include <sys/cpu.h>

#define MAX_OPEN_LG2       5
#define MAX_OPEN           (1 << MAX_OPEN_LG2)
#define FILENAME_MAX_LG2   7
#define FILENAME_MAX       (1 << FILENAME_MAX_LG2)

#define MAX(a,b)           (a > b ? a : b)

#define GPXE 1
#define USE_PXE_PROVIDED_STACK 0

char *err_nopxe     = "No !PXE or PXENV+ API found; we're dead...\n";
char *err_pxefailed = "PXE API call failed, error ";
char *err_udpinit   = "Failed to initialize UDP stack\n";
char *err_noconfig  = "Unable to locate configuration file\n";
char *err_damage    = "TFTP server sent an incomprehesible reply\n";

char *tftpprefix_msg = "TFTP prefix: ";
char *get_packet_msg = "Getting cached packet ";

uint16_t NextSocket = 49152;

int has_gpxe;
int HaveUUID = 0;
uint8_t UUIDType;
uint8_t uuid_dashes[] = {4, 2, 2, 2, 6, 0};

uint16_t StructPtr[2];

static const uint8_t TimeoutTable[] = {
    2, 2, 3, 3, 4, 5, 6, 7, 9, 10, 12, 15, 18, 21, 26, 31, 37, 44, 53, 64, 77,
    92, 110, 132, 159, 191, 229, 255, 255, 255, 255, 0
};

char *mode = "octet";
char *tsize_str = "tsize";
int tsize_len = 6; /* We should include the final null here */

char *blksize_str = "blksize";
int blksize_len = 8;

char *asciidec = "1408";


/*
 * parse the ip_str and return the ip address with *res.
 * return the the string address after the ip string
 *
 */
char *parse_dotquad(char *ip_str, uint32_t *res)
{
    char *p = ip_str;
    int  i  = 0;
    uint8_t part = 0;
    uint32_t ip  = 0;
    
    for (; i < 4; i++) {
        while (is_digit(*p)) {
            part = part * 10 + *p - '0';
            p++;
        }
        if (i != 3 && *p != '.') 
            return NULL;
        
        ip = (ip << 8) | part;
        part = 0;
        p++;
    }
    p --;
    
    *res = ip;
    return p;    
}


/*********************************************************************
;
; is_url:      Return 1 if and only if the buffer pointed to by
;	       url is a URL (contains ://).  No registers modified.
;
*********************************************************************/
#if GPXE
int is_url(char *url)
{
    
    while (*url) {
        if(! strncmp(url, "://", 3))
            return 1;
          
        url++;
    }    
    return 0;
}
#else
int is_url(char *url)
{
    return 0;
}
#endif /* GPXE */

/*
 ; mangle a filename pointed to by DS:SI into a buffer pointed
 ;	       to by ES:DI; ends on encountering any whitespace.
 ;	       DI is preserved.
 ;
 ;	       This verifies that a filename is < FILENAME_MAX characters
 ;	       and doesn't contain whitespace, and zero-pads the output buffer,
 ;	       so "repe cmpsb" can do a compare.
 ;
 ;	       The first four bytes of the manged name is the IP address of
 ;	       the download host, 0 for no host, or -1 for a gPXE URL.
 ;
 ;              No segment assumptions permitted.
 ;
*********************************************************************/
void mangle_name(com32sys_t *regs)
{
    char *dst = (char *)MK_PTR(regs->es, regs->edi.w[0]); 
    char *src = (char *)MK_PTR(regs->ds, regs->esi.w[0]);

    char *p = src;
    uint32_t ip;
    int i = 0;
   
#if GPXE
    if (is_url(MK_PTR(regs->ds, regs->esi.w[0])))
        goto prefix_done;
#endif

    ip = ServerIP;
    if (*p == 0)
        goto noip;
    if (! strncmp(p, "::", 2))
        goto gotprefix;
    else {
        while (*p && strncmp(p, "::", 2))
            p ++;
        if (! *p)
            goto noip;
        /*
         * we have a :: prefix of ip sort, it could be either a DNS
         * name or dot-quad IP address. Try the dot-quad first.
         */
        p = src;
        if ((p = parse_dotquad(p, &ip)) && !strncmp(p, "::", 2))
            goto gotprefix;
        else {
            extern void dns_resolv(void);
            call16(dns_resolv, regs, regs);
            p = (char *)MK_PTR(regs->ds, regs->esi.w[0]);
            ip = regs->eax.l;
            if (! strncmp(p, "::", 2))
                if (ip)
                    goto gotprefix;
        }
    }
 noip:
    p = src;
    ip = 0;
    goto prefix_done;

 gotprefix:
    p += 2;      /* skip double colon */
  
 prefix_done:
    *(uint32_t *)dst = ip;  
    dst += 4;
    i = FILENAME_MAX - 5;

    do {
        if (*p <= ' ')
            break;
        *dst++ = *p++;
    }while (i--);

    i ++;
    while (i) {
        *dst++ = 0;
        i --;
    }    
    
#if 0
    printf("the name before mangling: ");
    dump16(src);
    printf("the name after mangling:  ");
    dump16((char *)MK_PTR(regs->ds, regs->edi.w[0]));
#endif
}



/**
 * Take a nubmer of bytes in memory and convert to lower-case hxeadecimal 
 *
 * Input:
 *       DS:SI = input bytes
 *       ES:DI = output buffer
 *       CX    = number of bytes
 * Output:
 *       DS:SI = first byte after
 *       ES:DI = first byte after
 *       cx    = 0
 *
 * Trashes AX, DX
 */
void lchexbytes(char *dst, const void *src, int count)
{
    uint8_t half;
    uint8_t c;
    const uint8_t *s = src;
    
    for(; count > 0; count--) {
        c = *s++;
        half   = ((c >> 4) & 0x0f) + '0';
        *dst++ = half > '9' ? (half + 'a' - '9' - 1) : half;
        
        half   = (c & 0x0f) + '0';
        *dst++ = half > '9' ? (half + 'a' - '9' - 1) : half;
    }
}

/**
 * just like the lchexbytes, except to upper-case
 *
 */
void uchexbytes(char *dst, const void *src, int count)
{
    uint8_t half;
    uint8_t c;
    const uint8_t *s = src;
        
    for(; count > 0; count--) {
        c = *s++;
        half   = ((c >> 4) & 0x0f) + '0';
        *dst++ = half > '9' ? (half + 'A' - '9' - 1) : half;
        
        half   = (c & 0x0f) + '0';
        *dst++ = half > '9' ? (half + 'A' - '9' - 1) : half;
    }
}


/**
 * Validity check on possible !PXE structure in ES:BX
 *
 * Return ZF = 1 on success
 *
 * Clobbers CX and SI
 *
 */
int is_pxe(char *buf)
{
    int i = buf[4];
    uint8_t sum = 0;

    if (memcmp(buf, "!PXE", 4) || i < 0x58)
        return 0;

    while (i--)
        sum += *buf++;

    if (sum == 0)
        return 1;
    else
        return 0;
}

/**
 * Just like is_pxe, it checks PXENV+ structure
 *
 */
int is_pxenv(char *buf)
{
    int i = buf[8];
    uint8_t sum = 0;
    
    if (memcmp(buf, "PXENV+", 6) || i < 0x28)
        return 0;

    while (i--)
        sum += *buf++;

    if (sum == 0)
        return 1;
    else
        return 0;
}
        


/*********************************************************************
;
; memory_scan_for_pxe_struct:
; memory_scan_for_pxenv_struct:
;
;	If none of the standard methods find the !PXE/PXENV+ structure,
;	look for it by scanning memory.
;
;	On exit, if found:
;		ZF = 1, ES:BX -> !PXE structure
;	Otherwise:
;		ZF = 0
;
;	Assumes DS == CS
;	Clobbers AX, BX, CX, DX, SI, ES
;
 ********************************************************************/

inline int memory_scan(uint16_t seg, int (*func)(char *))
{
    while (seg < 0xA000) {
        if (func(MK_PTR(seg, 0)))
            return 1;       /* found it */
        seg++;
    }
    return 0;
}
    
int memory_scan_for_pxe_struct()
{
    extern uint16_t BIOS_fbm;  /* Starting segment */
    uint16_t seg = BIOS_fbm << (10 - 4);

    return memory_scan(seg, is_pxe);
}
    
int memory_scan_for_pxenv_struct()
{
    uint16_t seg = 0x1000;
    
    return memory_scan(seg, is_pxenv);
}


/*********************************************************************
;
; gendotquad
;
; Take an IP address (in network byte order) in EAX and
; output a dotted quad string to ES:DI.
; DI points to terminal null at end of string on exit.
;
 *********************************************************************/
/**
 * @param: dst, to store the converted ip string 
 * @param: ip, the ip address that needed convert.
 * 
 * @return: the ip string length
 */
int gendotquad(char *dst, uint32_t ip)
{
    int part;
    int i = 0, j;
    char temp[4];
    char *p = dst;
    
    for (; i < 4; i++) {
        j = 0;
        part = ip & 0xff;
        do {
            temp[j++] = (part % 10) + '0';
        }while(part /= 10);
        for (; j > 0; j--)
            *p++ = temp[j-1];
        *p++ = '.';
        
        ip >>= 8;
    }
    /* drop the last dot '.' and zero-terminate string*/
    *(--p) = 0;
    
    return p - dst;
}

 /**
  * try to load a config file, if found, return 1, or return 0
  *
  */   
int try_load(com32sys_t *regs)
{
    extern void open(void);
    extern char KernelName[];
    char *config_name = (char *)MK_PTR(regs->ds, regs->edi.w[0]);

    printf("Trying to load: %-50s ", config_name);
    
    regs->edi.w[0] = OFFS_WRT(KernelName, 0);
    regs->esi.w[0] = OFFS_WRT(config_name, 0);
    mangle_name(regs);
    regs->edi.w[0] = OFFS_WRT(KernelName, 0);
    call16(open, regs, regs);
    if (regs->eflags.l & EFLAGS_ZF) {
        printf("   [FAILED]\n");
        return 0;
    } else {
        printf("   [  OK  ]\n");
        return 1;
    }
}


 /**
  * load configuration file
  *
  */
void pxe_load_config(com32sys_t *regs)
{
    extern void no_config(void);
    char *cfgprefix = "pxelinux.cfg/";
    char *default_str = "default";
    char *config_file;		/* Pointer to the variable suffix */
    char *p;
   
    uint8_t *uuid_ptr;

    int tries = 8;
    char *last;
    
    if (DHCPMagic & 0x02) {
        /* We got a DHCP option, try it first */
        if (try_load(regs))
            return;
    }
    
    memcpy(ConfigName, cfgprefix, strlen(cfgprefix));
    config_file = ConfigName + strlen(cfgprefix);
    /*
     * Have to guess config file name ...
     */
    
    /* Try loading by UUID */
    if (HaveUUID) {
        uuid_ptr  = uuid_dashes;
	p = config_file;
        while (*uuid_ptr) {
            int len = *uuid_ptr;
            char *src = UUID;
            
            lchexbytes(p, src, len);
            p += len * 2;
            src += len;
            uuid_ptr++;
            *p++ = '-';
        }
        /* Remove last dash and zero-terminate */
	*--p = '\0';
        regs->edi.w[0] = OFFS_WRT(ConfigName, 0);
        if (try_load(regs))
            return;
    }

    /* Try loading by MAC address */
    strcpy(config_file, MACStr);
    regs->edi.w[0] = OFFS_WRT(ConfigName, 0);
    if (try_load(regs))
        return;
    
#if 0
    printf("MY IP: %p(%X)\n", MyIP, *(uint32_t *)MyIP);
 #endif
    
    /* Nope, try hexadecimal IP prefixes... */
    uchexbytes(config_file, (uint8_t *)&MyIP, 4);     /* Convet to hex string */
    last = &config_file[8];
    while (tries) {
        *last = '\0';        /* Zero-terminate string */
        regs->edi.w[0] = OFFS_WRT(ConfigName, 0);
        if (try_load(regs))
            return;
        last--;           /* Drop one character */
        tries--;
    };
    
    /* Final attempt: "default" string */
    strcpy(config_file, default_str);
    regs->edi.w[0] = OFFS_WRT(ConfigName, 0);
    if (try_load(regs))
        return;

    /* call16(no_config, NULL, NULL); */
}
    
    
/******************************************************************           
; Allocate a local UDP port structure
;
;		If successful:
;		  ZF clear
;		  BX     = socket pointer
;               If unsuccessful:
;                 ZF set
;    
******************************************************************/
struct open_file_t* allocate_socket()
{
    extern uint16_t NextSocket;
    uint16_t i = MAX_OPEN;
    struct open_file_t *socket = (struct open_file_t *)&Files;
    
    for (; i > 0; i--) {
        if (*(uint16_t*)socket == 0)
            break;
        socket ++;
    }
    
    /* Not found */
    if (i == 0) 
        return NULL;
    
    /*
     * Allocate a socket number. Socket numbers are made guaranteed unique 
     * by including the socket slot number(inverted, because we use the loop
     * counter cx; add a counter value to keep the numbers from being likely
     * to get immediately reused.
     *
     * The NextSocket variable also contains the top two bits set. This 
     * generates a value in the range 49152 to 57343.
     *
     */
    i--;
    NextSocket = ((NextSocket + 1) & ((1  << (13-MAX_OPEN_LG2))-1)) | 0xc000;
    i <<= 13-MAX_OPEN_LG2;
    i += NextSocket;
    i = ntohs(i)       ;    /* convet to network byte order, little to big */
    *(uint16_t*)socket = i; /* socket in use */
    
    return socket;
}

/*
 * free socket, socket in SI; return SI = 0, ZF = 1 for convenience
 */
void free_socket(struct open_file_t *file)
{
    /* tftp_pktbuf is not cleared */
    memset(file, 0, sizeof(struct open_file_t) - 2);
}



/************
;
; Tests an IP address in EAX for validity; return with ZF=1 for bad.
; We used to refuse class E, but class E addresses are likely to become
; assignable unicast addresses in the near future.
;
*************/
int ip_ok(uint32_t ip)
{
    if (ip == -1)          /* Refuse the all-one address */
        goto bad;
    if ((ip & 0xff) == 0)  /* Refuse network zero */
        goto bad;
    if ((ip & 0xff) == 0xff) /* Refuse loopback */
        goto bad;
    if ((ip & 0xf0) == 0xe0) /* Refuse class D */
        goto bad;
    
    return 1;

 bad:
    return 0;
}

int pxe_call(int opcode, void *data)
{
    extern void pxenv(void);
    com32sys_t in_regs, out_regs;
    
#if 0
    printf("pxe_call op %04x data %p\n", opcode, data);
#endif

    memset(&in_regs, 0, sizeof in_regs);
    
    in_regs.ebx.w[0] = opcode;
    in_regs.es       = SEG(data);
    in_regs.edi.w[0] = OFFS(data);
    call16(pxenv, &in_regs, &out_regs);
    
    return out_regs.eflags.l & EFLAGS_CF;  /* CF SET for fail */
}

/**
 *
 * Send ACK packet. This is a common operation and so is worth canning.
 *
 * @param: file,    TFTP block pointer
 * @param: ack_num, Packet # to ack (network byte order)
 * 
 */
void ack_packet(struct open_file_t *file, uint16_t ack_num)
{
    int err;
    static __lowmem struct pxe_udp_write_pkt uw_pkt;
 
    /* Packet number to ack */
    ack_packet_buf[1]  = ack_num;
    uw_pkt.lport      = file->tftp_localport;
    uw_pkt.rport      = file->tftp_remoteport;
    uw_pkt.sip        = file->tftp_remoteip;
    uw_pkt.gip        = ((uw_pkt.sip ^ MyIP) & Netmask) ? Gateway : 0;
    uw_pkt.buffer[0]  = OFFS_WRT(ack_packet_buf, 0);
    uw_pkt.buffer[1]  = 0;    /* seems SEG and OFFS stuff doesn't work here */
    uw_pkt.buffersize = 4;

    err = pxe_call(PXENV_UDP_WRITE, &uw_pkt);
#if 0
    printf("sent %s\n", err ? "FAILED" : "OK");
#endif
}


/**
 * Get a DHCP packet from the PXE stack into the trackbuf
 *
 * @param:  type,  packet type
 * @return: buffer size
 * 
 */
int pxe_get_cached_info(int type)
{
    int err;
    static __lowmem struct pxe_bootp_query_pkt bq_pkt;
    printf(" %02x", type);
    
    bq_pkt.status     = 0;
    bq_pkt.packettype = type;
    bq_pkt.buffersize = 8192;
    bq_pkt.buffer[0]  = OFFS_WRT(trackbuf, 0);
    bq_pkt.buffer[1]  = 0;
    
    err = pxe_call(PXENV_GET_CACHED_INFO, &bq_pkt);
    if (err) {
        printf("%s %04x\n", err_pxefailed, err);
        call16(kaboom, NULL, NULL);
    }
    
    return bq_pkt.buffersize;
}

/*
 * Initialize UDP stack 
 *
 */
void udp_init(void)
{
    int err;
    static __lowmem struct pxe_udp_open_pkt uo_pkt;
    uo_pkt.sip = MyIP;
    err = pxe_call(PXENV_UDP_OPEN, &uo_pkt);
    if (err || uo_pkt.status) {
        printf("%s", err_udpinit);
        printf("%d\n", uo_pkt.status);
        call16(kaboom, NULL, NULL);
    }
}
    
    
/*
 * Store standard filename prefix
 */
void get_prefix(void)
{
    int len;
    char *p;
    char c;
    
    if (DHCPMagic & 0x04)         /* Did we get a path prefix option */
        goto got_prefix;
    
    strcpy(PathPrefix, BootFile);
    len = strlen(PathPrefix);
    p = &PathPrefix[len - 1]; 

    while (len--) {
        c = *p--;
        c |= 0x20;
        
        c = (c >= '0' && c <= '9') || 
            (c >= 'a' && c <= 'z') || 
            (c == '.' || c == '-');
        if (!c)
            break;
    };
    
    if (len < 0)
        p --;

    *(p + 2) = 0;                /* Zero-terminate after delimiter */
    
 got_prefix:
    printf("%s%s\n", tftpprefix_msg, PathPrefix);
    strcpy(CurrentDirName, PathPrefix);
}





#if GPXE
/*
 * Return CF=0 if and only if the buffer pointed to by DS:SI is a URL 
 * (contains ://) *and* the gPXE extensions API is available. No 
 * registers modified.
 */
int is_gpxe(char *url)
{
    int err;
    static __lowmem struct gpxe_file_api_check ac;
    char *gpxe_warning_msg = "URL syntax, but gPXE extensions not detected, tring plain TFTP...\n";
    
    if (! is_url(url))
        return 0;
    
    ac.size  = 20;
    ac.magic = 0x91d447b2;
    /* If has_gpxe is greater than one, means the gpxe status is unknow */
    while (has_gpxe > 1)  {
        err = pxe_call(PXENV_FILE_API_CHECK, &ac);
        if (err || ac.magic != 0xe9c17b20) 
            printf("%s\n", gpxe_warning_msg);
        else             
            has_gpxe = (~ac.provider & 0xffff) & 0x4b ? 0 : 1;
        
        if (!has_gpxe)
            printf("%s\n", gpxe_warning_msg);
    }

    if (has_gpxe == 1) 
        return 1;
    else
        return 0;   
}

/**
 * Get a fresh packet from a gPXE socket
 * @param: file -> socket structure
 *
 */
void get_packet_gpxe(struct open_file_t *file)
{
    static __lowmem struct gpxe_file_read fr;
    int err;
 
    while (1) {
        fr.filehandle = file->tftp_remoteport;
        fr.buffer[0]  = file->tftp_pktbuf;
        fr.buffer[1]  = PKTBUF_SEG;
        fr.buffersize = PKTBUF_SIZE;
        err = pxe_call(PXENV_FILE_READ, &fr);
        if (!err)  /* successed */
            break;

        if (fr.status == PXENV_STATUS_TFTP_OPEN)
            continue;
        call16(kaboom, NULL, NULL);
    }

    file->tftp_bytesleft = fr.buffersize;
    file->tftp_filepos  += fr.buffersize;
    
    if (file->tftp_bytesleft == 0)
        file->tftp_filesize = file->tftp_filepos;
    
    /* if we're done here, close the file */
    if (file->tftp_filesize > file->tftp_filepos) 
        return;

    /* Got EOF, close it */
    file->tftp_goteof = 1;
    pxe_call(PXENV_FILE_CLOSE, &fr);
}
#endif /* GPXE */
        
/*
 *
 ;
 ; Get a fresh packet if the buffer is drained, and we haven't hit
 ; EOF yet.  The buffer should be filled immediately after draining!
 ;
 ; expects fs -> pktbuf_seg and ds:si -> socket structure
 ;
*/
void fill_buffer(struct open_file_t *file)
{
    int err;
    int last_pkt;
    const uint8_t *timeout_ptr = TimeoutTable;
    uint8_t timeout;
    uint16_t buffersize;
    uint16_t old_time;
    void *data = NULL;
    static __lowmem struct pxe_udp_read_pkt pkt;
        
    if (file->tftp_bytesleft || file->tftp_goteof)
        return;

#if GPXE
    if (file->tftp_localport == 0xffff) {
        get_packet_gpxe(file);
        return;
    }
#endif


    /*
     * Start by ACKing the previous packet; this should cause
     * the next packet to be sent.
     */
 ack_again:   
    ack_packet(file, file->tftp_lastpkt);
    
    timeout_ptr = TimeoutTable;    
    timeout = *timeout_ptr++;
    old_time = BIOS_timer;
    while (timeout) {
        pkt.buffer[0]  = file->tftp_pktbuf;
        pkt.buffer[1]  = PKTBUF_SEG;
        pkt.buffersize = PKTBUF_SIZE;
        pkt.sip        = file->tftp_remoteip;
        pkt.dip        = MyIP;
        pkt.rport      = file->tftp_remoteport;
        pkt.lport      = file->tftp_localport;
        err = pxe_call(PXENV_UDP_READ, &pkt);
        if (err) {
            if (BIOS_timer == old_time) {
		printf(".");
                continue;
	    }
	    printf("+");
            
            timeout--;		/* decrease one timer tick */
            if (!timeout) {
                timeout = *timeout_ptr++;
		if (!timeout)
		    break;
	    }
            continue;
        }
    
        if (pkt.buffersize < 4)  /* Bad size for a DATA packet */
            continue;    

        data = MK_PTR(PKTBUF_SEG, file->tftp_pktbuf);
        if (*(uint16_t *)data != TFTP_DATA)    /* Not a data packet */
            continue;
                
        /* If goes here, recevie OK, break */
        break;
    }

    /* time runs out */
    if (timeout == 0)
        call16(kaboom, NULL, NULL);
    
    last_pkt = file->tftp_lastpkt;
    last_pkt = ntohs(last_pkt);       /* Host byte order */
    last_pkt++;
    last_pkt = htons(last_pkt);       /* Network byte order */
    if (*(uint16_t *)(data + 2) != last_pkt) {
        /*
         * Wrong packet, ACK the packet and try again.
         * This is presumably because the ACK got lost,
         * so the server just resent the previous packet.
         */
#if 0
	printf("Wrong packet, wanted %04x, got %04x\n", htons(last_pkt), htons(*(uint16_t *)(data+2)));
#endif
        goto ack_again;
    }
    
    /* It's the packet we want.  We're also EOF if the size < blocksize */
    file->tftp_lastpkt = last_pkt;    /* Update last packet number */
    buffersize = pkt.buffersize - 4; /* Skip TFTP header */
    file->tftp_dataptr = file->tftp_pktbuf + 4;
    file->tftp_filepos += buffersize;
    file->tftp_bytesleft = buffersize;
    if (buffersize < file->tftp_blksize) {
        /* it's the last block, ACK packet immediately */
        ack_packet(file, *(uint16_t *)(data + 2));

        /* Make sure we know we are at end of file */
        file->tftp_filesize = file->tftp_filepos;
        file->tftp_goteof   = 1;
    }
}



/*
 *
 ;
 ; getfssec: Get multiple clusters from a file, given the starting cluster.
 ;
 ;	In this case, get multiple blocks from a specific TCP connection.
 ;
 ;  On entry:
 ;	ES:BX	-> Buffer
 ;	SI	-> TFTP socket pointer
 ;	CX	-> 512-byte block count; 0FFFFh = until end of file
 ;  On exit:
 ;	SI	-> TFTP socket pointer (or 0 on EOF)
 ;	CF = 1	-> Hit EOF
 ;	ECX	-> number of bytes actually read
 ;
*/
void getfssec(com32sys_t *regs)
{
    char *buf = MK_PTR(regs->es, regs->ebx.w[0]);
    struct open_file_t *file = (struct open_file_t *)MK_PTR(0, regs->esi.w[0]);
    int count = regs->ecx.w[0];
    int chunk;
    int bytes_read = 0;

    sti();
    
    regs->fs = PKTBUF_SEG;
        
    count <<= TFTP_BLOCKSIZE_LG2;
    while (count) {
        fill_buffer(file);         /* If we have no 'fresh' buffer, get it */              
        if (! file->tftp_bytesleft)
            break;
        
        chunk = count;
        if (chunk > file->tftp_bytesleft)
            chunk = file->tftp_bytesleft;
        file->tftp_bytesleft -= chunk;
        memcpy(buf, MK_PTR(regs->fs, file->tftp_dataptr), chunk);
	file->tftp_dataptr += chunk;
        buf += chunk;
        bytes_read += chunk;
        count -= chunk;
    }

    regs->ecx.l = bytes_read; /* number of bytes actually read */ 

    if (file->tftp_bytesleft || (file->tftp_filepos < file->tftp_filesize)) {
	fill_buffer(file);
        regs->eflags.l &= ~EFLAGS_CF;
        return;
    }
    
    if (file->tftp_goteof) {
        /* 
         * The socket is closed and the buffer dranined
         * close socket structure and re-init for next user
         */
        free_socket(file);
        regs->esi.w[0] = 0;
        regs->eflags.l |= EFLAGS_CF;     /* Hit EOF */
        return;
    }
    
    /* hpa is 99% sure this can't happen, but ... */
    fill_buffer(file);   /* Receive/ACK the EOF packet */    
 }

 
/*
 * Generate the botif string, and the hardware-based config string 
 */
void make_bootif_string(void)
{
    char *bootif_str = "BOOTIF=";
    uint8_t *src = &MACType;      /* MACType just followed by MAC */
    char *dst;
    int i = MACLen + 1;         /* MACType included */
    
    strcpy(BOOTIFStr, bootif_str);
    dst = strchr(BOOTIFStr, '\0');
    for (; i > 0; i--) {
        lchexbytes(dst, src, 1);
        dst += 2;
        src += 1;
        *dst++ = '-';
    }
    *(dst - 1) = 0;   /* Drop the last '-' and null-terminate string */

#if 0
    printf("%s\n", BOOTIFStr);
#endif
}
/*
  ;
  ; genipopt
  ;
  ; Generate an ip=<client-ip>:<boot-server-ip>:<gw-ip>:<netmask>
  ; option into IPOption based on a DHCP packet in trackbuf.
  ; Assumes CS == DS == ES.
  ;
*/
void genipopt(void)
{
    char *p = IPOption;
    int ip_len;
    
    strcpy(p, "ip=");
    p += 3;
    
    ip_len = gendotquad(p, MyIP);
    p += ip_len;
    *p++ = ':';

    ip_len = gendotquad(p, ServerIP);
    p += ip_len;
    *p++ = ':';

    ip_len = gendotquad(p, Gateway);
    p += ip_len;
    *p++ = ':';
    
    ip_len = gendotquad(p, Netmask);
}
    

/* Generate ip= option and print the ip adress */
void ip_init(void)
{
    int ip = MyIP;
    char *myipaddr_msg = "My IP address seems to be ";
    
    genipopt();

    gendotquad(DotQuadBuf, ip);
    
    ip = ntohl(ip);
    printf("%s %08X %s\n", myipaddr_msg, ip, DotQuadBuf);
    
    printf("%s\n", IPOption);
}


/*
 * Find the !PXE structure; we search for the following, in order:
 *
 * a. !PXE structure as SS:[SP + 4]
 * b. PXENV+ structure at [ES:BX]
 * c. INT 1Ah AX=0x5650 -> PXENV+
 * d. Search memory for !PXE
 * e. Search memory for PXENV+
 *
 * If we find a PXENV+ structure, we try to find a !PXE structure from 
 * if if the API version is 2.1 or later 
 *
 */
void pxe_init(com32sys_t *regs)
{
    char plan = 'A';
    uint16_t seg, off;
    uint16_t code_seg, code_len;
    uint16_t data_seg, data_len;
    char *base = GET_PTR(InitStack);

    /* Assume API version 2.1 */
    APIVer = 0x201;
    
    /* Plan A: !PXE structure as SS:[SP + 4] */
    off = *(uint16_t *)(base + 48);
    seg = *(uint16_t *)(base + 50);
    if (is_pxe(MK_PTR(seg, off))) 
        goto have_pxe;

    /* Plan B: PXENV+ structure at [ES:BX] */
    plan++;
    off = *(uint16_t *)(base + 24);  /* Original BX */
    seg = *(uint16_t *)(base + 4);   /* Original ES */
    if (is_pxenv(MK_PTR(seg, off)))
        goto have_pxenv;

    /* 
     * Plan C: PXENV+ structure via INT 1Ah AX=5650h 
     * 
     * for now, we just skip it since it must be run in Real mode 
     */
    extern void plan_c(void);
    plan++;
    goto plan_D;               
    call16(plan_c, regs, regs);
    if (((regs->eflags.l & EFLAGS_CF) == 0) && (regs->eax.w[0] == 0x564e)) {
        seg = regs->es;
        off = regs->ebx.w[0];
        if (is_pxenv(MK_PTR(seg, off)))
            goto have_pxenv;
    }

 plan_D:
    /* Plan D: !PXE memory scan */
    plan++;
    if (memory_scan_for_pxe_struct())
        goto have_pxe;
    
    /* Plan E: PXENV+ memory scan */
    plan++;
    if (memory_scan_for_pxenv_struct())
        goto have_pxenv;

    /* Found nothing at all !! */
    printf("%s\n", err_nopxe);
    call16(kaboom, NULL, NULL);
    
 have_pxenv:
    StructPtr[0] = off;
    StructPtr[1] = seg;
    base = MK_PTR(seg, off);
    APIVer = *(uint16_t *)(base + 6);
    printf("Found PXENV+ structure\nPXE API version is %04x\n", APIVer);

    /* if the API version number is 0x0201 or higher, use the !PXE structure */
    if (APIVer >= 0x201) {
        if (*(char *)(base + 8) < 0x2c) {          /* Length of PXENV+ structure in bytes */
            if (memory_scan_for_pxe_struct())
                goto have_pxe;
        }
    
        off = *(uint16_t *)(base + 0x28);
        seg = *(uint16_t *)(base + 0x2a);
        if (is_pxe(MK_PTR(seg, off)))
            goto have_pxe;    
        /*
         * Nope, !PXE structuremissing despite API 2.1+, or at least
         * the pointer is missing. Do a last-ditch attempt to find it
         */
        if (memory_scan_for_pxe_struct())
            goto have_pxe;
    }
    
    /* Otherwise, no dice, use PXENV+ structure */
    data_len = *(uint16_t *)(base + 0x22);  /* UNDI data len */
    data_seg = *(uint16_t *)(base + 0x20);  /* UNDI data seg */
    code_len = *(uint16_t *)(base + 0x26);  /* UNDI code len */
    code_seg = *(uint16_t *)(base + 0x24);  /* UNDI code seg */
    PXEEntry = *(far_ptr_t *)(base + 0x0a);  /* PXENV+ entry point */
    printf("PXENV+ entry point found (we hope) at ");
    goto have_entrypoint;

 have_pxe:
    StructPtr[0] = off;
    StructPtr[1] = seg;
    base = MK_PTR(seg, off);
    
    data_len = *(uint16_t *)(base + 0x2e);  /* UNDI data len */
    data_seg = *(uint16_t *)(base + 0x28);  /* UNDI data seg */
    code_len = *(uint16_t *)(base + 0x36);  /* UNDI code len */
    code_seg = *(uint16_t *)(base + 0x30);  /* UNDI code seg */
    PXEEntry = *(far_ptr_t *)(base + 0x10);  /* !PXE entry point */
    printf("!PXE entry point found (we hope) at ");

 have_entrypoint:
    printf("%04X:%04X via plan %c\n", PXEEntry.seg, PXEEntry.offs, plan);
    printf("UNDI code segment at %04X len %04X\n", code_seg, code_len);
    code_seg = code_seg + ((code_len + 15) >> 4);
    
    printf("UNDI data segment at %04X len %04X\n", data_seg, data_len);
    data_seg = data_seg + ((data_len + 15) >> 4);
    
    
    RealBaseMem = MAX(code_seg,data_seg) >> 6; /* Convert to kilobytes */
    regs->es = regs->ds;                       /* Restore the es segment */
}                                  

/*
 * Fill the packet tail with the tftp informations then retures the lenght
 */
int fill_tail(char *dst)
{
    char *p = dst;
    strcpy(p, mode);
    p += strlen(mode) + 1;
    
    strcpy(p, tsize_str);
    p += strlen(tsize_str) + 1;
    
    strcpy(p, "0");
    p += 2;
    
    strcpy(p, blksize_str);
    p += strlen(blksize_str) + 1;   

    strcpy(p, asciidec);
    p += strlen(asciidec) + 1;

    return p - dst;
}


struct tftp_options {
    char *str_ptr;        /* string pointer */
    int   str_len;        /* string lenght */
    int   offset;         /* offset into socket structre */
};
struct tftp_options tftp_options[2];

void init_options()
{
    tftp_options[0].str_ptr = tsize_str;
    tftp_options[0].str_len = tsize_len;
    tftp_options[0].offset  = (int)&((struct open_file_t *)0)->tftp_filesize;
    
    tftp_options[1].str_ptr = blksize_str;
    tftp_options[1].str_len = blksize_len;
    tftp_options[1].offset  = (int)&((struct open_file_t *)0)->tftp_blksize;
}

/*
 *
 ;
 ; searchdir:
 ;
 ;	Open a TFTP connection to the server
 ;
 ;	     On entry:
 ;		DS:DI	= mangled filename
 ;	     If successful:
 ;		ZF clear
 ;		SI	= socket pointer
 ;		EAX	= file length in bytes, or -1 if unknown
 ;	     If unsuccessful
 ;		ZF set
 ;
*/
void searchdir_c(com32sys_t *regs)
{
    char *filename = MK_PTR(regs->ds, regs->edi.w[0]);
    char *buf = packet_buf;
    char *p = filename;
    char *options;
    char *src, *dst;
    char *data;
    struct open_file_t *file;
    static __lowmem struct pxe_udp_write_pkt uw_pkt;
    static __lowmem struct pxe_udp_read_pkt  ur_pkt;
    static __lowmem struct gpxe_file_open fo;
    static __lowmem struct gpxe_get_file_size gs;
    struct tftp_options *tftp_opt = tftp_options;
    int i = 0;
    int tftp_opts = sizeof tftp_options / sizeof tftp_options[0];
    int err;
    int buffersize;
    const uint8_t  *timeout_ptr;
    uint8_t  timeout;
    uint16_t oldtime;
    uint16_t tid;
    uint16_t opcode;
    uint16_t blk_num;
    uint32_t ip;
    uint32_t filesize;
    uint32_t *data_ptr;
    
    init_options();
    file = allocate_socket();
    if (!file) {
        regs->eflags.l |= EFLAGS_ZF;
        return;
    }
    
    timeout_ptr = TimeoutTable;   /* Reset timeout */

 sendreq:
    uw_pkt.buffer[0] = OFFS_WRT(buf, 0);
    uw_pkt.buffer[1] = 0;
    *(uint16_t *)buf = TFTP_RRQ;  /* TFTP opcode */
    buf += 2;
    
    ip = *(uint32_t *)p;      /* ip <- server override (if any) */
    p += 4;
    if (ip == 0) {
        /* Have prefix */
        strcpy(buf, PathPrefix);
        buf += strlen(PathPrefix);
        ip = ServerIP;            /* Get the default server */
    }

    strcpy(buf, p);                /* Copy the filename */
    buf += strlen(p) + 1;          /* advance the pointer, null char included */
    
#if GPXE
    if (is_gpxe(packet_buf + 2)) {
        fo.status = PXENV_STATUS_BAD_FUNC;
        fo.filename[0] = OFFS_WRT(packet_buf + 2, 0);
        fo.filename[1] = regs->ds;
        err = pxe_call(PXENV_FILE_OPEN, &fo);
        if (err) {
            free_socket(file);
            regs->esi.w[0] = 0;
            regs->eflags.l |= EFLAGS_ZF;
            return;
        }            
        
        file->tftp_localport = -1;
        file->tftp_remoteport = fo.filehandle;
        gs.filehandle = fo.filehandle;
        
#if 0
        err = pxe_call(PXENV_GET_FILE_SIZE, &gs);
        if (!err)
            filesize = gs.filesize;
        else
#endif
            filesize = -1;
        file->tftp_filesize = -1;
        goto got_file;    
    }
#endif /* GPXE */
    
    file->tftp_remoteip = ip;
    tid = file->tftp_localport;   /* TID(local port No) */
    uw_pkt.sip = ip;
    uw_pkt.gip = ((uw_pkt.sip ^ MyIP) & Netmask) ? Gateway : 0;
    uw_pkt.lport = tid;
    uw_pkt.rport = ServerPort;
    buf += fill_tail(buf);
    uw_pkt.buffersize = buf - packet_buf;
    err = pxe_call(PXENV_UDP_WRITE, &uw_pkt);
    if (err || uw_pkt.status != 0)
        goto failure;            /* In fact, the 'failure' target will not do a failure thing; 
                                    it will move on to the next timeout, then tries again until
                                    _real_ time out */
    
    /*
     * Danger, Will Robinson! We need to support tiemout
     * and retry lest we just lost a packet ...
     */
    
    /* Packet transmitted OK, now we need to receive */
    timeout = *timeout_ptr++;
    oldtime = BIOS_timer;
    while (timeout) {
        buf = packet_buf;
        ur_pkt.buffer[0] = OFFS_WRT(buf, 0);
        ur_pkt.buffer[1] = regs->ds;
        ur_pkt.buffersize = 2048;
        ur_pkt.dip = MyIP;
        ur_pkt.lport = tid;
        err = pxe_call(PXENV_UDP_READ, &ur_pkt);
        if (err) {
            if (oldtime == BIOS_timer)
                continue;
            timeout --;  /* Decrease one timer tick */
            if (!timeout) 
                goto failure;
        }

        /* Make sure the packet actually came from the server */
        if (ur_pkt.sip == file->tftp_remoteip)
            break;
    }
          
    /* Got packet; reset timeout */
    timeout_ptr = TimeoutTable;
    file->tftp_remoteport = ur_pkt.rport;
    
    /* filesize <- -1 == unknow */
    file->tftp_filesize = -1;
    /* Default blksize unless blksize option negotiated */
    file->tftp_blksize = TFTP_BLOCKSIZE;
    buffersize = ur_pkt.buffersize - 2;  /* bytes after opcode */
    if (buffersize < 0)
        goto failure;                     /* Garbled reply */
    
    /*
     * Get the opcode type, and parse it 
     */
    opcode = *(uint16_t *)packet_buf;
    if (opcode == TFTP_ERROR)
        goto error;                     /* ERROR reply; don't try again */
    else if (opcode == TFTP_DATA) {
        /*
         * If the server doesn't support any options, we'll get a
         * DATA reply instead of OACK. Stash the data in the file
         * buffer and go with the default value for all options...
         *
         * We got a DATA packet, meaning no options are
         * suported. Save the data away and consider the 
         * length undefined, *unless* this is the only 
         * data packet... 
         */
        buffersize -= 2;
        if (buffersize < 0)
            goto failure;
        data = packet_buf + 2;
        blk_num = *(uint16_t *)data;
        data += 2;
        if (blk_num != htons(1))
            goto failure;
        file->tftp_lastpkt = blk_num;
        if (buffersize > TFTP_BLOCKSIZE)
            goto err_reply;  /* Corrupt */
        else if (buffersize < TFTP_BLOCKSIZE) {
            /* 
             * This is the final EOF packet, already...
             * We know the filesize, but we also want to 
             * ack the packet and set the EOF flag.
             */
            file->tftp_filesize = buffersize;
            file->tftp_goteof = 1;
            ack_packet(file, blk_num);
        }

        file->tftp_bytesleft = buffersize;
        file->tftp_dataptr = file->tftp_pktbuf;
        memcpy(MK_PTR(PKTBUF_SEG, file->tftp_pktbuf), data, buffersize);        
        goto done_pkt;   
        
    } else if (opcode == TFTP_OACK) {
        /* 
         * Now we need to parse the OACK packet to get the transfer
         * and packet sizes.
         */
        if (!buffersize)
            goto done_pkt;       /* No options acked */
        
        /*
         * If we find an option which starts with a NUL byte,
         * (a null option), we're either seeing garbage that some
         * TFTP servers add to the end of the packet, or we have
         * no clue how to parse the rest of the packet (what is
         * an option name and what is a value?)  In either case,
         * discard the rest.
         */
        options = packet_buf + 2;
        if (*options == 0)
            goto done_pkt;

        dst = src = options;
        while (buffersize--) {
            if (*src == 0)
                break;          /* found a final null */
            *dst++ = *src++ | 0x20;
            if (!buffersize)
                goto done_pkt;  /* found no final null */
        }
        
        /* 
         * Parse option pointed to by options; guaranteed to be null-terminated
         */
        p = options;
        do {
            tftp_opt = tftp_options;
            for (i = 0; i < tftp_opts; i++) {
                if (!strncmp(p, tftp_opt->str_ptr,tftp_opt->str_len))
                    break;
                tftp_opt++;
            }
            if (i == tftp_opts)
                goto err_reply; /* Non-negotitated option returned, no idea what it means ...*/
            
            p += tftp_opt->str_len;
            
            /* get the address of the filed that we want to write on */
            data_ptr = (uint32_t *)((char *)file + tftp_opt->offset);
            *data_ptr = 0;
            
            /* do convert a number-string to decimal number, just like atoi */
            while (buffersize--) {
                if (*p == 0)
                    break;              /* found a final null */
                if (*p > '9')
                    goto err_reply;     /* Not a decimal digit */
                *data_ptr = *data_ptr * 10 + *p++ - '0';
            }
            
        }while (buffersize);
        
    } else {
        extern char tftp_proto_err[];
    err_reply:
    
        uw_pkt.rport = file->tftp_remoteport;
        uw_pkt.buffer[0] = OFFS_WRT(tftp_proto_err, 0);
        uw_pkt.buffer[1] = 0;
        uw_pkt.buffersize = 24;
        pxe_call(PXENV_UDP_WRITE, &uw_pkt);
        printf("TFTP server sent an incomprehesible reply\n");
        call16(kaboom, NULL, NULL);
    }
    
 done_pkt:
    regs->eax.l    = file->tftp_filesize;
    regs->esi.w[0] = OFFS_WRT(file, 0);
 got_file:
    regs->eflags.l &= ~EFLAGS_ZF;
    if (!file->tftp_filesize) {
    error:
        free_socket(file);
        regs->esi.w[0] = 0;
        regs->eflags.l |= EFLAGS_ZF;
    }
    return;


 failure:
    timeout_ptr++;
    if (*timeout_ptr)
        goto sendreq;  /* Try again */
}
    
    
    
/*
 * Network-specific initialization
 */   
void network_init()
{   
    struct bootp_t *bp = (struct bootp_t *)trackbuf;
    int pkt_len;

    *LocalDomain = 0;   /* No LocalDomain received */
    
    /*
     * Get the DHCP client identifiers (query info 1)
     */
    printf("%s", get_packet_msg);
    pkt_len = pxe_get_cached_info(1);
    parse_dhcp(pkt_len);
    /*
      ; We don't use flags from the request packet, so
      ; this is a good time to initialize DHCPMagic...
      ; Initialize it to 1 meaning we will accept options found;
      ; in earlier versions of PXELINUX bit 0 was used to indicate
      ; we have found option 208 with the appropriate magic number;
      ; we no longer require that, but MAY want to re-introduce
      ; it in the future for vendor encapsulated options.
    */
    *(char *)&DHCPMagic = 1;

    
    /*
     * Get the BOOTP/DHCP packet that brought us file (and an IP
     * address). This lives in the DHCPACK packet (query info 2)
     */
    pkt_len = pxe_get_cached_info(2);
    parse_dhcp(pkt_len);
    /*
     * Save away MAC address (assume this is in query info 2. If this 
     * turns out to be problematic it might be better getting it from
     * the query info 1 packet
     */
    MACLen = bp->hardlen > 16 ? 0 : bp->hardlen;
    MACType = bp->hardware;
    memcpy(MAC, bp->macaddr, MACLen);
    

    /*
     * Get the boot file and other info. This lives in the CACHED_REPLY
     * packet (query info 3)
     */
    pkt_len = pxe_get_cached_info(3);
    parse_dhcp(pkt_len);
 
    printf("\n");



    make_bootif_string();
    ip_init();

    /*
     * Check to see if we got any PXELINUX-specific DHCP options; in particular,
     * if we didn't get the magic enable, do not recognize any other options.
     */
    if ((DHCPMagic & 1) == 0)
        DHCPMagic = 0;

    udp_init();
}