Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 21

Міністерство освіти та науки України

Національний університет “Львівська політехніка”


Інститут комп’ютерних наук та інформаційних технологій
Кафедра автоматизованих систем управління

ПРОГРАМУВАННЯ ЗА ДОПОМОГОЮ ФУНКЦІЙ


WINDOWS API
ЗБІРНИК ЛАБОРАТОРНИХ РОБІТ

Методичні вказівки
до курсу “Операційні системи”
для студентів базової вищої освіти
за напрямком “Комп’ютерні науки”

Львів - 2022
Laboratory work #13
Topic - System Internet functions.
Goal – Learn to use a minimal set of networking functions to better
understand other related disciplines.

THEORETICAL PROVISIONS
The Internet is a partial use case of network functions that relies on the
concept of a web page and an Internet resource that can be retrieved using
data from a web page. When we talk about the Internet, we mean remote
communication between computers that are located in different local
networks, although the simulation of the Internet can be done in the same
local network, and even on the same computer. A special network controller
(through a cable - Ethernet Controller) is responsible for communication in
the computer, as well as a wireless WLAN Controller, which can work
without a computer, for example, in interaction with another controller that
turns on or off electrical appliances ( Internet of Things - IoT).
The data memory of the Internet controller is limited to 2 kilobytes,
because the larger size of Internet packets leads to a sharp increase in errors
during transmission. This happens because packets enter the local network
randomly, and an increase in packet length increases the probability of their
overlap. To understand this, imagine several people who, sitting in the same
room, decided to simultaneously communicate on their mobile phones with
other subscribers.
A special radio frequency is allocated for household radio
communication, regardless of the number of subscribers. Therefore, the
mobile phone stores the sound in a temporary data buffer, and then instantly
transmits it in the form of a data packet. Therefore, most of the time when
the conversation is buffered, the phone is not transmitting and another
phone can use it to transmit its packet. If the packet size is increased, it will
not only degrade the quality of the connection, but also increase the delay
during the conversation.
The theory of packet communication is independent of the medium
through which they are propagated. It is only necessary that each package
arrives intact and that it is not intercepted by an attacker. Therefore, the
controller checks the packet's destination address, the checksum, and
accepts only the packet that is destined for it, or the packet whose
destination address is 0ffffffffffffh. Therefore, each packet has a special
header that contains the MAC address of the controller that sent the packet
(6 bytes), the MAC address of the controller to which the packet is destined
(6 bytes), the sequence number, the maximum number of nodes through
which the packet must be routed, and also, a port is an abstract data
assignment containing a packet (2 bytes). In radio networks, the MAC
address can be 8 bytes (for example, IMEI - International Mobile
Equipment Identity), which allows manufacturers to guarantee its global
uniqueness thanks to the three-byte manufacturer's code.
A protocol is an algorithm for processing data contained in a packet. A
connection is a sequence of MAC addresses through which a packet must be
sent to reach its destination address. If a certain protocol wants to establish a
connection, it first sends packets with 0ffffffffffffh instead of the destination
address. Such packets are processed by each LAN controller. A computer or
controller that has multiple network controllers can route packets between
different LANs to which it is connected. Some wireless controllers have a
mode of simply duplicating the received packet to another radio controller,
or "wrapping" one packet into another, which allows you to perform the
functions of a radio extender in case of poor communication.
To simplify the use of network functions, the developers introduced
the concept of "Internet Protocol", which uses IP addresses (4 bytes long),
which can be centrally changed by network administrators. There should
not be two computers with the same addresses on the same local network.
All computers in any local network have an initial prefix of "192.168.*.*",
and a computer or router that makes an exit from this network to the
outside, as a rule, has the number 1 at the end, for example: "192.168.
31.1". The same node (Gateway) also has an external IP - an address issued
by the provider from the addresses allocated to it. Address ranges are
allocated to providers of all European countries by a special organization
located in Belgium.
Thus, each local network has one external IP address and is perceived
as one computer. For example, you can see through which addresses your
request to the google.com site goes. To do this, press the <WIN>-<R> key
combination, and type "CMD" in the startup window. After launching
CMD, type "tracert google.com". To get complete information about the
Gateway, MAC address and IP address of your computer, enter the
command: "ipconfig /all" in CMD.

WORK PERFORMANCE PROCEDURE


