7237fff4db62b008d3db32f84ce95848665baa76
[profile/ivi/syslinux.git] / pxelinux.asm
1 ; -*- fundamental -*- (asm-mode sucks)
2 ; ****************************************************************************
3 ;
4 ;  pxelinux.asm
5 ;
6 ;  A program to boot Linux kernels off a TFTP server using the Intel PXE
7 ;  network booting API.  It is based on the SYSLINUX boot loader for
8 ;  MS-DOS floppies.
9 ;
10 ;   Copyright 1994-2008 H. Peter Anvin - All Rights Reserved
11 ;
12 ;  This program is free software; you can redistribute it and/or modify
13 ;  it under the terms of the GNU General Public License as published by
14 ;  the Free Software Foundation, Inc., 53 Temple Place Ste 330,
15 ;  Boston MA 02111-1307, USA; either version 2 of the License, or
16 ;  (at your option) any later version; incorporated herein by reference.
17 ;
18 ; ****************************************************************************
19
20 %define IS_PXELINUX 1
21 %include "head.inc"
22 %include "pxe.inc"
23
24 ;
25 ; Some semi-configurable constants... change on your own risk.
26 ;
27 my_id           equ pxelinux_id
28 FILENAME_MAX_LG2 equ 7                  ; log2(Max filename size Including final null)
29 FILENAME_MAX    equ (1 << FILENAME_MAX_LG2)
30 NULLFILE        equ 0                   ; Zero byte == null file name
31 NULLOFFSET      equ 4                   ; Position in which to look
32 REBOOT_TIME     equ 5*60                ; If failure, time until full reset
33 %assign HIGHMEM_SLOP 128*1024           ; Avoid this much memory near the top
34 MAX_OPEN_LG2    equ 5                   ; log2(Max number of open sockets)
35 MAX_OPEN        equ (1 << MAX_OPEN_LG2)
36 PKTBUF_SIZE     equ (65536/MAX_OPEN)    ; Per-socket packet buffer size
37 TFTP_PORT       equ htons(69)           ; Default TFTP port
38 PKT_RETRY       equ 6                   ; Packet transmit retry count
39 PKT_TIMEOUT     equ 12                  ; Initial timeout, timer ticks @ 55 ms
40 ; Desired TFTP block size
41 ; For Ethernet MTU is normally 1500.  Unfortunately there seems to
42 ; be a fair number of networks with "substandard" MTUs which break.
43 ; The code assumes TFTP_LARGEBLK <= 2K.
44 TFTP_MTU        equ 1440
45 TFTP_LARGEBLK   equ (TFTP_MTU-20-8-4)   ; MTU - IP hdr - UDP hdr - TFTP hdr
46 ; Standard TFTP block size
47 TFTP_BLOCKSIZE_LG2 equ 9                ; log2(bytes/block)
48 TFTP_BLOCKSIZE  equ (1 << TFTP_BLOCKSIZE_LG2)
49 %assign USE_PXE_PROVIDED_STACK 1        ; Use stack provided by PXE?
50
51 SECTOR_SHIFT    equ TFTP_BLOCKSIZE_LG2
52 SECTOR_SIZE     equ TFTP_BLOCKSIZE
53
54 ;
55 ; This is what we need to do when idle
56 ; *** This is disabled because some PXE stacks wait for unacceptably
57 ; *** long if there are no packets receivable.
58
59 %define HAVE_IDLE 0                     ; idle is not a noop
60
61 %if HAVE_IDLE
62 %macro  RESET_IDLE 0
63         call reset_idle
64 %endmacro
65 %macro  DO_IDLE 0
66         call check_for_arp
67 %endmacro
68 %else
69 %macro  RESET_IDLE 0
70         ; Nothing
71 %endmacro
72 %macro  DO_IDLE 0
73         ; Nothing
74 %endmacro
75 %endif
76
77 ;
78 ; TFTP operation codes
79 ;
80 TFTP_RRQ        equ htons(1)            ; Read request
81 TFTP_WRQ        equ htons(2)            ; Write request
82 TFTP_DATA       equ htons(3)            ; Data packet
83 TFTP_ACK        equ htons(4)            ; ACK packet
84 TFTP_ERROR      equ htons(5)            ; ERROR packet
85 TFTP_OACK       equ htons(6)            ; OACK packet
86
87 ;
88 ; TFTP error codes
89 ;
90 TFTP_EUNDEF     equ htons(0)            ; Unspecified error
91 TFTP_ENOTFOUND  equ htons(1)            ; File not found
92 TFTP_EACCESS    equ htons(2)            ; Access violation
93 TFTP_ENOSPACE   equ htons(3)            ; Disk full
94 TFTP_EBADOP     equ htons(4)            ; Invalid TFTP operation
95 TFTP_EBADID     equ htons(5)            ; Unknown transfer
96 TFTP_EEXISTS    equ htons(6)            ; File exists
97 TFTP_ENOUSER    equ htons(7)            ; No such user
98 TFTP_EOPTNEG    equ htons(8)            ; Option negotiation failure
99
100 ;
101 ; The following structure is used for "virtual kernels"; i.e. LILO-style
102 ; option labels.  The options we permit here are `kernel' and `append
103 ; Since there is no room in the bottom 64K for all of these, we
104 ; stick them at vk_seg:0000 and copy them down before we need them.
105 ;
106                 struc vkernel
107 vk_vname:       resb FILENAME_MAX       ; Virtual name **MUST BE FIRST!**
108 vk_rname:       resb FILENAME_MAX       ; Real name
109 vk_ipappend:    resb 1                  ; "IPAPPEND" flag
110 vk_type:        resb 1                  ; Type of file
111 vk_appendlen:   resw 1
112                 alignb 4
113 vk_append:      resb max_cmd_len+1      ; Command line
114                 alignb 4
115 vk_end:         equ $                   ; Should be <= vk_size
116                 endstruc
117
118 ;
119 ; Segment assignments in the bottom 640K
120 ; 0000h - main code/data segment (and BIOS segment)
121 ;
122 real_mode_seg   equ 4000h
123 pktbuf_seg      equ 3000h               ; Packet buffers segments
124 vk_seg          equ 2000h               ; Virtual kernels
125 xfer_buf_seg    equ 1000h               ; Bounce buffer for I/O to high mem
126 comboot_seg     equ real_mode_seg       ; COMBOOT image loading zone
127
128 ;
129 ; BOOTP/DHCP packet pattern
130 ;
131                 struc bootp_t
132 bootp:
133 .opcode         resb 1                  ; BOOTP/DHCP "opcode"
134 .hardware       resb 1                  ; ARP hardware type
135 .hardlen        resb 1                  ; Hardware address length
136 .gatehops       resb 1                  ; Used by forwarders
137 .ident          resd 1                  ; Transaction ID
138 .seconds        resw 1                  ; Seconds elapsed
139 .flags          resw 1                  ; Broadcast flags
140 .cip            resd 1                  ; Client IP
141 .yip            resd 1                  ; "Your" IP
142 .sip            resd 1                  ; Next server IP
143 .gip            resd 1                  ; Relay agent IP
144 .macaddr        resb 16                 ; Client MAC address
145 .sname          resb 64                 ; Server name (optional)
146 .bootfile       resb 128                ; Boot file name
147 .option_magic   resd 1                  ; Vendor option magic cookie
148 .options        resb 1260               ; Vendor options
149                 endstruc
150
151 BOOTP_OPTION_MAGIC      equ htonl(0x63825363)   ; See RFC 2132
152
153 ;
154 ; TFTP connection data structure.  Each one of these corresponds to a local
155 ; UDP port.  The size of this structure must be a power of 2.
156 ; HBO = host byte order; NBO = network byte order
157 ; (*) = written by options negotiation code, must be dword sized
158 ;
159                 struc open_file_t
160 tftp_localport  resw 1                  ; Local port number     (0 = not in use)
161 tftp_remoteport resw 1                  ; Remote port number
162 tftp_remoteip   resd 1                  ; Remote IP address
163 tftp_filepos    resd 1                  ; Bytes downloaded (including buffer)
164 tftp_filesize   resd 1                  ; Total file size(*)
165 tftp_blksize    resd 1                  ; Block size for this connection(*)
166 tftp_bytesleft  resw 1                  ; Unclaimed data bytes
167 tftp_lastpkt    resw 1                  ; Sequence number of last packet (NBO)
168 tftp_dataptr    resw 1                  ; Pointer to available data
169                 resw 2                  ; Currently unusued
170                 ; At end since it should not be zeroed on socked close
171 tftp_pktbuf     resw 1                  ; Packet buffer offset
172                 endstruc
173 %ifndef DEPEND
174 %if (open_file_t_size & (open_file_t_size-1))
175 %error "open_file_t is not a power of 2"
176 %endif
177 %endif
178
179 ; ---------------------------------------------------------------------------
180 ;   BEGIN CODE
181 ; ---------------------------------------------------------------------------
182
183 ;
184 ; Memory below this point is reserved for the BIOS and the MBR
185 ;
186                 section .earlybss
187 trackbufsize    equ 8192
188 trackbuf        resb trackbufsize       ; Track buffer goes here
189                 ; ends at 2800h
190
191                 alignb open_file_t_size
192 Files           resb MAX_OPEN*open_file_t_size
193
194                 alignb FILENAME_MAX
195 BootFile        resb 256                ; Boot file from DHCP packet
196 PathPrefix      resb 256                ; Path prefix derived from boot file
197 DotQuadBuf      resb 16                 ; Buffer for dotted-quad IP address
198 IPOption        resb 80                 ; ip= option buffer
199 InitStack       resd 1                  ; Pointer to reset stack (SS:SP)
200 PXEStack        resd 1                  ; Saved stack during PXE call
201
202                 section .bss
203                 alignb 4
204 RebootTime      resd 1                  ; Reboot timeout, if set by option
205 StrucPtr        resd 1                  ; Pointer to PXENV+ or !PXE structure
206 APIVer          resw 1                  ; PXE API version found
207 IPOptionLen     resw 1                  ; Length of IPOption
208 IdleTimer       resw 1                  ; Time to check for ARP?
209 LocalBootType   resw 1                  ; Local boot return code
210 PktTimeout      resw 1                  ; Timeout for current packet
211 RealBaseMem     resw 1                  ; Amount of DOS memory after freeing
212 OverLoad        resb 1                  ; Set if DHCP packet uses "overloading"
213 DHCPMagic       resb 1                  ; PXELINUX magic flags
214
215 ; The relative position of these fields matter!
216 MAC_MAX         equ  32                 ; Handle hardware addresses this long
217 MACLen          resb 1                  ; MAC address len
218 MACType         resb 1                  ; MAC address type
219 MAC             resb MAC_MAX+1          ; Actual MAC address
220 BOOTIFStr       resb 7                  ; Space for "BOOTIF="
221 MACStr          resb 3*(MAC_MAX+1)      ; MAC address as a string
222
223 ; The relative position of these fields matter!
224 UUIDType        resb 1                  ; Type byte from DHCP option
225 UUID            resb 16                 ; UUID, from the PXE stack
226 UUIDNull        resb 1                  ; dhcp_copyoption zero-terminates
227
228 ;
229 ; PXE packets which don't need static initialization
230 ;
231                 alignb 4
232 pxe_unload_stack_pkt:
233 .status:        resw 1                  ; Status
234 .reserved:      resw 10                 ; Reserved
235 pxe_unload_stack_pkt_len        equ $-pxe_unload_stack_pkt
236
237                 alignb 16
238                 ; BOOTP/DHCP packet buffer
239
240                 section .bss2
241                 alignb 16
242 packet_buf      resb 2048               ; Transfer packet
243 packet_buf_size equ $-packet_buf
244
245                 section .text
246                 ;
247                 ; PXELINUX needs more BSS than the other derivatives;
248                 ; therefore we relocate it from 7C00h on startup.
249                 ;
250 StackBuf        equ $                   ; Base of stack if we use our own
251
252 ;
253 ; Primary entry point.
254 ;
255 bootsec         equ $
256 _start:
257                 pushfd                  ; Paranoia... in case of return to PXE
258                 pushad                  ; ... save as much state as possible
259                 push ds
260                 push es
261                 push fs
262                 push gs
263
264                 xor ax,ax
265                 mov ds,ax
266                 mov es,ax
267
268 %ifndef DEPEND
269 %if TEXT_START != 0x7c00
270                 ; This is uglier than it should be, but works around
271                 ; some NASM 0.98.38 bugs.
272                 mov di,section..bcopy32.start
273                 add di,__bcopy_size-4
274                 lea si,[di-(TEXT_START-7C00h)]
275                 lea cx,[di-(TEXT_START-4)]
276                 shr cx,2
277                 std                     ; Overlapping areas, copy backwards
278                 rep movsd
279 %endif
280 %endif
281                 jmp 0:_start1           ; Canonicalize address
282 _start1:
283                 mov bp,sp
284                 les bx,[bp+48]          ; ES:BX -> !PXE or PXENV+ structure
285
286                 ; That is all pushed onto the PXE stack.  Save the pointer
287                 ; to it and switch to an internal stack.
288                 mov [InitStack],sp
289                 mov [InitStack+2],ss
290
291 %if USE_PXE_PROVIDED_STACK
292                 ; Apparently some platforms go bonkers if we
293                 ; set up our own stack...
294                 mov [BaseStack],sp
295                 mov [BaseStack+4],ss
296 %endif
297
298                 cli                     ; Paranoia
299                 lss esp,[BaseStack]
300
301                 sti                     ; Stack set up and ready
302                 cld                     ; Copy upwards
303
304 ;
305 ; Initialize screen (if we're using one)
306 ;
307                 push es                 ; Save ES -> PXE entry structure
308                 push ds
309                 pop es                  ; ES <- DS
310 %include "init.inc"
311                 pop es                  ; Restore ES -> PXE entry structure
312 ;
313 ; Tell the user we got this far
314 ;
315                 mov si,syslinux_banner
316                 call writestr
317
318                 mov si,copyright_str
319                 call writestr
320
321 ;
322 ; Assume API version 2.1, in case we find the !PXE structure without
323 ; finding the PXENV+ structure.  This should really look at the Base
324 ; Code ROM ID structure in have_pxe, but this is adequate for now --
325 ; if we have !PXE, we have to be 2.1 or higher, and we don't care
326 ; about higher versions than that.
327 ;
328                 mov word [APIVer],0201h
329
330 ;
331 ; Now we need to find the !PXE structure.  It's *supposed* to be pointed
332 ; to by SS:[SP+4], but support INT 1Ah, AX=5650h method as well.
333 ; FIX: ES:BX should point to the PXENV+ structure on entry as well.
334 ; We should make that the second test, and not trash ES:BX...
335 ;
336                 cmp dword [es:bx], '!PXE'
337                 je have_pxe
338
339                 ; Uh-oh, not there... try plan B
340                 mov ax, 5650h
341 %if USE_PXE_PROVIDED_STACK == 0
342                 lss sp,[InitStack]
343 %endif
344                 int 1Ah                                 ; May trash regs
345 %if USE_PXE_PROVIDED_STACK == 0
346                 lss esp,[BaseStack]
347 %endif
348
349                 jc no_pxe
350                 cmp ax,564Eh
351                 jne no_pxe
352
353                 ; Okay, that gave us the PXENV+ structure, find !PXE
354                 ; structure from that (if available)
355                 cmp dword [es:bx], 'PXEN'
356                 jne no_pxe
357                 cmp word [es:bx+4], 'V+'
358                 je have_pxenv
359
360                 ; Nothing there either.  Last-ditch: scan memory
361                 call memory_scan_for_pxe_struct         ; !PXE scan
362                 jnc have_pxe
363                 call memory_scan_for_pxenv_struct       ; PXENV+ scan
364                 jnc have_pxenv
365
366 no_pxe:         mov si,err_nopxe
367                 call writestr
368                 jmp kaboom
369
370 have_pxenv:
371                 mov [StrucPtr],bx
372                 mov [StrucPtr+2],es
373
374                 mov si,found_pxenv
375                 call writestr
376
377                 mov si,apiver_str
378                 call writestr
379                 mov ax,[es:bx+6]
380                 mov [APIVer],ax
381                 call writehex4
382                 call crlf
383
384                 cmp ax,0201h                    ; API version 2.1 or higher
385                 jb old_api
386                 mov si,bx
387                 mov ax,es
388                 les bx,[es:bx+28h]              ; !PXE structure pointer
389                 cmp dword [es:bx],'!PXE'
390                 je have_pxe
391
392                 ; Nope, !PXE structure missing despite API 2.1+, or at least
393                 ; the pointer is missing.  Do a last-ditch attempt to find it.
394                 call memory_scan_for_pxe_struct
395                 jnc have_pxe
396
397                 ; Otherwise, no dice, use PXENV+ structure
398                 mov bx,si
399                 mov es,ax
400
401 old_api:        ; Need to use a PXENV+ structure
402                 mov si,using_pxenv_msg
403                 call writestr
404
405                 mov eax,[es:bx+0Ah]             ; PXE RM API
406                 mov [PXENVEntry],eax
407
408                 mov si,undi_data_msg
409                 call writestr
410                 mov ax,[es:bx+20h]
411                 call writehex4
412                 call crlf
413                 mov si,undi_data_len_msg
414                 call writestr
415                 mov ax,[es:bx+22h]
416                 call writehex4
417                 call crlf
418                 mov si,undi_code_msg
419                 call writestr
420                 mov ax,[es:bx+24h]
421                 call writehex4
422                 call crlf
423                 mov si,undi_code_len_msg
424                 call writestr
425                 mov ax,[es:bx+26h]
426                 call writehex4
427                 call crlf
428
429                 ; Compute base memory size from PXENV+ structure
430                 xor esi,esi
431                 movzx eax,word [es:bx+20h]      ; UNDI data seg
432                 cmp ax,[es:bx+24h]              ; UNDI code seg
433                 ja .use_data
434                 mov ax,[es:bx+24h]
435                 mov si,[es:bx+26h]
436                 jmp short .combine
437 .use_data:
438                 mov si,[es:bx+22h]
439 .combine:
440                 shl eax,4
441                 add eax,esi
442                 shr eax,10                      ; Convert to kilobytes
443                 mov [RealBaseMem],ax
444
445                 mov si,pxenventry_msg
446                 call writestr
447                 mov ax,[PXENVEntry+2]
448                 call writehex4
449                 mov al,':'
450                 call writechr
451                 mov ax,[PXENVEntry]
452                 call writehex4
453                 call crlf
454                 jmp have_entrypoint
455
456 have_pxe:
457                 mov [StrucPtr],bx
458                 mov [StrucPtr+2],es
459
460                 mov eax,[es:bx+10h]
461                 mov [PXEEntry],eax
462
463                 mov si,undi_data_msg
464                 call writestr
465                 mov eax,[es:bx+2Ah]
466                 call writehex8
467                 call crlf
468                 mov si,undi_data_len_msg
469                 call writestr
470                 mov ax,[es:bx+2Eh]
471                 call writehex4
472                 call crlf
473                 mov si,undi_code_msg
474                 call writestr
475                 mov ax,[es:bx+32h]
476                 call writehex8
477                 call crlf
478                 mov si,undi_code_len_msg
479                 call writestr
480                 mov ax,[es:bx+36h]
481                 call writehex4
482                 call crlf
483
484                 ; Compute base memory size from !PXE structure
485                 xor esi,esi
486                 mov eax,[es:bx+2Ah]
487                 cmp eax,[es:bx+32h]
488                 ja .use_data
489                 mov eax,[es:bx+32h]
490                 mov si,[es:bx+36h]
491                 jmp short .combine
492 .use_data:
493                 mov si,[es:bx+2Eh]
494 .combine:
495                 add eax,esi
496                 shr eax,10
497                 mov [RealBaseMem],ax
498
499                 mov si,pxeentry_msg
500                 call writestr
501                 mov ax,[PXEEntry+2]
502                 call writehex4
503                 mov al,':'
504                 call writechr
505                 mov ax,[PXEEntry]
506                 call writehex4
507                 call crlf
508
509 have_entrypoint:
510                 push cs
511                 pop es                          ; Restore CS == DS == ES
512
513 ;
514 ; Network-specific initialization
515 ;
516                 xor ax,ax
517                 mov [LocalDomain],al            ; No LocalDomain received
518
519 ;
520 ; The DHCP client identifiers are best gotten from the DHCPREQUEST
521 ; packet (query info 1).
522 ;
523 query_bootp_1:
524                 mov dl,1
525                 call pxe_get_cached_info
526                 call parse_dhcp
527
528                 ; We don't use flags from the request packet, so
529                 ; this is a good time to initialize DHCPMagic...
530                 ; Initialize it to 1 meaning we will accept options found;
531                 ; in earlier versions of PXELINUX bit 0 was used to indicate
532                 ; we have found option 208 with the appropriate magic number;
533                 ; we no longer require that, but MAY want to re-introduce
534                 ; it in the future for vendor encapsulated options.
535                 mov byte [DHCPMagic],1
536
537 ;
538 ; Now attempt to get the BOOTP/DHCP packet that brought us life (and an IP
539 ; address).  This lives in the DHCPACK packet (query info 2).
540 ;
541 query_bootp_2:
542                 mov dl,2
543                 call pxe_get_cached_info
544                 call parse_dhcp                 ; Parse DHCP packet
545 ;
546 ; Save away MAC address (assume this is in query info 2.  If this
547 ; turns out to be problematic it might be better getting it from
548 ; the query info 1 packet.)
549 ;
550 .save_mac:
551                 movzx cx,byte [trackbuf+bootp.hardlen]
552                 cmp cx,16
553                 jna .mac_ok
554                 xor cx,cx               ; Bad hardware address length
555 .mac_ok:
556                 mov [MACLen],cl
557                 mov al,[trackbuf+bootp.hardware]
558                 mov [MACType],al
559                 mov si,trackbuf+bootp.macaddr
560                 mov di,MAC
561                 rep movsb
562
563 ; Enable this if we really need to zero-pad this field...
564 ;               mov cx,MAC+MAC_MAX+1
565 ;               sub cx,di
566 ;               xor ax,ax
567 ;               rep stosb
568
569 ;
570 ; Now, get the boot file and other info.  This lives in the CACHED_REPLY
571 ; packet (query info 3).
572 ;
573                 mov dl,3
574                 call pxe_get_cached_info
575                 call parse_dhcp                 ; Parse DHCP packet
576
577 ;
578 ; Generate the bootif string, and the hardware-based config string.
579 ;
580 make_bootif_string:
581                 mov si,bootif_str
582                 mov di,BOOTIFStr
583                 mov cx,bootif_str_len
584                 rep movsb
585
586                 movzx cx,byte [MACLen]
587                 mov si,MACType
588                 inc cx
589 .hexify_mac:
590                 push cx
591                 mov cl,1                ; CH == 0 already
592                 call lchexbytes
593                 mov al,'-'
594                 stosb
595                 pop cx
596                 loop .hexify_mac
597                 mov [di-1],cl           ; Null-terminate and strip final dash
598 ;
599 ; Generate ip= option
600 ;
601                 call genipopt
602
603 ;
604 ; Print IP address
605 ;
606                 mov eax,[MyIP]
607                 mov di,DotQuadBuf
608                 push di
609                 call gendotquad                 ; This takes network byte order input
610
611                 xchg ah,al                      ; Convert to host byte order
612                 ror eax,16                      ; (BSWAP doesn't work on 386)
613                 xchg ah,al
614
615                 mov si,myipaddr_msg
616                 call writestr
617                 call writehex8
618                 mov al,' '
619                 call writechr
620                 pop si                          ; DotQuadBuf
621                 call writestr
622                 call crlf
623
624                 mov si,IPOption
625                 call writestr
626                 call crlf
627
628 ;
629 ; Check to see if we got any PXELINUX-specific DHCP options; in particular,
630 ; if we didn't get the magic enable, do not recognize any other options.
631 ;
632 check_dhcp_magic:
633                 test byte [DHCPMagic], 1        ; If we didn't get the magic enable...
634                 jnz .got_magic
635                 mov byte [DHCPMagic], 0         ; If not, kill all other options
636 .got_magic:
637
638
639 ;
640 ; Initialize UDP stack
641 ;
642 udp_init:
643                 mov eax,[MyIP]
644                 mov [pxe_udp_open_pkt.sip],eax
645                 mov di,pxe_udp_open_pkt
646                 mov bx,PXENV_UDP_OPEN
647                 call pxenv
648                 jc .failed
649                 cmp word [pxe_udp_open_pkt.status], byte 0
650                 je .success
651 .failed:        mov si,err_udpinit
652                 call writestr
653                 jmp kaboom
654 .success:
655
656 ;
657 ; Common initialization code
658 ;
659 %include "cpuinit.inc"
660
661 ;
662 ; Now we're all set to start with our *real* business.  First load the
663 ; configuration file (if any) and parse it.
664 ;
665 ; In previous versions I avoided using 32-bit registers because of a
666 ; rumour some BIOSes clobbered the upper half of 32-bit registers at
667 ; random.  I figure, though, that if there are any of those still left
668 ; they probably won't be trying to install Linux on them...
669 ;
670 ; The code is still ripe with 16-bitisms, though.  Not worth the hassle
671 ; to take'm out.  In fact, we may want to put them back if we're going
672 ; to boot ELKS at some point.
673 ;
674
675 ;
676 ; Store standard filename prefix
677 ;
678 prefix:         test byte [DHCPMagic], 04h      ; Did we get a path prefix option
679                 jnz .got_prefix
680                 mov si,BootFile
681                 mov di,PathPrefix
682                 cld
683                 call strcpy
684                 mov cx,di
685                 sub cx,PathPrefix+1
686                 std
687                 lea si,[di-2]                   ; Skip final null!
688 .find_alnum:    lodsb
689                 or al,20h
690                 cmp al,'.'                      ; Count . or - as alphanum
691                 je .alnum
692                 cmp al,'-'
693                 je .alnum
694                 cmp al,'0'
695                 jb .notalnum
696                 cmp al,'9'
697                 jbe .alnum
698                 cmp al,'a'
699                 jb .notalnum
700                 cmp al,'z'
701                 ja .notalnum
702 .alnum:         loop .find_alnum
703                 dec si
704 .notalnum:      mov byte [si+2],0               ; Zero-terminate after delimiter
705                 cld
706 .got_prefix:
707                 mov si,tftpprefix_msg
708                 call writestr
709                 mov si,PathPrefix
710                 call writestr
711                 call crlf
712
713 ;
714 ; Load configuration file
715 ;
716 find_config:
717
718 ;
719 ; Begin looking for configuration file
720 ;
721 config_scan:
722                 test byte [DHCPMagic], 02h
723                 jz .no_option
724
725                 ; We got a DHCP option, try it first
726                 call .try
727                 jnz .success
728
729 .no_option:
730                 mov di,ConfigName
731                 mov si,cfgprefix
732                 mov cx,cfgprefix_len
733                 rep movsb
734
735                 ; Have to guess config file name...
736
737                 ; Try loading by UUID.
738                 cmp byte [HaveUUID],0
739                 je .no_uuid
740
741                 push di
742                 mov bx,uuid_dashes
743                 mov si,UUID
744 .gen_uuid:
745                 movzx cx,byte [bx]
746                 jcxz .done_uuid
747                 inc bx
748                 call lchexbytes
749                 mov al,'-'
750                 stosb
751                 jmp .gen_uuid
752 .done_uuid:
753                 mov [di-1],cl           ; Remove last dash and zero-terminate
754                 pop di
755                 call .try
756                 jnz .success
757 .no_uuid:
758
759                 ; Try loading by MAC address
760                 push di
761                 mov si,MACStr
762                 call strcpy
763                 pop di
764                 call .try
765                 jnz .success
766
767                 ; Nope, try hexadecimal IP prefixes...
768 .scan_ip:
769                 mov cx,4
770                 mov si,MyIP
771                 call uchexbytes                 ; Convert to hex string
772
773                 mov cx,8                        ; Up to 8 attempts
774 .tryagain:
775                 mov byte [di],0                 ; Zero-terminate string
776                 call .try
777                 jnz .success
778                 dec di                          ; Drop one character
779                 loop .tryagain
780
781                 ; Final attempt: "default" string
782                 mov si,default_str              ; "default" string
783                 call strcpy
784                 call .try
785                 jnz .success
786
787                 mov si,err_noconfig
788                 call writestr
789                 jmp kaboom
790
791 .try:
792                 pusha
793                 mov si,trying_msg
794                 call writestr
795                 mov di,ConfigName
796                 mov si,di
797                 call writestr
798                 call crlf
799                 mov si,di
800                 mov di,KernelName       ;  Borrow this buffer for mangled name
801                 call mangle_name
802                 call open
803                 popa
804                 ret
805
806
807 .success:
808
809 ;
810 ; Linux kernel loading code is common.  However, we need to define
811 ; a couple of helper macros...
812 ;
813
814 ; Handle "ipappend" option
815 %define HAVE_SPECIAL_APPEND
816 %macro  SPECIAL_APPEND 0
817                 test byte [IPAppend],01h        ; ip=
818                 jz .noipappend1
819                 mov si,IPOption
820                 mov cx,[IPOptionLen]
821                 rep movsb
822                 mov al,' '
823                 stosb
824 .noipappend1:
825                 test byte [IPAppend],02h
826                 jz .noipappend2
827                 mov si,BOOTIFStr
828                 call strcpy
829                 mov byte [es:di-1],' '          ; Replace null with space
830 .noipappend2:
831 %endmacro
832
833 ; Unload PXE stack
834 %define HAVE_UNLOAD_PREP
835 %macro  UNLOAD_PREP 0
836                 call unload_pxe
837 %endmacro
838
839 ;
840 ; Now we have the config file open.  Parse the config file and
841 ; run the user interface.
842 ;
843 %include "ui.inc"
844
845 ;
846 ; Boot to the local disk by returning the appropriate PXE magic.
847 ; AX contains the appropriate return code.
848 ;
849 local_boot:
850                 push cs
851                 pop ds
852                 mov [LocalBootType],ax
853                 call vgaclearmode
854                 mov si,localboot_msg
855                 call writestr
856                 ; Restore the environment we were called with
857                 lss sp,[InitStack]
858                 pop gs
859                 pop fs
860                 pop es
861                 pop ds
862                 popad
863                 mov ax,[cs:LocalBootType]
864                 popfd
865                 retf                            ; Return to PXE
866
867 ;
868 ; kaboom: write a message and bail out.  Wait for quite a while,
869 ;         or a user keypress, then do a hard reboot.
870 ;
871 kaboom:
872                 RESET_STACK_AND_SEGS AX
873 .patch:         mov si,bailmsg
874                 call writestr           ; Returns with AL = 0
875 .drain:         call pollchar
876                 jz .drained
877                 call getchar
878                 jmp short .drain
879 .drained:
880                 mov edi,[RebootTime]
881                 mov al,[DHCPMagic]
882                 and al,09h              ; Magic+Timeout
883                 cmp al,09h
884                 je .time_set
885                 mov edi,REBOOT_TIME
886 .time_set:
887                 mov cx,18
888 .wait1:         push cx
889                 mov ecx,edi
890 .wait2:         mov dx,[BIOS_timer]
891 .wait3:         call pollchar
892                 jnz .keypress
893                 cmp dx,[BIOS_timer]
894                 je .wait3
895                 loop .wait2,ecx
896                 mov al,'.'
897                 call writechr
898                 pop cx
899                 loop .wait1
900 .keypress:
901                 call crlf
902                 mov word [BIOS_magic],0 ; Cold reboot
903                 jmp 0F000h:0FFF0h       ; Reset vector address
904
905 ;
906 ; memory_scan_for_pxe_struct:
907 ;
908 ;       If none of the standard methods find the !PXE structure, look for it
909 ;       by scanning memory.
910 ;
911 ;       On exit, if found:
912 ;               CF = 0, ES:BX -> !PXE structure
913 ;       Otherwise CF = 1, all registers saved
914 ;
915 memory_scan_for_pxe_struct:
916                 push ds
917                 pusha
918                 mov ax,cs
919                 mov ds,ax
920                 mov si,trymempxe_msg
921                 call writestr
922                 mov ax,[BIOS_fbm]       ; Starting segment
923                 shl ax,(10-4)           ; Kilobytes -> paragraphs
924 ;               mov ax,01000h           ; Start to look here
925                 dec ax                  ; To skip inc ax
926 .mismatch:
927                 inc ax
928                 cmp ax,0A000h           ; End of memory
929                 jae .not_found
930                 call writehex4
931                 mov si,fourbs_msg
932                 call writestr
933                 mov es,ax
934                 mov edx,[es:0]
935                 cmp edx,'!PXE'
936                 jne .mismatch
937                 movzx cx,byte [es:4]    ; Length of structure
938                 cmp cl,08h              ; Minimum length
939                 jb .mismatch
940                 push ax
941                 xor ax,ax
942                 xor si,si
943 .checksum:      es lodsb
944                 add ah,al
945                 loop .checksum
946                 pop ax
947                 jnz .mismatch           ; Checksum must == 0
948 .found:         mov bp,sp
949                 xor bx,bx
950                 mov [bp+8],bx           ; Save BX into stack frame (will be == 0)
951                 mov ax,es
952                 call writehex4
953                 call crlf
954                 popa
955                 pop ds
956                 clc
957                 ret
958 .not_found:     mov si,notfound_msg
959                 call writestr
960                 popa
961                 pop ds
962                 stc
963                 ret
964
965 ;
966 ; memory_scan_for_pxenv_struct:
967 ;
968 ;       If none of the standard methods find the PXENV+ structure, look for it
969 ;       by scanning memory.
970 ;
971 ;       On exit, if found:
972 ;               CF = 0, ES:BX -> PXENV+ structure
973 ;       Otherwise CF = 1, all registers saved
974 ;
975 memory_scan_for_pxenv_struct:
976                 pusha
977                 mov si,trymempxenv_msg
978                 call writestr
979 ;               mov ax,[BIOS_fbm]       ; Starting segment
980 ;               shl ax,(10-4)           ; Kilobytes -> paragraphs
981                 mov ax,01000h           ; Start to look here
982                 dec ax                  ; To skip inc ax
983 .mismatch:
984                 inc ax
985                 cmp ax,0A000h           ; End of memory
986                 jae .not_found
987                 mov es,ax
988                 mov edx,[es:0]
989                 cmp edx,'PXEN'
990                 jne .mismatch
991                 mov dx,[es:4]
992                 cmp dx,'V+'
993                 jne .mismatch
994                 movzx cx,byte [es:8]    ; Length of structure
995                 cmp cl,26h              ; Minimum length
996                 jb .mismatch
997                 xor ax,ax
998                 xor si,si
999 .checksum:      es lodsb
1000                 add ah,al
1001                 loop .checksum
1002                 and ah,ah
1003                 jnz .mismatch           ; Checksum must == 0
1004 .found:         mov bp,sp
1005                 mov [bp+8],bx           ; Save BX into stack frame
1006                 mov ax,bx
1007                 call writehex4
1008                 call crlf
1009                 clc
1010                 ret
1011 .not_found:     mov si,notfound_msg
1012                 call writestr
1013                 popad
1014                 stc
1015                 ret
1016
1017 ;
1018 ; close_file:
1019 ;            Deallocates a file structure (pointer in SI)
1020 ;            Assumes CS == DS.
1021 ;
1022 ; XXX: We should check to see if this file is still open on the server
1023 ; side and send a courtesy ERROR packet to the server.
1024 ;
1025 close_file:
1026                 and si,si
1027                 jz .closed
1028                 mov word [si],0         ; Not in use
1029 .closed:        ret
1030
1031 ;
1032 ; searchdir:
1033 ;
1034 ;       Open a TFTP connection to the server
1035 ;
1036 ;            On entry:
1037 ;               DS:DI   = mangled filename
1038 ;            If successful:
1039 ;               ZF clear
1040 ;               SI      = socket pointer
1041 ;               DX:AX   = file length in bytes
1042 ;            If unsuccessful
1043 ;               ZF set
1044 ;
1045
1046 searchdir:
1047                 push es
1048                 push bx
1049                 push cx
1050                 mov ax,ds
1051                 mov es,ax
1052                 mov si,di
1053                 push bp
1054                 mov bp,sp
1055
1056                 call allocate_socket
1057                 jz .ret
1058
1059                 mov ax,PKT_RETRY        ; Retry counter
1060                 mov word [PktTimeout],PKT_TIMEOUT       ; Initial timeout
1061
1062 .sendreq:       push ax                 ; [bp-2]  - Retry counter
1063                 push si                 ; [bp-4]  - File name
1064
1065                 mov di,packet_buf
1066                 mov [pxe_udp_write_pkt.buffer],di
1067
1068                 mov ax,TFTP_RRQ         ; TFTP opcode
1069                 stosw
1070
1071                 lodsd                   ; EAX <- server override (if any)
1072                 and eax,eax
1073                 jnz .noprefix           ; No prefix, and we have the server
1074
1075                 push si                 ; Add common prefix
1076                 mov si,PathPrefix
1077                 call strcpy
1078                 dec di
1079                 pop si
1080
1081                 mov eax,[ServerIP]      ; Get default server
1082
1083 .noprefix:
1084                 call strcpy             ; Filename
1085
1086                 mov [bx+tftp_remoteip],eax
1087
1088                 push bx                 ; [bp-6]  - TFTP block
1089                 mov bx,[bx]
1090                 push bx                 ; [bp-8]  - TID (local port no)
1091
1092                 mov [pxe_udp_write_pkt.status],byte 0
1093                 mov [pxe_udp_write_pkt.sip],eax
1094                 ; Now figure out the gateway
1095                 xor eax,[MyIP]
1096                 and eax,[Netmask]
1097                 jz .nogwneeded
1098                 mov eax,[Gateway]
1099 .nogwneeded:
1100                 mov [pxe_udp_write_pkt.gip],eax
1101                 mov [pxe_udp_write_pkt.lport],bx
1102                 mov ax,[ServerPort]
1103                 mov [pxe_udp_write_pkt.rport],ax
1104                 mov si,tftp_tail
1105                 mov cx,tftp_tail_len
1106                 rep movsb
1107                 sub di,packet_buf       ; Get packet size
1108                 mov [pxe_udp_write_pkt.buffersize],di
1109
1110                 mov di,pxe_udp_write_pkt
1111                 mov bx,PXENV_UDP_WRITE
1112                 call pxenv
1113                 jc .failure
1114                 cmp word [pxe_udp_write_pkt.status],byte 0
1115                 jne .failure
1116
1117                 ;
1118                 ; Danger, Will Robinson!  We need to support timeout
1119                 ; and retry lest we just lost a packet...
1120                 ;
1121
1122                 ; Packet transmitted OK, now we need to receive
1123 .getpacket:     push word [PktTimeout]  ; [bp-10]
1124                 push word [BIOS_timer]  ; [bp-12]
1125
1126 .pkt_loop:      mov bx,[bp-8]           ; TID
1127                 mov di,packet_buf
1128                 mov word [pxe_udp_read_pkt.status],0
1129                 mov [pxe_udp_read_pkt.buffer],di
1130                 mov [pxe_udp_read_pkt.buffer+2],ds
1131                 mov word [pxe_udp_read_pkt.buffersize],packet_buf_size
1132                 mov eax,[MyIP]
1133                 mov [pxe_udp_read_pkt.dip],eax
1134                 mov [pxe_udp_read_pkt.lport],bx
1135                 mov di,pxe_udp_read_pkt
1136                 mov bx,PXENV_UDP_READ
1137                 call pxenv
1138                 and ax,ax
1139                 jz .got_packet                  ; Wait for packet
1140 .no_packet:
1141                 mov dx,[BIOS_timer]
1142                 cmp dx,[bp-12]
1143                 je .pkt_loop
1144                 mov [bp-12],dx
1145                 dec word [bp-10]                ; Timeout
1146                 jnz .pkt_loop
1147                 pop ax  ; Adjust stack
1148                 pop ax
1149                 shl word [PktTimeout],1         ; Exponential backoff
1150                 jmp .failure
1151
1152 .got_packet:
1153                 mov si,[bp-6]                   ; TFTP pointer
1154                 mov bx,[bp-8]                   ; TID
1155
1156                 mov eax,[si+tftp_remoteip]
1157                 cmp [pxe_udp_read_pkt.sip],eax  ; This is technically not to the TFTP spec?
1158                 jne .no_packet
1159
1160                 ; Got packet - reset timeout
1161                 mov word [PktTimeout],PKT_TIMEOUT
1162
1163                 pop ax  ; Adjust stack
1164                 pop ax
1165
1166                 mov ax,[pxe_udp_read_pkt.rport]
1167                 mov [si+tftp_remoteport],ax
1168
1169                 ; filesize <- -1 == unknown
1170                 mov dword [si+tftp_filesize], -1
1171                 ; Default blksize unless blksize option negotiated
1172                 mov word [si+tftp_blksize], TFTP_BLOCKSIZE
1173
1174                 mov cx,[pxe_udp_read_pkt.buffersize]
1175                 sub cx,2                ; CX <- bytes after opcode
1176                 jb .failure             ; Garbled reply
1177
1178                 mov si,packet_buf
1179                 lodsw
1180
1181                 cmp ax, TFTP_ERROR
1182                 je .bailnow             ; ERROR reply: don't try again
1183
1184                 cmp ax, TFTP_OACK
1185                 jne .no_tsize
1186
1187                 ; Now we need to parse the OACK packet to get the transfer
1188                 ; size.  SI -> first byte of options; CX -> byte count
1189 .parse_oack:
1190                 jcxz .no_tsize                  ; No options acked
1191 .get_opt_name:
1192                 mov di,si
1193                 mov bx,si
1194 .opt_name_loop: lodsb
1195                 and al,al
1196                 jz .got_opt_name
1197                 or al,20h                       ; Convert to lowercase
1198                 stosb
1199                 loop .opt_name_loop
1200                 ; We ran out, and no final null
1201                 jmp .err_reply
1202 .got_opt_name:  ; si -> option value
1203                 dec cx                          ; bytes left in pkt
1204                 jz .err_reply                   ; Option w/o value
1205
1206                 ; Parse option pointed to by bx; guaranteed to be
1207                 ; null-terminated.
1208                 push cx
1209                 push si
1210                 mov si,bx                       ; -> option name
1211                 mov bx,tftp_opt_table
1212                 mov cx,tftp_opts
1213 .opt_loop:
1214                 push cx
1215                 push si
1216                 mov di,[bx]                     ; Option pointer
1217                 mov cx,[bx+2]                   ; Option len
1218                 repe cmpsb
1219                 pop si
1220                 pop cx
1221                 je .get_value                   ; OK, known option
1222                 add bx,6
1223                 loop .opt_loop
1224
1225                 pop si
1226                 pop cx
1227                 jmp .err_reply                  ; Non-negotiated option returned
1228
1229 .get_value:     pop si                          ; si -> option value
1230                 pop cx                          ; cx -> bytes left in pkt
1231                 mov bx,[bx+4]                   ; Pointer to data target
1232                 add bx,[bp-6]                   ; TFTP socket pointer
1233                 xor eax,eax
1234                 xor edx,edx
1235 .value_loop:    lodsb
1236                 and al,al
1237                 jz .got_value
1238                 sub al,'0'
1239                 cmp al, 9
1240                 ja .err_reply                   ; Not a decimal digit
1241                 imul edx,10
1242                 add edx,eax
1243                 mov [bx],edx
1244                 loop .value_loop
1245                 ; Ran out before final null, accept anyway
1246                 jmp short .done_pkt
1247
1248 .got_value:
1249                 dec cx
1250                 jnz .get_opt_name               ; Not end of packet
1251
1252                 ; ZF == 1
1253
1254                 ; Success, done!
1255 .done_pkt:
1256                 pop si                  ; Junk
1257                 pop si                  ; We want the packet ptr in SI
1258
1259                 mov eax,[si+tftp_filesize]
1260                 cmp eax,-1
1261                 jz .no_tsize
1262                 mov edx,eax
1263                 shr edx,16              ; DX:AX == EAX
1264
1265                 and eax,eax             ; Set ZF depending on file size
1266                 pop bp                  ; Junk
1267                 pop bp                  ; Junk (retry counter)
1268                 jz .error_si            ; ZF = 1 need to free the socket
1269 .ret:
1270                 pop bp
1271                 pop cx
1272                 pop bx
1273                 pop es
1274                 ret
1275
1276 .no_tsize:
1277 .err_reply:     ; Option negotiation error.  Send ERROR reply.
1278                 ; ServerIP and gateway are already programmed in
1279                 mov si,[bp-6]
1280                 mov ax,[si+tftp_remoteport]
1281                 mov word [pxe_udp_write_pkt.rport],ax
1282                 mov word [pxe_udp_write_pkt.buffer],tftp_opt_err
1283                 mov word [pxe_udp_write_pkt.buffersize],tftp_opt_err_len
1284                 mov di,pxe_udp_write_pkt
1285                 mov bx,PXENV_UDP_WRITE
1286                 call pxenv
1287
1288                 ; Write an error message and explode
1289                 mov si,err_oldtftp
1290                 call writestr
1291                 jmp kaboom
1292
1293 .bailnow:       mov word [bp-2],1       ; Immediate error - no retry
1294
1295 .failure:       pop bx                  ; Junk
1296                 pop bx
1297                 pop si
1298                 pop ax
1299                 dec ax                  ; Retry counter
1300                 jnz .sendreq            ; Try again
1301
1302 .error:         mov si,bx               ; Socket pointer
1303 .error_si:                              ; Socket pointer already in SI
1304                 call free_socket        ; ZF <- 1, SI <- 0
1305                 jmp .ret
1306
1307 ;
1308 ; allocate_socket: Allocate a local UDP port structure
1309 ;
1310 ;               If successful:
1311 ;                 ZF set
1312 ;                 BX     = socket pointer
1313 ;               If unsuccessful:
1314 ;                 ZF clear
1315 ;
1316 allocate_socket:
1317                 push cx
1318                 mov bx,Files
1319                 mov cx,MAX_OPEN
1320 .check:         cmp word [bx], byte 0
1321                 je .found
1322                 add bx,open_file_t_size
1323                 loop .check
1324                 xor cx,cx                       ; ZF = 1
1325                 pop cx
1326                 ret
1327                 ; Allocate a socket number.  Socket numbers are made
1328                 ; guaranteed unique by including the socket slot number
1329                 ; (inverted, because we use the loop counter cx); add a
1330                 ; counter value to keep the numbers from being likely to
1331                 ; get immediately reused.
1332                 ;
1333                 ; The NextSocket variable also contains the top two bits
1334                 ; set.  This generates a value in the range 49152 to
1335                 ; 57343.
1336 .found:
1337                 dec cx
1338                 push ax
1339                 mov ax,[NextSocket]
1340                 inc ax
1341                 and ax,((1 << (13-MAX_OPEN_LG2))-1) | 0xC000
1342                 mov [NextSocket],ax
1343                 shl cx,13-MAX_OPEN_LG2
1344                 add cx,ax                       ; ZF = 0
1345                 xchg ch,cl                      ; Convert to network byte order
1346                 mov [bx],cx                     ; Socket in use
1347                 pop ax
1348                 pop cx
1349                 ret
1350
1351 ;
1352 ; Free socket: socket in SI; return SI = 0, ZF = 1 for convenience
1353 ;
1354 free_socket:
1355                 push es
1356                 pusha
1357                 xor ax,ax
1358                 mov es,ax
1359                 mov di,si
1360                 mov cx,tftp_pktbuf >> 1         ; tftp_pktbuf is not cleared
1361                 rep stosw
1362                 popa
1363                 pop es
1364                 xor si,si
1365                 ret
1366
1367 ;
1368 ; parse_dotquad:
1369 ;               Read a dot-quad pathname in DS:SI and output an IP
1370 ;               address in EAX, with SI pointing to the first
1371 ;               nonmatching character.
1372 ;
1373 ;               Return CF=1 on error.
1374 ;
1375 ;               No segment assumptions permitted.
1376 ;
1377 parse_dotquad:
1378                 push cx
1379                 mov cx,4
1380                 xor eax,eax
1381 .parseloop:
1382                 mov ch,ah
1383                 mov ah,al
1384                 lodsb
1385                 sub al,'0'
1386                 jb .notnumeric
1387                 cmp al,9
1388                 ja .notnumeric
1389                 aad                             ; AL += 10 * AH; AH = 0;
1390                 xchg ah,ch
1391                 jmp .parseloop
1392 .notnumeric:
1393                 cmp al,'.'-'0'
1394                 pushf
1395                 mov al,ah
1396                 mov ah,ch
1397                 xor ch,ch
1398                 ror eax,8
1399                 popf
1400                 jne .error
1401                 loop .parseloop
1402                 jmp .done
1403 .error:
1404                 loop .realerror                 ; If CX := 1 then we're done
1405                 clc
1406                 jmp .done
1407 .realerror:
1408                 stc
1409 .done:
1410                 dec si                          ; CF unchanged!
1411                 pop cx
1412                 ret
1413 ;
1414 ; mangle_name: Mangle a filename pointed to by DS:SI into a buffer pointed
1415 ;              to by ES:DI; ends on encountering any whitespace.
1416 ;              DI is preserved.
1417 ;
1418 ;              This verifies that a filename is < FILENAME_MAX characters
1419 ;              and doesn't contain whitespace, and zero-pads the output buffer,
1420 ;              so "repe cmpsb" can do a compare.
1421 ;
1422 ;              The first four bytes of the manged name is the IP address of
1423 ;              the download host.
1424 ;
1425 ;              No segment assumptions permitted.
1426 ;
1427 mangle_name:
1428                 push di
1429                 push si
1430                 mov eax,[cs:ServerIP]
1431                 cmp byte [si],0
1432                 je .noip                        ; Null filename?!?!
1433                 cmp word [si],'::'              ; Leading ::?
1434                 je .gotprefix
1435
1436 .more:
1437                 inc si
1438                 cmp byte [si],0
1439                 je .noip
1440                 cmp word [si],'::'
1441                 jne .more
1442
1443                 ; We have a :: prefix of some sort, it could be either
1444                 ; a DNS name or a dot-quad IP address.  Try the dot-quad
1445                 ; first...
1446 .here:
1447                 pop si
1448                 push si
1449                 call parse_dotquad
1450                 jc .notdq
1451                 cmp word [si],'::'
1452                 je .gotprefix
1453 .notdq:
1454                 pop si
1455                 push si
1456                 call dns_resolv
1457                 cmp word [si],'::'
1458                 jne .noip
1459                 and eax,eax
1460                 jnz .gotprefix
1461
1462 .noip:
1463                 pop si
1464                 xor eax,eax
1465                 jmp .prefix_done
1466
1467 .gotprefix:
1468                 pop cx                          ; Adjust stack
1469                 inc si                          ; Skip double colon
1470                 inc si
1471
1472 .prefix_done:
1473                 stosd                           ; Save IP address prefix
1474                 mov cx,FILENAME_MAX-5
1475
1476 .mn_loop:
1477                 lodsb
1478                 cmp al,' '                      ; If control or space, end
1479                 jna .mn_end
1480                 stosb
1481                 loop .mn_loop
1482 .mn_end:
1483                 inc cx                          ; At least one null byte
1484                 xor ax,ax                       ; Zero-fill name
1485                 rep stosb                       ; Doesn't do anything if CX=0
1486                 pop di
1487                 ret                             ; Done
1488
1489 ;
1490 ; unmangle_name: Does the opposite of mangle_name; converts a DOS-mangled
1491 ;                filename to the conventional representation.  This is needed
1492 ;                for the BOOT_IMAGE= parameter for the kernel.
1493 ;
1494 ;                NOTE: The output buffer needs to be able to hold an
1495 ;                expanded IP address.
1496 ;
1497 ;                DS:SI -> input mangled file name
1498 ;                ES:DI -> output buffer
1499 ;
1500 ;                On return, DI points to the first byte after the output name,
1501 ;                which is set to a null byte.
1502 ;
1503 unmangle_name:
1504                 push eax
1505                 lodsd
1506                 and eax,eax
1507                 jz .noip
1508                 call gendotquad
1509                 mov ax,'::'
1510                 stosw
1511 .noip:
1512                 call strcpy
1513                 dec di                          ; Point to final null byte
1514                 pop eax
1515                 ret
1516
1517 ;
1518 ; pxenv
1519 ;
1520 ; This is the main PXENV+/!PXE entry point, using the PXENV+
1521 ; calling convention.  This is a separate local routine so
1522 ; we can hook special things from it if necessary.  In particular,
1523 ; some PXE stacks seem to not like being invoked from anything but
1524 ; the initial stack, so humour it.
1525 ;
1526
1527 pxenv:
1528 %if USE_PXE_PROVIDED_STACK == 0
1529                 mov [cs:PXEStack],sp
1530                 mov [cs:PXEStack+2],ss
1531                 lss sp,[cs:InitStack]
1532 %endif
1533 .jump:          call 0:pxe_thunk                ; Default to calling the thunk
1534 %if USE_PXE_PROVIDED_STACK == 0
1535                 lss sp,[cs:PXEStack]
1536 %endif
1537                 cld                             ; Make sure DF <- 0
1538                 ret
1539
1540 ; Must be after function def due to NASM bug
1541 PXENVEntry      equ pxenv.jump+1
1542
1543 ;
1544 ; pxe_thunk
1545 ;
1546 ; Convert from the PXENV+ calling convention (BX, ES, DI) to the !PXE
1547 ; calling convention (using the stack.)
1548 ;
1549 ; This is called as a far routine so that we can just stick it into
1550 ; the PXENVEntry variable.
1551 ;
1552 pxe_thunk:      push es
1553                 push di
1554                 push bx
1555 .jump:          call 0:0
1556                 add sp,byte 6
1557                 cmp ax,byte 1
1558                 cmc                             ; Set CF unless ax == 0
1559                 retf
1560
1561 ; Must be after function def due to NASM bug
1562 PXEEntry        equ pxe_thunk.jump+1
1563
1564 ;
1565 ; getfssec: Get multiple clusters from a file, given the starting cluster.
1566 ;
1567 ;       In this case, get multiple blocks from a specific TCP connection.
1568 ;
1569 ;  On entry:
1570 ;       ES:BX   -> Buffer
1571 ;       SI      -> TFTP socket pointer
1572 ;       CX      -> 512-byte block count; 0FFFFh = until end of file
1573 ;  On exit:
1574 ;       SI      -> TFTP socket pointer (or 0 on EOF)
1575 ;       CF = 1  -> Hit EOF
1576 ;
1577 getfssec:       push si
1578                 push fs
1579                 mov di,bx
1580                 mov bx,si
1581                 mov ax,pktbuf_seg
1582                 mov fs,ax
1583
1584                 movzx ecx,cx
1585                 shl ecx,TFTP_BLOCKSIZE_LG2      ; Convert to bytes
1586                 jz .hit_eof                     ; Nothing to do?
1587
1588 .need_more:
1589                 push ecx
1590
1591                 movzx eax,word [bx+tftp_bytesleft]
1592                 cmp ecx,eax
1593                 jna .ok_size
1594                 mov ecx,eax
1595                 jcxz .need_packet               ; No bytes available?
1596 .ok_size:
1597
1598                 mov ax,cx                       ; EAX<31:16> == ECX<31:16> == 0
1599                 mov si,[bx+tftp_dataptr]
1600                 sub [bx+tftp_bytesleft],cx
1601                 fs rep movsb                    ; Copy from packet buffer
1602                 mov [bx+tftp_dataptr],si
1603
1604                 pop ecx
1605                 sub ecx,eax
1606                 jnz .need_more
1607
1608
1609 .hit_eof:
1610                 pop fs
1611                 pop si
1612
1613                 ; Is there anything left of this?
1614                 mov eax,[si+tftp_filesize]
1615                 sub eax,[si+tftp_filepos]
1616                 jnz .bytes_left ; CF <- 0
1617
1618                 cmp [si+tftp_bytesleft],ax
1619                 jnz .bytes_left ; CF <- 0
1620
1621                 ; The socket is closed and the buffer drained
1622                 ; Close socket structure and re-init for next user
1623                 call free_socket
1624                 stc
1625 .bytes_left:
1626                 ret
1627
1628 ;
1629 ; No data in buffer, check to see if we can get a packet...
1630 ;
1631 .need_packet:
1632                 pop ecx
1633                 mov eax,[bx+tftp_filesize]
1634                 cmp eax,[bx+tftp_filepos]
1635                 je .hit_eof                     ; Already EOF'd; socket already closed
1636
1637                 pushad
1638                 push es
1639                 mov si,bx
1640                 call get_packet
1641                 pop es
1642                 popad
1643
1644                 jmp .need_more
1645
1646 ;
1647 ; Get a fresh packet; expects fs -> pktbuf_seg and ds:si -> socket structure
1648 ;
1649 get_packet:
1650                 mov ax,ds
1651                 mov es,ax
1652
1653 .packet_loop:
1654                 ; Start by ACKing the previous packet; this should cause the
1655                 ; next packet to be sent.
1656                 mov cx,PKT_RETRY
1657                 mov word [PktTimeout],PKT_TIMEOUT
1658
1659 .send_ack:      push cx                         ; <D> Retry count
1660
1661                 mov ax,[si+tftp_lastpkt]
1662                 call ack_packet                 ; Send ACK
1663
1664                 ; We used to test the error code here, but sometimes
1665                 ; PXE would return negative status even though we really
1666                 ; did send the ACK.  Now, just treat a failed send as
1667                 ; a normally lost packet, and let it time out in due
1668                 ; course of events.
1669
1670 .send_ok:       ; Now wait for packet.
1671                 mov dx,[BIOS_timer]             ; Get current time
1672
1673                 mov cx,[PktTimeout]
1674 .wait_data:     push cx                         ; <E> Timeout
1675                 push dx                         ; <F> Old time
1676
1677                 mov bx,[si+tftp_pktbuf]
1678                 mov [pxe_udp_read_pkt.buffer],bx
1679                 mov [pxe_udp_read_pkt.buffer+2],fs
1680                 mov [pxe_udp_read_pkt.buffersize],word PKTBUF_SIZE
1681                 mov eax,[si+tftp_remoteip]
1682                 mov [pxe_udp_read_pkt.sip],eax
1683                 mov eax,[MyIP]
1684                 mov [pxe_udp_read_pkt.dip],eax
1685                 mov ax,[si+tftp_remoteport]
1686                 mov [pxe_udp_read_pkt.rport],ax
1687                 mov ax,[si+tftp_localport]
1688                 mov [pxe_udp_read_pkt.lport],ax
1689                 mov di,pxe_udp_read_pkt
1690                 mov bx,PXENV_UDP_READ
1691                 push si                         ; <G>
1692                 call pxenv
1693                 pop si                          ; <G>
1694                 and ax,ax
1695                 jz .recv_ok
1696
1697                 ; No packet, or receive failure
1698                 mov dx,[BIOS_timer]
1699                 pop ax                          ; <F> Old time
1700                 pop cx                          ; <E> Timeout
1701                 cmp ax,dx                       ; Same time -> don't advance timeout
1702                 je .wait_data                   ; Same clock tick
1703                 loop .wait_data                 ; Decrease timeout
1704
1705                 pop cx                          ; <D> Didn't get any, send another ACK
1706                 shl word [PktTimeout],1         ; Exponential backoff
1707                 loop .send_ack
1708                 jmp kaboom                      ; Forget it...
1709
1710 .recv_ok:       pop dx                          ; <F>
1711                 pop cx                          ; <E>
1712
1713                 cmp word [pxe_udp_read_pkt.buffersize],byte 4
1714                 jb .wait_data                   ; Bad size for a DATA packet
1715
1716                 mov bx,[si+tftp_pktbuf]
1717                 cmp word [fs:bx],TFTP_DATA      ; Not a data packet?
1718                 jne .wait_data                  ; Then wait for something else
1719
1720                 mov ax,[si+tftp_lastpkt]
1721                 xchg ah,al                      ; Host byte order
1722                 inc ax                          ; Which packet are we waiting for?
1723                 xchg ah,al                      ; Network byte order
1724                 cmp [fs:bx+2],ax
1725                 je .right_packet
1726
1727                 ; Wrong packet, ACK the packet and then try again
1728                 ; This is presumably because the ACK got lost,
1729                 ; so the server just resent the previous packet
1730                 mov ax,[fs:bx+2]
1731                 call ack_packet
1732                 jmp .send_ok                    ; Reset timeout
1733
1734 .right_packet:  ; It's the packet we want.  We're also EOF if the size < blocksize
1735
1736                 pop cx                          ; <D> Don't need the retry count anymore
1737
1738                 mov [si+tftp_lastpkt],ax        ; Update last packet number
1739
1740                 movzx ecx,word [pxe_udp_read_pkt.buffersize]
1741                 sub cx,byte 4                   ; Skip TFTP header
1742
1743                 ; If this is a zero-length block, don't mess with the pointers,
1744                 ; since we may have just set up the previous block that way
1745                 jz .last_block
1746
1747                 ; Set pointer to data block
1748                 lea ax,[bx+4]                   ; Data past TFTP header
1749                 mov [si+tftp_dataptr],ax
1750
1751                 add [si+tftp_filepos],ecx
1752                 mov [si+tftp_bytesleft],cx
1753
1754                 cmp cx,[si+tftp_blksize]        ; Is it a full block?
1755                 jb .last_block                  ; If so, it's not EOF
1756
1757                 ; If we had the exact right number of bytes, always get
1758                 ; one more packet to get the (zero-byte) EOF packet and
1759                 ; close the socket.
1760                 mov eax,[si+tftp_filepos]
1761                 cmp [si+tftp_filesize],eax
1762                 je .packet_loop
1763
1764                 ret
1765
1766
1767 .last_block:    ; Last block - ACK packet immediately
1768                 mov ax,[fs:bx+2]
1769                 call ack_packet
1770
1771                 ; Make sure we know we are at end of file
1772                 mov eax,[si+tftp_filepos]
1773                 mov [si+tftp_filesize],eax
1774
1775                 ret
1776
1777 ;
1778 ; ack_packet:
1779 ;
1780 ; Send ACK packet.  This is a common operation and so is worth canning.
1781 ;
1782 ; Entry:
1783 ;       SI      = TFTP block
1784 ;       AX      = Packet # to ack (network byte order)
1785 ; Exit:
1786 ;       ZF = 0 -> Error
1787 ;       All registers preserved
1788 ;
1789 ; This function uses the pxe_udp_write_pkt but not the packet_buf.
1790 ;
1791 ack_packet:
1792                 pushad
1793                 mov [ack_packet_buf+2],ax       ; Packet number to ack
1794                 mov ax,[si]
1795                 mov [pxe_udp_write_pkt.lport],ax
1796                 mov ax,[si+tftp_remoteport]
1797                 mov [pxe_udp_write_pkt.rport],ax
1798                 mov eax,[si+tftp_remoteip]
1799                 mov [pxe_udp_write_pkt.sip],eax
1800                 xor eax,[MyIP]
1801                 and eax,[Netmask]
1802                 jz .nogw
1803                 mov eax,[Gateway]
1804 .nogw:
1805                 mov [pxe_udp_write_pkt.gip],eax
1806                 mov [pxe_udp_write_pkt.buffer],word ack_packet_buf
1807                 mov [pxe_udp_write_pkt.buffersize], word 4
1808                 mov di,pxe_udp_write_pkt
1809                 mov bx,PXENV_UDP_WRITE
1810                 call pxenv
1811                 cmp ax,byte 0                   ; ZF = 1 if write OK
1812                 popad
1813                 ret
1814
1815 ;
1816 ; unload_pxe:
1817 ;
1818 ; This function unloads the PXE and UNDI stacks and unclaims
1819 ; the memory.
1820 ;
1821 unload_pxe:
1822                 test byte [KeepPXE],01h         ; Should we keep PXE around?
1823                 jnz reset_pxe
1824
1825                 push ds
1826                 push es
1827
1828                 mov ax,cs
1829                 mov ds,ax
1830                 mov es,ax
1831
1832                 mov si,new_api_unload
1833                 cmp byte [APIVer+1],2           ; Major API version >= 2?
1834                 jae .new_api
1835                 mov si,old_api_unload
1836 .new_api:
1837
1838 .call_loop:     xor ax,ax
1839                 lodsb
1840                 and ax,ax
1841                 jz .call_done
1842                 xchg bx,ax
1843                 mov di,pxe_unload_stack_pkt
1844                 push di
1845                 xor ax,ax
1846                 mov cx,pxe_unload_stack_pkt_len >> 1
1847                 rep stosw
1848                 pop di
1849                 call pxenv
1850                 jc .cant_free
1851                 mov ax,word [pxe_unload_stack_pkt.status]
1852                 cmp ax,PXENV_STATUS_SUCCESS
1853                 jne .cant_free
1854                 jmp .call_loop
1855
1856 .call_done:
1857                 mov bx,0FF00h
1858
1859                 mov dx,[RealBaseMem]
1860                 cmp dx,[BIOS_fbm]               ; Sanity check
1861                 jna .cant_free
1862                 inc bx
1863
1864                 ; Check that PXE actually unhooked the INT 1Ah chain
1865                 movzx eax,word [4*0x1a]
1866                 movzx ecx,word [4*0x1a+2]
1867                 shl ecx,4
1868                 add eax,ecx
1869                 shr eax,10
1870                 cmp ax,dx                       ; Not in range
1871                 jae .ok
1872                 cmp ax,[BIOS_fbm]
1873                 jae .cant_free
1874                 ; inc bx
1875
1876 .ok:
1877                 mov [BIOS_fbm],dx
1878 .pop_ret:
1879                 pop es
1880                 pop ds
1881                 ret
1882
1883 .cant_free:
1884                 mov si,cant_free_msg
1885                 call writestr
1886                 push ax
1887                 xchg bx,ax
1888                 call writehex4
1889                 mov al,'-'
1890                 call writechr
1891                 pop ax
1892                 call writehex4
1893                 mov al,'-'
1894                 call writechr
1895                 mov eax,[4*0x1a]
1896                 call writehex8
1897                 call crlf
1898                 jmp .pop_ret
1899
1900                 ; We want to keep PXE around, but still we should reset
1901                 ; it to the standard bootup configuration
1902 reset_pxe:
1903                 push es
1904                 push cs
1905                 pop es
1906                 mov bx,PXENV_UDP_CLOSE
1907                 mov di,pxe_udp_close_pkt
1908                 call pxenv
1909                 pop es
1910                 ret
1911
1912 ;
1913 ; gendotquad
1914 ;
1915 ; Take an IP address (in network byte order) in EAX and
1916 ; output a dotted quad string to ES:DI.
1917 ; DI points to terminal null at end of string on exit.
1918 ;
1919 gendotquad:
1920                 push eax
1921                 push cx
1922                 mov cx,4
1923 .genchar:
1924                 push eax
1925                 cmp al,10               ; < 10?
1926                 jb .lt10                ; If so, skip first 2 digits
1927
1928                 cmp al,100              ; < 100
1929                 jb .lt100               ; If so, skip first digit
1930
1931                 aam 100
1932                 ; Now AH = 100-digit; AL = remainder
1933                 add ah,'0'
1934                 mov [es:di],ah
1935                 inc di
1936
1937 .lt100:
1938                 aam 10
1939                 ; Now AH = 10-digit; AL = remainder
1940                 add ah,'0'
1941                 mov [es:di],ah
1942                 inc di
1943
1944 .lt10:
1945                 add al,'0'
1946                 stosb
1947                 mov al,'.'
1948                 stosb
1949                 pop eax
1950                 ror eax,8       ; Move next char into LSB
1951                 loop .genchar
1952                 dec di
1953                 mov [es:di], byte 0
1954                 pop cx
1955                 pop eax
1956                 ret
1957 ;
1958 ; uchexbytes/lchexbytes
1959 ;
1960 ; Take a number of bytes in memory and convert to upper/lower-case
1961 ; hexadecimal
1962 ;
1963 ; Input:
1964 ;       DS:SI   = input bytes
1965 ;       ES:DI   = output buffer
1966 ;       CX      = number of bytes
1967 ; Output:
1968 ;       DS:SI   = first byte after
1969 ;       ES:DI   = first byte after
1970 ;       CX = 0
1971 ;
1972 ; Trashes AX, DX
1973 ;
1974
1975 lchexbytes:
1976         mov dl,'a'-'9'-1
1977         jmp xchexbytes
1978 uchexbytes:
1979         mov dl,'A'-'9'-1
1980 xchexbytes:
1981 .loop:
1982         lodsb
1983         mov ah,al
1984         shr al,4
1985         call .outchar
1986         mov al,ah
1987         call .outchar
1988         loop .loop
1989         ret
1990 .outchar:
1991         and al,0Fh
1992         add al,'0'
1993         cmp al,'9'
1994         jna .done
1995         add al,dl
1996 .done:
1997         stosb
1998         ret
1999
2000 ;
2001 ; pxe_get_cached_info
2002 ;
2003 ; Get a DHCP packet from the PXE stack into the trackbuf.
2004 ;
2005 ; Input:
2006 ;       DL = packet type
2007 ; Output:
2008 ;       CX = buffer size
2009 ;
2010 ; Assumes CS == DS == ES.
2011 ;
2012 pxe_get_cached_info:
2013                 pushad
2014                 mov di,pxe_bootp_query_pkt
2015                 push di
2016                 xor ax,ax
2017                 stosw           ; Status
2018                 movzx ax,dl
2019                 stosw           ; Packet type
2020                 mov ax,trackbufsize
2021                 stosw           ; Buffer size
2022                 mov ax,trackbuf
2023                 stosw           ; Buffer offset
2024                 xor ax,ax
2025                 stosw           ; Buffer segment
2026
2027                 pop di          ; DI -> parameter set
2028                 mov bx,PXENV_GET_CACHED_INFO
2029                 call pxenv
2030                 jc .err
2031                 and ax,ax
2032                 jnz .err
2033
2034                 popad
2035                 mov cx,[pxe_bootp_query_pkt.buffersize]
2036                 ret
2037
2038 .err:
2039                 mov si,err_pxefailed
2040                 jmp kaboom
2041
2042 ;
2043 ; parse_dhcp
2044 ;
2045 ; Parse a DHCP packet.  This includes dealing with "overloaded"
2046 ; option fields (see RFC 2132, section 9.3)
2047 ;
2048 ; This should fill in the following global variables, if the
2049 ; information is present:
2050 ;
2051 ; MyIP          - client IP address
2052 ; ServerIP      - boot server IP address
2053 ; Netmask       - network mask
2054 ; Gateway       - default gateway router IP
2055 ; BootFile      - boot file name
2056 ; DNSServers    - DNS server IPs
2057 ; LocalDomain   - Local domain name
2058 ; MACLen, MAC   - Client identifier, if MACLen == 0
2059 ;
2060 ; This assumes the DHCP packet is in "trackbuf" and the length
2061 ; of the packet in in CX on entry.
2062 ;
2063
2064 parse_dhcp:
2065                 mov byte [OverLoad],0           ; Assume no overload
2066                 mov eax, [trackbuf+bootp.yip]
2067                 and eax, eax
2068                 jz .noyip
2069                 cmp al,224                      ; Class D or higher -> bad
2070                 jae .noyip
2071                 mov [MyIP], eax
2072 .noyip:
2073                 mov eax, [trackbuf+bootp.sip]
2074                 and eax, eax
2075                 jz .nosip
2076                 cmp al,224                      ; Class D or higher -> bad
2077                 jae .nosip
2078                 mov [ServerIP], eax
2079 .nosip:
2080                 sub cx, bootp.options
2081                 jbe .nooptions
2082                 mov si, trackbuf+bootp.option_magic
2083                 lodsd
2084                 cmp eax, BOOTP_OPTION_MAGIC
2085                 jne .nooptions
2086                 call parse_dhcp_options
2087 .nooptions:
2088                 mov si, trackbuf+bootp.bootfile
2089                 test byte [OverLoad],1
2090                 jz .nofileoverload
2091                 mov cx,128
2092                 call parse_dhcp_options
2093                 jmp short .parsed_file
2094 .nofileoverload:
2095                 cmp byte [si], 0
2096                 jz .parsed_file                 ; No bootfile name
2097                 mov di,BootFile
2098                 mov cx,32
2099                 rep movsd
2100                 xor al,al
2101                 stosb                           ; Null-terminate
2102 .parsed_file:
2103                 mov si, trackbuf+bootp.sname
2104                 test byte [OverLoad],2
2105                 jz .nosnameoverload
2106                 mov cx,64
2107                 call parse_dhcp_options
2108 .nosnameoverload:
2109                 ret
2110
2111 ;
2112 ; Parse a sequence of DHCP options, pointed to by DS:SI; the field
2113 ; size is CX -- some DHCP servers leave option fields unterminated
2114 ; in violation of the spec.
2115 ;
2116 ; For parse_some_dhcp_options, DH contains the minimum value for
2117 ; the option to recognize -- this is used to restrict parsing to
2118 ; PXELINUX-specific options only.
2119 ;
2120 parse_dhcp_options:
2121                 xor dx,dx
2122
2123 parse_some_dhcp_options:
2124 .loop:
2125                 and cx,cx
2126                 jz .done
2127
2128                 lodsb
2129                 dec cx
2130                 jz .done        ; Last byte; must be PAD, END or malformed
2131                 cmp al, 0       ; PAD option
2132                 je .loop
2133                 cmp al,255      ; END option
2134                 je .done
2135
2136                 ; Anything else will have a length field
2137                 mov dl,al       ; DL <- option number
2138                 xor ax,ax
2139                 lodsb           ; AX <- option length
2140                 dec cx
2141                 sub cx,ax       ; Decrement bytes left counter
2142                 jb .done        ; Malformed option: length > field size
2143
2144                 cmp dl,dh       ; Is the option value valid?
2145                 jb .opt_done
2146
2147                 mov bx,dhcp_option_list
2148 .find_option:
2149                 cmp bx,dhcp_option_list_end
2150                 jae .opt_done
2151                 cmp dl,[bx]
2152                 je .found_option
2153                 add bx,3
2154                 jmp .find_option
2155 .found_option:
2156                 pushad
2157                 call [bx+1]
2158                 popad
2159
2160 ; Fall through
2161                 ; Unknown option.  Skip to the next one.
2162 .opt_done:
2163                 add si,ax
2164                 jmp .loop
2165 .done:
2166                 ret
2167
2168                 section .data
2169 dhcp_option_list:
2170                 section .text
2171
2172 %macro dopt 2
2173                 section .data
2174                 db %1
2175                 dw dopt_%2
2176                 section .text
2177 dopt_%2:
2178 %endmacro
2179
2180 ;
2181 ; Parse individual DHCP options.  SI points to the option data and
2182 ; AX to the option length.  DL contains the option number.
2183 ; All registers are saved around the routine.
2184 ;
2185         dopt 1, subnet_mask
2186                 mov ebx,[si]
2187                 mov [Netmask],ebx
2188                 ret
2189
2190         dopt 3, router
2191                 mov ebx,[si]
2192                 mov [Gateway],ebx
2193                 ret
2194
2195         dopt 6, dns_servers
2196                 mov cx,ax
2197                 shr cx,2
2198                 cmp cl,DNS_MAX_SERVERS
2199                 jna .oklen
2200                 mov cl,DNS_MAX_SERVERS
2201 .oklen:
2202                 mov di,DNSServers
2203                 rep movsd
2204                 mov [LastDNSServer],di
2205                 ret
2206
2207         dopt 16, local_domain
2208                 mov bx,si
2209                 add bx,ax
2210                 xor ax,ax
2211                 xchg [bx],al    ; Zero-terminate option
2212                 mov di,LocalDomain
2213                 call dns_mangle ; Convert to DNS label set
2214                 mov [bx],al     ; Restore ending byte
2215                 ret
2216
2217         dopt 43, vendor_encaps
2218                 mov dh,208      ; Only recognize PXELINUX options
2219                 mov cx,ax       ; Length of option = max bytes to parse
2220                 call parse_some_dhcp_options    ; Parse recursive structure
2221                 ret
2222
2223         dopt 52, option_overload
2224                 mov bl,[si]
2225                 mov [OverLoad],bl
2226                 ret
2227
2228         dopt 54, server
2229                 mov eax,[si]
2230                 cmp dword [ServerIP],0
2231                 jne .skip               ; Already have a next server IP
2232                 cmp al,224              ; Class D or higher
2233                 jae .skip
2234                 mov [ServerIP],eax
2235 .skip:          ret
2236
2237         dopt 61, client_identifier
2238                 cmp ax,MAC_MAX          ; Too long?
2239                 ja .skip
2240                 cmp ax,2                ; Too short?
2241                 jb .skip
2242                 cmp [MACLen],ah         ; Only do this if MACLen == 0
2243                 jne .skip
2244                 push ax
2245                 lodsb                   ; Client identifier type
2246                 cmp al,[MACType]
2247                 pop ax
2248                 jne .skip               ; Client identifier is not a MAC
2249                 dec ax
2250                 mov [MACLen],al
2251                 mov di,MAC
2252                 jmp dhcp_copyoption
2253 .skip:          ret
2254
2255         dopt 67, bootfile_name
2256                 mov di,BootFile
2257                 jmp dhcp_copyoption
2258
2259         dopt 97, uuid_client_identifier
2260                 cmp ax,17               ; type byte + 16 bytes UUID
2261                 jne .skip
2262                 mov dl,[si]             ; Must have type 0 == UUID
2263                 or dl,[HaveUUID]        ; Capture only the first instance
2264                 jnz .skip
2265                 mov byte [HaveUUID],1   ; Got UUID
2266                 mov di,UUIDType
2267                 jmp dhcp_copyoption
2268 .skip:          ret
2269
2270         dopt 209, pxelinux_configfile
2271                 mov di,ConfigName
2272                 or byte [DHCPMagic],2   ; Got config file
2273                 jmp dhcp_copyoption
2274
2275         dopt 210, pxelinux_pathprefix
2276                 mov di,PathPrefix
2277                 or byte [DHCPMagic],4   ; Got path prefix
2278                 jmp dhcp_copyoption
2279
2280         dopt 211, pxelinux_reboottime
2281                 cmp al,4
2282                 jne .done
2283                 mov ebx,[si]
2284                 xchg bl,bh              ; Convert to host byte order
2285                 rol ebx,16
2286                 xchg bl,bh
2287                 mov [RebootTime],ebx
2288                 or byte [DHCPMagic],8   ; Got RebootTime
2289 .done:          ret
2290
2291                 ; Common code for copying an option verbatim
2292                 ; Copies the option into ES:DI and null-terminates it.
2293                 ; Returns with AX=0 and SI past the option.
2294 dhcp_copyoption:
2295                 xchg cx,ax      ; CX <- option length
2296                 rep movsb
2297                 xchg cx,ax      ; AX <- 0
2298                 stosb           ; Null-terminate
2299                 ret
2300
2301                 section .data
2302 dhcp_option_list_end:
2303                 section .text
2304
2305                 section .data
2306 HaveUUID        db 0
2307 uuid_dashes     db 4,2,2,2,6,0  ; Bytes per UUID dashed section
2308                 section .text
2309
2310 ;
2311 ; genipopt
2312 ;
2313 ; Generate an ip=<client-ip>:<boot-server-ip>:<gw-ip>:<netmask>
2314 ; option into IPOption based on a DHCP packet in trackbuf.
2315 ; Assumes CS == DS == ES.
2316 ;
2317 genipopt:
2318                 pushad
2319                 mov di,IPOption
2320                 mov eax,'ip='
2321                 stosd
2322                 dec di
2323                 mov eax,[MyIP]
2324                 call gendotquad
2325                 mov al,':'
2326                 stosb
2327                 mov eax,[ServerIP]
2328                 call gendotquad
2329                 mov al,':'
2330                 stosb
2331                 mov eax,[Gateway]
2332                 call gendotquad
2333                 mov al,':'
2334                 stosb
2335                 mov eax,[Netmask]
2336                 call gendotquad ; Zero-terminates its output
2337                 sub di,IPOption
2338                 mov [IPOptionLen],di
2339                 popad
2340                 ret
2341
2342 ;
2343 ; Call the receive loop while idle.  This is done mostly so we can respond to
2344 ; ARP messages, but perhaps in the future this can be used to do network
2345 ; console.
2346 ;
2347 ; hpa sez: people using automatic control on the serial port get very
2348 ; unhappy if we poll for ARP too often (the PXE stack is pretty slow,
2349 ; typically.)  Therefore, only poll if at least 4 BIOS timer ticks have
2350 ; passed since the last poll, and reset this when a character is
2351 ; received (RESET_IDLE).
2352 ;
2353 %if HAVE_IDLE
2354
2355 reset_idle:
2356                 push ax
2357                 mov ax,[cs:BIOS_timer]
2358                 mov [cs:IdleTimer],ax
2359                 pop ax
2360                 ret
2361
2362 check_for_arp:
2363                 push ax
2364                 mov ax,[cs:BIOS_timer]
2365                 sub ax,[cs:IdleTimer]
2366                 cmp ax,4
2367                 pop ax
2368                 jae .need_poll
2369                 ret
2370 .need_poll:     pushad
2371                 push ds
2372                 push es
2373                 mov ax,cs
2374                 mov ds,ax
2375                 mov es,ax
2376                 mov di,packet_buf
2377                 mov [pxe_udp_read_pkt.status],al        ; 0
2378                 mov [pxe_udp_read_pkt.buffer],di
2379                 mov [pxe_udp_read_pkt.buffer+2],ds
2380                 mov word [pxe_udp_read_pkt.buffersize],packet_buf_size
2381                 mov eax,[MyIP]
2382                 mov [pxe_udp_read_pkt.dip],eax
2383                 mov word [pxe_udp_read_pkt.lport],htons(9)      ; discard port
2384                 mov di,pxe_udp_read_pkt
2385                 mov bx,PXENV_UDP_READ
2386                 call pxenv
2387                 ; Ignore result...
2388                 pop es
2389                 pop ds
2390                 popad
2391                 RESET_IDLE
2392                 ret
2393
2394 %endif ; HAVE_IDLE
2395
2396 ; -----------------------------------------------------------------------------
2397 ;  Common modules
2398 ; -----------------------------------------------------------------------------
2399
2400 %include "getc.inc"             ; getc et al
2401 %include "conio.inc"            ; Console I/O
2402 %include "writestr.inc"         ; String output
2403 writestr        equ cwritestr
2404 %include "writehex.inc"         ; Hexadecimal output
2405 %include "configinit.inc"       ; Initialize configuration
2406 %include "parseconfig.inc"      ; High-level config file handling
2407 %include "parsecmd.inc"         ; Low-level config file handling
2408 %include "bcopy32.inc"          ; 32-bit bcopy
2409 %include "loadhigh.inc"         ; Load a file into high memory
2410 %include "font.inc"             ; VGA font stuff
2411 %include "graphics.inc"         ; VGA graphics
2412 %include "highmem.inc"          ; High memory sizing
2413 %include "strcpy.inc"           ; strcpy()
2414 %include "rawcon.inc"           ; Console I/O w/o using the console functions
2415 %include "dnsresolv.inc"        ; DNS resolver
2416 %include "adv.inc"              ; Auxillary Data Vector
2417
2418 ; -----------------------------------------------------------------------------
2419 ;  Begin data section
2420 ; -----------------------------------------------------------------------------
2421
2422                 section .data
2423
2424 copyright_str   db ' Copyright (C) 1994-', year, ' H. Peter Anvin'
2425                 db CR, LF, 0
2426 err_bootfailed  db CR, LF, 'Boot failed: press a key to retry, or wait for reset...', CR, LF, 0
2427 bailmsg         equ err_bootfailed
2428 err_nopxe       db "No !PXE or PXENV+ API found; we're dead...", CR, LF, 0
2429 err_pxefailed   db 'PXE API call failed, error ', 0
2430 err_udpinit     db 'Failed to initialize UDP stack', CR, LF, 0
2431 err_noconfig    db 'Unable to locate configuration file', CR, LF, 0
2432 err_oldtftp     db 'TFTP server does not support the tsize option', CR, LF, 0
2433 found_pxenv     db 'Found PXENV+ structure', CR, LF, 0
2434 using_pxenv_msg db 'Old PXE API detected, using PXENV+ structure', CR, LF, 0
2435 apiver_str      db 'PXE API version is ',0
2436 pxeentry_msg    db 'PXE entry point found (we hope) at ', 0
2437 pxenventry_msg  db 'PXENV entry point found (we hope) at ', 0
2438 trymempxe_msg   db 'Scanning memory for !PXE structure... ', 0
2439 trymempxenv_msg db 'Scanning memory for PXENV+ structure... ', 0
2440 undi_data_msg     db 'UNDI data segment at:   ',0
2441 undi_data_len_msg db 'UNDI data segment size: ',0
2442 undi_code_msg     db 'UNDI code segment at:   ',0
2443 undi_code_len_msg db 'UNDI code segment size: ',0
2444 cant_free_msg   db 'Failed to free base memory, error ', 0
2445 notfound_msg    db 'not found', CR, LF, 0
2446 myipaddr_msg    db 'My IP address seems to be ',0
2447 tftpprefix_msg  db 'TFTP prefix: ', 0
2448 localboot_msg   db 'Booting from local disk...', CR, LF, 0
2449 trying_msg      db 'Trying to load: ', 0
2450 fourbs_msg      db BS, BS, BS, BS, 0
2451 default_str     db 'default', 0
2452 syslinux_banner db CR, LF, 'PXELINUX ', version_str, ' ', date, ' ', 0
2453 cfgprefix       db 'pxelinux.cfg/'              ; No final null!
2454 cfgprefix_len   equ ($-cfgprefix)
2455
2456 ;
2457 ; Command line options we'd like to take a look at
2458 ;
2459 ; mem= and vga= are handled as normal 32-bit integer values
2460 initrd_cmd      db 'initrd='
2461 initrd_cmd_len  equ $-initrd_cmd
2462
2463 ; This one we make ourselves
2464 bootif_str      db 'BOOTIF='
2465 bootif_str_len  equ $-bootif_str
2466 ;
2467 ; Config file keyword table
2468 ;
2469 %include "keywords.inc"
2470
2471 ;
2472 ; Extensions to search for (in *forward* order).
2473 ; (.bs and .bss are disabled for PXELINUX, since they are not supported)
2474 ;
2475                 align 4, db 0
2476 exten_table:    db '.cbt'               ; COMBOOT (specific)
2477                 db '.0', 0, 0           ; PXE bootstrap program
2478                 db '.com'               ; COMBOOT (same as DOS)
2479                 db '.c32'               ; COM32
2480 exten_table_end:
2481                 dd 0, 0                 ; Need 8 null bytes here
2482
2483 ;
2484 ; PXE unload sequences
2485 ;
2486 new_api_unload:
2487                 db PXENV_UDP_CLOSE
2488                 db PXENV_UNDI_SHUTDOWN
2489                 db PXENV_UNLOAD_STACK
2490                 db PXENV_STOP_UNDI
2491                 db 0
2492 old_api_unload:
2493                 db PXENV_UDP_CLOSE
2494                 db PXENV_UNDI_SHUTDOWN
2495                 db PXENV_UNLOAD_STACK
2496                 db PXENV_UNDI_CLEANUP
2497                 db 0
2498
2499 ;
2500 ; PXE query packets partially filled in
2501 ;
2502                 section .bss
2503 pxe_bootp_query_pkt:
2504 .status:        resw 1                  ; Status
2505 .packettype:    resw 1                  ; Boot server packet type
2506 .buffersize:    resw 1                  ; Packet size
2507 .buffer:        resw 2                  ; seg:off of buffer
2508 .bufferlimit:   resw 1                  ; Unused
2509
2510                 section .data
2511 pxe_udp_open_pkt:
2512 .status:        dw 0                    ; Status
2513 .sip:           dd 0                    ; Source (our) IP
2514
2515 pxe_udp_close_pkt:
2516 .status:        dw 0                    ; Status
2517
2518 pxe_udp_write_pkt:
2519 .status:        dw 0                    ; Status
2520 .sip:           dd 0                    ; Server IP
2521 .gip:           dd 0                    ; Gateway IP
2522 .lport:         dw 0                    ; Local port
2523 .rport:         dw 0                    ; Remote port
2524 .buffersize:    dw 0                    ; Size of packet
2525 .buffer:        dw 0, 0                 ; seg:off of buffer
2526
2527 pxe_udp_read_pkt:
2528 .status:        dw 0                    ; Status
2529 .sip:           dd 0                    ; Source IP
2530 .dip:           dd 0                    ; Destination (our) IP
2531 .rport:         dw 0                    ; Remote port
2532 .lport:         dw 0                    ; Local port
2533 .buffersize:    dw 0                    ; Max packet size
2534 .buffer:        dw 0, 0                 ; seg:off of buffer
2535
2536 ;
2537 ; Misc initialized (data) variables
2538 ;
2539                 alignb 4, db 0
2540 BaseStack       dd StackBuf             ; ESP of base stack
2541                 dw 0                    ; SS of base stack
2542 NextSocket      dw 49152                ; Counter for allocating socket numbers
2543 KeepPXE         db 0                    ; Should PXE be kept around?
2544
2545 ;
2546 ; TFTP commands
2547 ;
2548 tftp_tail       db 'octet', 0                           ; Octet mode
2549 tsize_str       db 'tsize' ,0                           ; Request size
2550 tsize_len       equ ($-tsize_str)
2551                 db '0', 0
2552 blksize_str     db 'blksize', 0                         ; Request large blocks
2553 blksize_len     equ ($-blksize_str)
2554                 asciidec TFTP_LARGEBLK
2555                 db 0
2556 tftp_tail_len   equ ($-tftp_tail)
2557
2558                 alignb 2, db 0
2559 ;
2560 ; Options negotiation parsing table (string pointer, string len, offset
2561 ; into socket structure)
2562 ;
2563 tftp_opt_table:
2564                 dw tsize_str, tsize_len, tftp_filesize
2565                 dw blksize_str, blksize_len, tftp_blksize
2566 tftp_opts       equ ($-tftp_opt_table)/6
2567
2568 ;
2569 ; Error packet to return on options negotiation error
2570 ;
2571 tftp_opt_err    dw TFTP_ERROR                           ; ERROR packet
2572                 dw TFTP_EOPTNEG                         ; ERROR 8: bad options
2573                 db 'tsize option required', 0           ; Error message
2574 tftp_opt_err_len equ ($-tftp_opt_err)
2575
2576                 alignb 4, db 0
2577 ack_packet_buf: dw TFTP_ACK, 0                          ; TFTP ACK packet
2578
2579 ;
2580 ; IP information (initialized to "unknown" values)
2581 MyIP            dd 0                    ; My IP address
2582 ServerIP        dd 0                    ; IP address of boot server
2583 Netmask         dd 0                    ; Netmask of this subnet
2584 Gateway         dd 0                    ; Default router
2585 ServerPort      dw TFTP_PORT            ; TFTP server port
2586
2587 ;
2588 ; Variables that are uninitialized in SYSLINUX but initialized here
2589 ;
2590                 alignb 4, db 0
2591 BufSafe         dw trackbufsize/TFTP_BLOCKSIZE  ; Clusters we can load into trackbuf
2592 BufSafeBytes    dw trackbufsize         ; = how many bytes?
2593 %ifndef DEPEND
2594 %if ( trackbufsize % TFTP_BLOCKSIZE ) != 0
2595 %error trackbufsize must be a multiple of TFTP_BLOCKSIZE
2596 %endif
2597 %endif