Let's start by studying the functions of the transport layer (TCP/IP),
when it is necessary to forward a buffer of any data from one computer to
another computer. At this level, the main function is the socket function,
which resembles opening a file. A socket is an abstract network channel
between computers through which data is transmitted. The sequence of data
transmitted through a socket is called a protocol, and is used for more
complex and structured data transmission. We will use port number 80 (web
page transfer protocol).
First, try using sockets to download the initial page from any site. An
example program is provided below:

.586
.model flat,stdcall
Extrn ExitProcess:Proc, WSAStartup:Proc, socket:Proc, bind:Proc, listen:Proc,
closesocket:Proc, accept:Proc, recv:Proc, send:Proc, inet_ntoa:Proc, lstrlen:Proc,
MessageBoxA:Proc, connect:Proc, Sleep:Proc, gethostbyname:Proc,
ShellExecuteA:Proc
SOCK_STREAM equ 1
SOCK_DGRAM equ 2
SOCK_RAW equ 3
SOCK_RDM equ 4
SOCK_SEQPACKET equ 5
PF_INET equ 2
.data
ZERO db 0,0
.data?
Hsocket dd ?
HAccept dd ?
WSADATA:
wVersion dw ?
wHighVersion dw ?
szDescription db 257 dup (?)
szSystemStatus db 129 dup (?)
iMaxSockets dw ?
iMaxUdpDg dw ?
lpVendorInfo dd ?
.code
;--------------------------------------------------------------------------------------------------
START:
call WSAStartup,101h,offset WSADATA
call socket,PF_INET,SOCK_STREAM,0
mov Hsocket,eax
mov HAccept,eax
mov eax,80 ; «http port»
xchg al,ah
mov PORT_CONNECT,ax
;----------------------------------------------------------------------------
; Create a file for saving results:
;----------------------------------------------------------------------------
Extrn CreateFileA:Proc, WriteFile:Proc, CloseHandle:Proc
CREATE_ALWAYS equ 2
GENERIC_WRITE equ 40000000h
.data
openname db "Received_data.txt",0
.data?
hFile_LISTEN dd ?
WRITTEN dd ?
; Memory buffer for received data:
BUFFER_LISTEN_MAXLEN equ 100000
BUFFER_LISTEN db BUFFER_LISTEN_MAXLEN dup(?)
BUFFER_LISTEN_LEN dd ?
;-------------------------------------------------------------------------------------
.code
push 0
push 0
push CREATE_ALWAYS
push 0
push 1
push GENERIC_WRITE
push offset openname
call CreateFileA
mov hFile_LISTEN,eax ; the result is a handle of file
;------------------------------------------------------------
; Sending the http-request to web-server:
;------------------------------------------------------------
.data
HOST_NAME db "www.cyber-soft.com",0
; The request "GET" looks like this:
BUFFER_CONNECT_SEND:
db "GET / HTTP/1.1",0Dh,0Ah
db "User-Agent: Opera/9.80 (Windows NT 5.1) Presto/2.12.388
Version/12.17",0Dh,0Ah
db "Host: "
db "www.cyber-soft.com",0Dh,0Ah
db "Accept: text/html, application/xml;q=0.9, application/xhtml+xml,
image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap,
*/*;q=0.1",0Dh,0Ah
db "Accept-Language: en-US,en;q=0.9",0Dh,0Ah
db "Accept-Encoding: gzip, deflate",0Dh,0Ah
db "Connection: Keep-Alive",0Dh,0Ah
db 0Dh,0Ah,0
; Standard structure using for connection:
PEER_CONNECT:
dw PF_INET
PORT_CONNECT dw 0
IP_CONNECT dd 0,0,0 ; IP-address for connection
;------------------------------------------------------------------------
.code
call gethostbyname,offset HOST_NAME
or eax,eax
jz ERR_HOSTNAME
mov ebx,[eax] ; use the standard structure HOSTENT for obtaining information
push ebx
mov eax,[eax+0ch]
mov eax,[eax]
mov eax,[eax]
mov IP_CONNECT,eax ; address of connected site
call inet_ntoa,eax ; convert IP-address to the texform
pop ebx
test eax,eax
jz STOP
call MessageBoxA,0,eax,ebx,40h
.data
;----------------------------------------------------------------------------------------------------
.code

call connect, Hsocket, offset PEER_CONNECT, 16

call lstrlen, offset BUFFER_CONNECT_SEND

call send, Hsocket, offset BUFFER_CONNECT_SEND,eax,0

call recv, HAccept, offset BUFFER_LISTEN,


BUFFER_LISTEN_MAXLEN, 0

call WriteFile, hFile_LISTEN, offset BUFFER_LISTEN, eax, offset


WRITTEN,0
call WriteFile, hFile_LISTEN, offset ZERO, 1, offset WRITTEN,0
call Sleep,100
call recv, HAccept, offset BUFFER_LISTEN, 1022, 0

call WriteFile, hFile_LISTEN, offset BUFFER_LISTEN, eax, offset


WRITTEN,0
call WriteFile, hFile_LISTEN, offset ZERO, 1, offset WRITTEN,0

CALL closesocket,HAccept

call MessageBoxA,0,offset BUFFER_LISTEN,offset


BUFFER_CONNECT_SEND,40h
call ShellExecuteA,0,0,offset openname,0,0,1
;----------------------------------------------------------------------------------------------------
STOP:
call CloseHandle,hFile_LISTEN
call ExitProcess,0
ERR_HOSTNAME:
call MessageBoxA,0,offset TEXT_ERR_HOSTNAME,offset
HOST_NAME,10h
jmp STOP
TEXT_ERR_HOSTNAME db "IP-address Error!",0
end START

This program simulates access to www.cyber-soft.com using the


Opera/9.80 browser. The site's response is written to the Received_data.txt
file, where you will see that the site responds with some structured
information. First, there are data about the server, date, type of encoding,
language in which the site is made, data about user personalization, access
mode without saving the web page, and the web page itself. The fact that a
site immediately sends some script, as seen in the text of the page, can be
dangerous if the site is opened by a browser, because the browser
immediately starts executing this script. Your program doesn't execute the
script, it only reads it, so it's safe.
The next lab task is to create a simple server that uses sockets to send
your web page to the browser. In the theory of sockets, functions are
distinguished that are characteristic of the client (the one who initiates the
connection) and the server (the one who expects and accepts the
connection), the rest of the functions are common, for example, "send data
(send)", "receive data (recv)" etc. To connect, the client uses the connect
function, and the server must perform the accept function in response to it.
The result of such a connection will be the handle of the client socket (in the
EAX register), through which the server will communicate with a specific
client (theoretically, there can be many of them). The result of the accept
function is also a structure containing the IP address of this client. To wait
for a connection with the next client, the server uses the bind and listen
functions.
The program below works as follows. First, a window with the "Send"
button is created. In the window procedure, when the window is created, the
INITIALIZE subroutine is called, which initializes the socket library
(WSAStartup), opens a socket, and registers a new NET_CODE message
(set by the programmer at his own choice), which will notify your window
procedure about any events in sockets This registration is performed by the
WSAAsyncSelect function, where the events in the socket are specified by
the following flags:

FD_ACCEPT - The server received a client connection request and


must perform the accept function.
FD_CONNECT - The client has received confirmation of joining the
server and can send any request to it using the send function.
FD_CLOSE - A message about the connection (socket) being closed
by the other party.
FD_READ - The socket received data that can be read by the recv
function.
FD_WRITE - Sending data through the socket is complete. You can
continue sending new data using the send function.

If, after the client performs the connect function, the server does not
respond with the accept function for some time, the system can send a
repeated NET_CODE message with the FD_ACCEPT parameter to the
server. In order to avoid fake connections from the same client, this
program uses the FLAG_ACCEPT flag variable, which is set to 1 if the
client has already joined.

.586
.model flat,stdcall
extrn WSAStartup:proc, socket:proc, WSAAsyncSelect:proc, inet_addr:proc,
lstrlen:proc, connect:proc, CreateWindowExA:proc, RegisterClassExA:proc,
GetModuleHandleA:proc, ExitProcess:proc, MessageBoxA:proc,
DefWindowProcA:proc, GetMessageA:proc, TranslateMessage:proc,
DispatchMessageA:proc, send:proc, recv:proc, closesocket:Proc, bind:proc,
listen:proc, accept:proc, inet_ntoa:proc, CreateMenu:Proc, AppendMenuA:Proc
extrn GetDC:Proc, ReleaseDC:Proc, TextOutA:Proc, ModifyMenuA:Proc,
DrawMenuBar:Proc
extrn CreateFileA:Proc, GetFileSize:Proc, ReadFile:Proc, CloseHandle:Proc
PF_INET equ 2
SOCK_STREAM equ 1
FD_READ equ 001h
FD_ACCEPT equ 008h
FD_CONNECT equ 010h
FD_CLOSE equ 020h
MB_SETFOREGROUND equ 10000h
WS_MY_STYLE equ 10cf0000h
WM_CREATE equ 1h
WM_COMMAND equ 111h
NET_CODE equ 7458
;=============================
.data
winclass:
dd 12*4, 4003h, offset wndproc, 0,0
hInstance dd 0
hIcon dd 0
hCursor dd 0
hbrBackground dd 1
lpszMenuName dd 0
lpszClassName dd offset class_name;
hIconSm dd 0;
class_name db 'MY_chat',0
MENUNAME db "MM1",0
MSG dd 0,0,0,0,0,0,0
Hwnd1 dd 0
port dd 80
peer_name_bind:
sim_family dw PF_INET
sin_port dw 0
sim_addres dd 0,0,0
peer_name_accept:
dw PF_INET
dw 0
adr_accept dd 0,0,0
peer_len_accept dd 0
FLAG_ACCEPT dd 0
TITLE1 db "SERVER:",0
TEXT_FILE db "File not Found!",0
TEXT_CLOSE db "Connection was closed...",0
TEXT_READ db "SERVER received data:",0
TEXT_DISCONNECT db "Connection error...",0
TEXT_CONNECT db "SERVER: The connection is accepted!",0
Hsocket dd 0
HAccept dd 0
hMENU dd 0
TEXT_SEND db "Send "
openname db 260 dup(0)
hFILE dd 0
TEMP dd 0
LEN_FILE dd 0
.data?
buffer2 db 1000000 dup(?)
WSADATA:
wVersion dW ?
wHighVersion dW ?
szDescription dB 257 dup (?)
szSystemStatus dB 129 dup (?)
iMaxSockets dW ?
iMaxUdpDg dW ?
lpVendorInfo dD ?
;================================================
.code
start: call GetModuleHandleA,0
mov hInstance,eax
call CreateMenu
mov hMENU,eax
call AppendMenuA,hMENU,0,111,offset TEXT_SEND
call RegisterClassExA, offset winclass
call CreateWindowExA,8,eax,offset
TITLE1,WS_MY_STYLE,350,350,300,160,0,hMENU,hInstance,0
mov Hwnd1,eax
cmp eax,0
jz STOP
MSG_LOOP:
call GetMessageA,offset MSG,Hwnd1,0,0
cmp eax,-1
jz STOP
call TranslateMessage,offset MSG
call DispatchMessageA,offset MSG
jmp MSG_LOOP
STOP: call ExitProcess,0
;==============================================
wndproc proc,HWND:dword,code_Msg:dword,wparam:dword,lparam:dword
cmp code_Msg,WM_CREATE
jnz GO_NET
INIT_AGAIN: ; This part is activated only when waiting for a new client
call closesocket, HAccept
mov sim_addres,0
mov FLAG_ACCEPT,0
call INITIALIZE ; Creating a socket and registering NET_CODE
call bind, Hsocket,offset peer_name_bind,16 ; SERVER command
call listen, Hsocket,2 ; SERVER command
jmp EXIT_PROC
GO_NET:
cmp code_Msg,NET_CODE
jnz NOT_NET
mov eax,lparam
;--------------------
TEST_ACCEPT:
cmp AX,FD_ACCEPT ; Is it a request to join?
jnz TEST_READ
cmp FLAG_ACCEPT,0 ; yes, we connect the client:
jnz EXIT_PROC
mov FLAG_ACCEPT,1
mov peer_len_accept,16
call accept, Hsocket,offset peer_name_accept,offset peer_len_accept
mov HAccept,eax
mov eax,offset peer_name_accept
mov eax,[eax+4] ; get the client's IP-address from the table
call inet_ntoa,eax ; convert IP-address to text form
mov esi,eax
call lstrlen,esi
mov edi,eax
call GetDC,HWND
push eax
call TextOutA,eax,20,20,esi,edi ; display the IP-address in the window
pop eax
call ReleaseDC,HWND,eax
jmp EXIT_PROC
;--------------------
TEST_READ:
cmp AX,FD_READ ; did the data arrive in the socket?
jnz TEST_CLOSE
call recv,HAccept,offset buffer2,1000000,0 ; Yes, read arrived data.
mov byte ptr [eax+offset buffer2],0 ; Zero at the end of the text
call MessageBoxA,HWND,offset buffer2,offset
TEXT_READ,MB_SETFOREGROUND
and byte ptr buffer2,255-32 ; convert to uppercase
cmp byte ptr buffer2, "G" ; The request is «GET …?»
jnz EXIT_PROC
; Get the requested file name from the header after "GET ...":
mov esi,offset buffer2+5
mov edi,offset openname
L_READ1:
lodsb
cmp AL," " ; The file name ends with a space ,
jz EX_TEST_READ
cmp AL,"?" ; or a question mark if there is an option.
jz EX_TEST_READ
stosb
jmp L_READ1
EX_TEST_READ:
mov byte ptr [edi],0
; We replace the empty file name at the initial request with Main.txt:
.if byte ptr openname==0
mov dword ptr openname,"niaM"
mov dword ptr openname+4,"txt."
mov dword ptr openname+8,0
.endif
call ModifyMenuA,hMENU,111,0,111,offset TEXT_SEND
call DrawMenuBar, HWND ; change the button name
jmp EXIT_PROC
TEST_CLOSE:
cmp AX,FD_CLOSE
jnz NOT_NET
call MessageBoxA,HWND,offset TEXT_CLOSE,offset
TITLE1,MB_SETFOREGROUND
jmp INIT_AGAIN
NOT_NET:
cmp code_Msg,WM_COMMAND
jnz EXIT_PROC
; Send reqested file:
call CreateFileA, offset openname, 80000000h,1,0,3,0,0
mov hFILE,eax ; отримали хендл файлу
.if hFILE==-1
call MessageBoxA,HWND,offset openname,offset TEXT_FILE,10h
jmp INIT_AGAIN
.endif
call GetFileSize,hFILE,0
mov LEN_FILE,eax
call ReadFile,hFILE,offset buffer2,LEN_FILE,offset TEMP,0
call CloseHandle,hFILE
call send,HAccept,offset buffer2,LEN_FILE,0
jmp INIT_AGAIN
EXIT_PROC: call DefWindowProcA, HWND,code_Msg,wparam,lparam
ret
endp wndproc

;========= At the begining create a socket and register NET_CODE:


INITIALIZE:
call WSAStartup,101h,offset WSADATA ; ініціалізація бібліотеки
сокетів
call closesocket,Hsocket
call socket,PF_INET,SOCK_STREAM,0 ; відкриття сокету
mov Hsocket,eax ; хендл сокету для клієнта
mov HAccept,eax ; хендл сокету для сервера
call WSAAsyncSelect, Hsocket, HWND, NET_CODE,
FD_CONNECT+FD_ACCEPT+FD_CLOSE+FD_READ
mov ax,word ptr port
xchg ah,al ; байти в номері порту поміняні місцями
mov sin_port,ax
ret
end start

The following text files must be placed in the folder with this program.
Main.txt is given below:

<html> <meta charset="windows-1251"/>


<head><title>Remote System</title></head>
<body bgcolor="yellow">
<form action="Question.txt">
<p><H1>Your Name:
<input type="text" name="mister" size="15"
maxlength="30" />
</H1> </p> </form> </body> </html>

This file will be transferred to the browser when the browser connects
to the server. After entering any text (Your Name), a Question.txt file will
be sent to the browser, which must also be placed in the current folder:

<html> <meta charset="windows-1251"/>


<head><title>Remote System</title></head>
<body bgcolor="yellow">
<img src="test.jpg" alt="Test" title="User" height="492" width="512">
<form action="Thanks.txt">
<button name="test1"> <img src="test.jpg" width="35" height="35" />
FOR </button>
<button name="test2"> <img src="test.jpg" width="35" height="35" />
AGAINST </button>
<button name="test3"> <img src="test.jpg" width="35" height="35" />
UNCERTAIN </button>
</form></body> </html>

It is also necessary to place any icon in the current folder and name it
"favicon.ico", then it will be displayed on the browser bookmark. It is also
necessary to place in the current folder any picture "test.jpg" with an
arbitrary question, for example: "Do you like football?". It is necessary to
launch this program, write down your IP address, launch a browser and
enter: "http://127.0.0.1" or your IP-address in the address bar. In response
to this, the server window will display the IP address of the client, as well as
a MessageBox, which will contain a "GET" request to the root web page.
You need to click "OK", after which the text on the "Send" button in the
server window will change to "Send Main.txt". You need to click this
button, after which the text and request for the last name that you gave in
the Main.txt web page will appear in the browser. After you enter your last
name, the web browser will pull up the "Question.txt" web page with the
image you selected. Before its output, the server will again display its
request in the MessageBox. For the server to continue, you must repeat the
same steps you did to display the previous web page. In order for the dialog
to continue, the current folder should contain a "Thanks.txt" web page with
something like this (ANSI format):
<html> <head> <meta charset="windows-1251"/>
<title>Remote System</title> </head> <body bgcolor="yellow">
<h1> Thank You ! </h1> </body> </html>
To successfully pass the laboratory work, it is necessary to modify the
specified web pages in any way so that they contain your last name and
group.
The next task is to move to a higher level of Internet resources (URL),
where you can transfer the file in one operation. Based on sockets, libraries
for network protocols have been created, the most important of which is the
wininet.dll library. With the help of the implib.exe program, the file
wininet.lib was created from this library, which contains the addresses of
the functions of this library and is available on the shared google-disk.
There are primary and secondary functions in this library. The main
function is InternetOpenA, which opens the user's Internet session (returns
the session handle in the EAX register). This is necessary for opening any
Internet resource. It is called with the following parameters:
1. The name of the program that opens the Internet session, the so-
called "user agent". This is an arbitrary name that will appear in all
protocols.
2. Type of access: direct, or filtered through a proxy server, or from a
specific source, or by default (which is written in the registry).
3. The name of the source or proxy server, if the connection is not by
default.
4. The address of the list of IP addresses or hostnames to be searched
on the local network, not on the global network.
5. Access modes, for example: search for data only in the cache.
The next step depends on the protocol. For example, if it is "ftp:", then
you need to execute the InternetConnectA function, which specifies the
address of the host (site), the username and password of the user on this
host. According to this protocol, you can download and upload any
information to any site. If it is the "http:" protocol, then you can get any
Internet file (resource) using the InternetOpenUrlA function, which in most
cases does not require a password. This function is similar to the well-
known file opening function, but only for reading. As with opening a file,
the result of executing InternetOpenUrlA will be a handle to a specific
Internet file or web page (URL). After that, this file can be downloaded
using the InternetReadFile function. In case of a poor connection, files are
downloaded much faster if they are downloaded in 200-byte chunks. Then
this function must be executed in a loop. If the connection is lost, you can
open the same URL again and use the InternetSetFilePointer function to
set the pointer to the part of the file where the connection was lost,
otherwise the download will start over.
InternetOpenUrlA parameters:
1. The Internet session handle that you have already opened.
2. A pointer to a string that represents a specific URL, for example:
"http://www.safetree.ca/files/LargeTree.jpg".
3. A pointer to a list of additional headers if a secure or password
connection or 0 is in progress.
4. The length of this list is either 0.
5. Flags defining the opening mode, for example, disallow write to
cache, do not check content certification, save connection after download,
do not redirect connection, do not use authentication, do not add cookie to
header, reload data, create secure with unity.
6. Context parameter or 0.
As you saw in the sockets example, the http protocol involves passing
a sequence of specialized headers before an Internet resource. They contain
additional information about the connection. Some of these headers can be
retrieved using the HttpQueryInfoA function. You can receive them one by
one, or all together (using the HTTP_QUERY_RAW_HEADERS_CRLF
parameter). The parameters of this function are as follows:
1. Internet resource handle (file, web page, etc.).
2. Header type to be retrieved or
HTTP_QUERY_RAW_HEADERS_CRLF.
3. A pointer to the buffer in which the header will be written.
4. A pointer to a variable that initially contains the maximum length of
the buffer, and after the function is executed, the variable will contain the
length of the header.
5. If there are several headers of this type, then the header index of the
same type (more often 0).
One of the headers contains the length of the resource. Before
receiving the file, the web browser obtains the length of the resource from
this header to show the download percentage. You can convert the text
result into a number using the inet_addr function, after which you will need
to swap bytes in EAX in the reverse order: bswap eax.
Parameters of the InternetReadFile function:
1. URL handle (obtained from InternetOpenUrlA).
2. The address of the data buffer to receive it.
3. How many bytes you want to read into this buffer.
4. A pointer to a variable that will contain the actual number of bytes
received after this function is executed. If the function is executed again, it
will continue to read the URL further. If the resource has no more bytes,
this variable will contain 0.
To check the availability of this resource, you can use "call
InternetCheckConnectionA, offset lpszURL, 2, 0".
To fix the material, you need to run the following program that
downloads the image:

.586
.model flat,stdcall
includelib wininet.lib
Extrn InternetOpenA:Proc, InternetOpenUrlA:Proc, InternetReadFile:Proc
Extrn InternetCloseHandle:Proc, InternetSetFilePointer:Proc,
ExitProcess:Proc, InternetSetOptionA:Proc, MessageBoxA:Proc,
InternetQueryOptionA:Proc, InternetGetLastResponseInfoA:Proc,
HttpQueryInfoA:Proc, CreateFileA:Proc, WriteFile:Proc, CloseHandle:Proc,
ShellExecuteA:Proc
INTERNET_OPEN_TYPE_PRECONFIG equ 0
INTERNET_FLAG_RELOAD equ 80000000h

HTTP_QUERY_RAW_HEADERS_CRLF equ 22
HTTP_QUERY_CONTENT_LENGTH equ 5
GENERIC_WRITE equ 40000000h
.data
lpszAgent db "Internet Explorer",0
lpszURL db "http://www.safetree.ca/files/LargeTree.jpg",0
hSession dd 0
hURL dd 0
hFILE dd 0
TITLE1 db "Main:",0
TITLE2 db "Length:",0
TITLE3 db "IntrnetReadFile:",0
SizeOfBuffer dd 10000000
BufLen dd 0
openname db "1.jpg",0
SizeRead dd 0
.data?
BUFFER db 10000000 dup(?)
.code
Start: call InternetOpenA,offset lpszAgent,
INTERNET_OPEN_TYPE_PRECONFIG, 0,0,0
mov hSession,eax
call InternetOpenUrlA,hSession, offset lpszURL,
0,0,INTERNET_FLAG_RELOAD,0
mov hURL,eax
mov BufLen,10000
call HttpQueryInfoA, hURL, HTTP_QUERY_RAW_HEADERS_CRLF,
offset BUFFER,offset BufLen,0
.if eax==1
call MessageBoxA,0,offset BUFFER, offset TITLE1,40h
.endif
mov BufLen,10000
call HttpQueryInfoA,hURL,HTTP_QUERY_CONTENT_LENGTH,offset
BUFFER,offset BufLen,0
.if eax==1
call MessageBoxA,0,offset BUFFER, offset TITLE2,30h
.endif
call InternetReadFile,hURL, offset BUFFER, SizeOfBuffer,offset BufLen
call InternetCloseHandle,hURL
call InternetCloseHandle,hSession
push 0
push 0
push 4
push 0
push 1
push GENERIC_WRITE
push offset openname
call CreateFileA
mov hFILE,eax
push 0
push offset SizeRead
push BufLen
push offset BUFFER
push hFILE
call WriteFile
call CloseHandle,hFILE
call ShellExecuteA,0,0,offset openname,0,0,1 ; display the picture
STOP:
call ExitProcess,0
end Start

It is necessary to redesign the program so that it downloads a sound


file. The next step of the laboratory work is to work with the FTP server.
FTP has its own set of functions, each of which begins with "FTP". These
functions are system functions and are present on every computer. FTP is
used to change web pages on a site, for example to display weather
conditions or traffic in the town. In order to create a site, you need to buy
hosting (from someone who sells it). The seller sends the IP-address,
UserName and Password to your mailbox. You can also purchase your
domain name registration to the site. Below are examples of how to
download a file (FtpGetFileA), upload a file to the server (FtpPutFileA),
and get a list of files on the server (FtpFindFirstFileA,
InternetFindNextFileA) using the FTP protocol:

.586
.model flat,stdcall
includelib wininet.lib
Extrn InternetOpenA:Proc, InternetOpenUrlA:Proc, InternetReadFile:Proc
Extrn InternetCloseHandle:Proc, InternetSetFilePointer:Proc,FtpGetFileA:Proc
Extrn HttpQueryInfoA:Proc, FtpPutFileA:Proc, FtpRemoveDirectoryA:Proc
Extrn ExitProcess:Proc, MessageBoxA:Proc, InternetConnectA:proc,
_wsprintfA:Proc, FtpGetCurrentDirectoryA:Proc, FtpCreateDirectoryA:Proc,
FtpSetCurrentDirectoryA:Proc, InternetFindNextFileA:Proc,
FtpFindFirstFileA:Proc, FtpDeleteFileA:Proc
INTERNET_OPEN_TYPE_PRECONFIG equ 0
INTERNET_FLAG_PASSIVE equ 8000000h
INTERNET_DEFAULT_FTP_PORT equ 21
INTERNET_SERVICE_FTP equ 1
FTP_TRANSFER_TYPE_BINARY equ 2
.data
InternetAgent db "Internet Explorer",0
hSession dd 0
hConnect dd 0
FTP_ID dd 0
;--------------------------------------
host_name db "185.86.76.30",0
UserName db "624124-ddzerbino",0
Password db "EvatkNvFuNza",0
;--------------------------------------
SET_DIRNAME db "http",0
FILE_NAME db "test.jpg",0
TEXT_DOWNLOAD db "File Downloaded",0
.code
Start:
call InternetOpenA, offset InternetAgent,
INTERNET_OPEN_TYPE_PRECONFIG,0,0,0
mov hSession,eax
call InternetConnectA, hSession, offset host_name,
INTERNET_DEFAULT_FTP_PORT, offset UserName, offset Password,
INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,offset FTP_ID
mov hConnect,eax
cmp eax,0
jz STOP
call MessageBoxA,0,offset UserName, offset host_name,40h
call FtpSetCurrentDirectoryA, hConnect, offset SET_DIRNAME
cmp eax,0
jz STOP
;==============================================
call FtpGetFileA, hConnect, offset FILE_NAME, offset FILE_NAME,
0,0,FTP_TRANSFER_TYPE_BINARY,offset FTP_ID
cmp eax,0
jz STOP
;==============================================
call MessageBoxA,0,offset FILE_NAME, offset TEXT_DOWNLOAD,40h
STOP:
call InternetCloseHandle,hConnect
call InternetCloseHandle,hSession
call ExitProcess,0
end Start

In order to upload your file to the server, you need to change the line
with the FtpGetFileA function call to the following line in this program:
call FtpPutFileA, hConnect, offset FILE_NAME, offset FILE_NAME,
FTP_TRANSFER_TYPE_BINARY, offset FTP_ID
After a successful connection to the server, the program displays a
message and downloads the specified file. To successfully complete the
task, you need to upload an arbitrary file to the server, the name of which
matches your last name. In order to check the presence of a file on the
server, you can download it again, or see a list of all server files using the
following fragment, which should be added instead of the line containing
FtpGetFileA:

INTERNET_FLAG_RAW_DATA equ 40000000h


.data
WIN32_FIND_DATA:
dwFileAttributes DD 0ffffffffh
ftCreationTime DQ 0
ftLastAccessTime DQ 0
ftLastWriteTime DQ 0
nFileSizeHigh DD 0
nFileSizeLow DD 0
dwReserved0 DD 0
dwReserved1 DD 0
cFileName DB MAX_PATH dup(?)
cAlternate DB MAX_PATH dup(?)
FORM1 db "Attr = %Xh",0
hFindURL dd ?
TEXT_BUF db 260 dup(?)
.code
call FtpFindFirstFileA, hConnect, 0, offset
WIN32_FIND_DATA,INTERNET_FLAG_RAW_DATA, offset FTP_ID
mov hFindURL,eax
L_FIND1:
call _wsprintfA, offset TEXT_BUF, offset FORM1, dwFileAttributes
add esp,12
call MessageBoxA, 0, offset cFileName, offset TEXT_BUF, 0
call InternetFindNextFileA, hFindURL, offset WIN32_FIND_DATA
cmp eax,0
jnz L_FIND1
After successfully passing the laboratory work, you need to delete
your file using the following function:
call FtpDeleteFileA, hConnect, offset MY_FILE_NAME

CONTROL QUESTIONS
1. What is a client?
2. What is a server?
3. What does the WSAStartup function do?
4. What does the socket function do?
5. What does the WSAAsyncSelect function do?
6. What does the inet_addr function do?
7. What does the connect function do?
8. What does the send function do?
9. What does the recv function do?
10. What does the bind function do?
11. What does the listen function do?
12. What does the accept function do?
13. What does the inet_ntoa function do?
14. What is a port?
15. What is an IP address?
16. What network events do you know?
17. What functions of the http protocol do you know?
18. What functions of the ftp protocol do you know?

WORK REPORT FORM


The report is a document that the student has successfully completed
the work.
1. The goal of the work (on your understanding);
2. Summary of theoretical information (on your understanding);
3. Texts of all debugged programs with your comments;
4. Answers to control questions;
5. Conclusions on the specifics of the application of the acquired
knowledge or comments on the performance of the work and comments
for improving methodical support.

You might also like