Dedicated Yamaha Router APIs for Lua

Summary

This chapter describes the list of APIs that are available for the Lua script function.

Notes

If the execution result is returned in the API return value, it indicates that the API was executed successfully. Even if an error is returned in the return value of the API, the script execution is not aborted as there is no syntax error in the script; and the execution result of the show status lua command is the normal end.
On the other hand, if the script cannot be executed due to incorrect API argument or script syntax error, the script execution is aborted, and an INFO type error message is output to the system log. In this case, the execution result of the show status lua command is an error.

[System log example]

2009/09/21 12:20:07: lua: mail.lua:26: 'rt.mail': 'text' field value of argument #1 is invalid.

If you do not want the script execution to be aborted by an API argument error, use the standard Lua functions such as pcall() or xpcall().


API List

The available APIs vary depending on the version of the Lua script function. See the Revision history of the Lua script function versions for information on the Lua script function versions and their corresponding firmware.


Basic Library

Executing a Router Command

[Format]
rt.command(COMMAND [, LOG])
[Argument]
  • COMMAND ... Command string (including parameters)
  • LOG ... Output or not when COMMAND is executed ("on" if omit).
    • "on" ... Output logs
    • "off" ... Not output logs

[Description]

Executes the router command COMMAND. This function is returned when the COMMAND execution completes. The maximum number of characters you can specify in COMMAND is 4095 characters based on the router command specification. You can include pipes ("|") and redirect symbols (">", ">>") in COMMAND.
If LOG is specified as "off", both executed COMMAND and executing result (true/false) are not output into SYSLOG. If LOG is omitted or specified as "on", both executed COMMAND and executing result (true/false) are output in SYSLOG as DEBUG level. LOG can be specified in firmware with _RT_LUA_VERSION higher than "1.07".


[Return value]
<< Multi-Value >>
  1. Command input result (Logical)
    ▪ true : Normal response
    ▪ false : Error response
  2. A string output by command execution

If the first return value is true, the second return value will contain the string output as a result of executing COMMAND. If there is an error message output, the message string will be stored in the second return value even if the first return value is false. If no string is output as a result of executing COMMAND, the second return value will be nil. The character code of the output string will be as specified by the console character command.

For example, if:

rtn, str = rt.command("show status lan2")

is executed, the following information will be stored in the two return values. For easier viewing, a new line inserted into str in the "\n" position. However, all lines are actually stored in str as a single string.

rtn   : true

str   : "LAN2\r\n"
        "Description:\r\n"
        "IP Address:                     192.168.2.1/24\r\n”
        "Ethernet Address:               00:a0:de:00:00:00\r\n" 
        "Operation mode setting:         Auto Negotiation (Link Down)\r\n"
        "Maximum Transmission Unit(MTU): 1500 octets\r\n"
                 (SNIP)
        "  IPv6:                         0 packet\r\n"

Also, if there is a command input error such as below:

rtn, str = rt.command("show status tunnel 9999")

The return value will be as follows.

rtn   : false

str   : "Error: Parameter out of range\r\n"
[Example of use]

Sends a ping 10 times to the specified address. If the packet loss rate is 30% or higher, change the route and write to the system log.
The packet loss rate (%) that is output at the end of the ping command execution is identified in this example.

rtn, str = rt.command("ping -c 10 172.168.1.100")
if (rtn) and (str) then 
	loss = string.match(str, "(%d+)%.%d+%%")    -- Extract the integer part of the packet loss rate (NNN.N%). 
	if (loss ~= nil) then 
		loss = tonumber(loss)               -- Convert from the string into the numeric value. 
		if (loss >= 30) then
			rt.command("ip route default gateway pp 2")
			rt.command("save") 
			text = string.format("The packet loss rate reached %d%%, " ..
					     "so the default route was changed", 
					     loss)
			rt.syslog("info", text)
		end
	end
end
[Note]

This function executes all commands with administrative user rights.

If the ping / ping6 command is executed without the COUNT option (i.e., how many times it is sent), ping will only be sent once.

The following router commands cannot be executed from this function.

  • administrator
  • administrator password
  • administrator password encrypt
  • clear configuration
  • cold start
  • copy config
  • copy exec
  • delete config
  • delete exec
  • execute batch
  • exit
  • http revision-up go
  • Commands starting with "less", and commands in which "less" is concatenated by "|"
  • login password
  • login password encrypt
  • lua use
  • luac
  • mail notify
  • mail server pop
  • mail server smtp
  • mail server timeout
  • mail template
  • pri loopback active
  • pri loopback passive
  • quit
  • remote setup
  • scp
  • ssh
  • telnet

Sending of E-mails

[Format]
rt.mail(TABLE)
[Argument]
  • TABLE ... E-mail settings table

    Contents of an e-mail settings table:
    Field name Setting value Omittable/Not omittable Default value
    smtp_address A string indicating the SMTP server address or host name (up to 64 characters) Not omittable -
    smtp_port SMTP server port number (0 to 65535) Omittable 25
    smtp_auth_name A string indicating the SMTP authentication user name (up to 64 characters) Omittable No
    smtp_auth_password A string indicating the SMTP authentication password (up to 64 characters) Omittable No
    smtp_auth_protocol A string indicating the SMTP-AUTH authentication protocol
    • cram-md5
    • digest-md5
    • plain
    Omittable Authentication negotiation is performed in sequence.
    pop_before_smtp This field should be set to true if performing POP before SMTP Omittable false
    pop_address A string indicating the POP server address or host name (up to 64 characters) Not omittable when pop_before_smtp=true No
    pop_port POP server port number (0 to 65535) Omittable 110
    pop_protocol A string indicating the reception protocol
    • pop3
    • apop
    Not omittable when pop_before_smtp=true No
    pop_auth_name A string indicating the POP authentication user name (up to 64 characters) Not omittable when pop_before_smtp=true No
    pop_auth_password A string indicating the POP authentication password (up to 64 characters) Not omittable when pop_before_smtp=true No
    timeout Timeout period for sending and receiving data (1 to 600 seconds) Omittable 60
    from A string indicating the source e-mail address Not omittable -
    to A string indicating the source e-mail address
    You can specify multiple addresses by delimiting them with a comma (,) without spaces.
    Not omittable -
    subject A string indicating the subject (up to 64 characters) Omittable Untitled
    date A string indicating the time displayed in the e-mail header
    This field specifies the time in the format indicated in RFC822.
    Omittable The router time when the e-mail is sent
    mime_version A string indicating the MIME-Version to be displayed in the e-mail header Omittable "1.0"
    content_type A string indicating the Content-Type displayed in the e-mail header
    You can specify "text/plain" for type/subject and "charset=us-ascii" or
    "charset=iso-2022-jp" for the parameter.
    Omittable "text/plain; charset=us-ascii"
    text A string indicating the body text (RTX5000: Up to 8000KB, RTX810/FWX120: Up to 640KB)
    You cannot include control characters other than line feed and tab characters.
    Omittable No body text
    preface_of_text This field should be set to false if the router information is not inserted at the beginning of the body text
    This field is specifiable in firmware with _RT_LUA_VERSION higher than "1.05".
    Omittable true
[Description]

Sends an e-mail based on the settings specified in TABLE. The e-mail is always sent after a one-second standby time, and this function will be returned when the sending of e-mail has completed. Therefore, if the response from the server is slow or if there is no response, the function may not be returned until the sending/receiving of data to/from the server times out.

"Omittable" fields do not need to exist in TABLE. If a "not omittable" field does not exist in TABLE, it will be treated as an incorrect API argument, and the script execution will be aborted.

Configure smtp_auth_name / smtp_auth_password if you require an authentication for the SMTP server.

If you wish to set the pop_before_smtp field to true, you will also need to configure the POP server-related settings.


[Return value]

E-mail send result (Logical type)

  • true : Send successful
  • false : Send failed

[Example of use]

Execute the show techinfo command and send the output data by e-mail.

command = "show techinfo"
mail_table = {
	smtp_address = "smtp.xxxx.com",
	from = "rt-admin@xxxx.com",
	to = "rt-admin@xxxx.com",
	subject = command
}

rtn, str = rt.command(command)
if (rtn) and (str) then 
	mail_table.text = string.format ("\"%s\" execution results \r\n\r\n%s", command, str)  
	rt.mail(mail_table)
end

Sleep

[Format]
rt.sleep(SECONDS)
[Argument]
  • SECONDS ... Number of sleep seconds (1 to 864000)
[Description]

Puts the calling Lua task to the sleep state for the duration of SECONDS. The CPU resource will not be used in the sleep state.

[Return value]

Returns 0 when SECONDS expires.


Writing to the System Log

[Format]
rt.syslog(TYPE, TEXT)
[Argument]
  • TYPE ... String type of the system log to be written
    • "notice" ... NOTICE type
    • "info" ... INFO type
    • "debug" ... DEBUG type
    • "log_only" ... INFO type log output only
  • TEXT ... Log string (up to 231 single-byte or 115 double-byte characters)

[Description]

Writes the specified content to the system log.

Even if the destination host for the system log has been configured using the syslog host command, no notifications will be sent to the host if you specify "log_only" for TYPE (only the log will be output).

You can include line feed characters "\r\n" in TEXT, but there is no need to append line feed characters to the end of TEXT. Moreover, you cannot include control characters other than line feed characters in TEXT.


[Return value]
<< Multi-Value >>
  1. Write result (Logical type)
    ▪ true : Write successful
    ▪ false : Write failed
  2. Error message

If the first return value is true, the second return value will be nil. If the first return value is false, the second return value will contain the string indicating the error details.

If the NOTICE / DEBUG type has been specified for TYPE and the corresponding syslog notice/debug command setting is off, nothing will be written to the system log, and false will be returned as the write result. If the INFO type has been specified for TYPE, data will be written to the system log regardless of the corresponding syslog info command setting. However, the notification to the system log host will only be performed when the syslog info command setting is set to on.


[Example of use]

Writes the CPU usage to the system log.

command = "show environment"

rtn, str = rt.command(command)
if (rtn) and (str) then
	cpu = string.match(str, "CPU:%s+(%d+)%%") 
	text = string.format("The current CPU usage is %s%%", cpu) 
	rt.syslog("info", text)
end

Monitoring the System Log

[Format]
rt.syslogwatch(PATTERN [, N [, SECONDS]])
[Argument]
  • PATTERN ... Search string
  • N ... Detection count (1 to 1000; 1 if omitted)
  • SECONDS ... Monitoring seconds (1 to 864000; indefinite if omitted)

[Description]

Monitors the system log of the router that is output after this function has been called. This function is returned when a string matching PATTERN has been detected N times or when SECONDS expires. The timestamps of the system log are not included in the search. Lua regular expressions can be used in PATTERN, but the capture function using brackets is not supported. In firmware with _RT_LUA_VERSION higher than "1.03", you can also use regular expression objects as PATTERN.

The calling Lua task goes to the sleep state while the system log is not output.


[Return value]
<< Multi-Value >>
  1. Number of hits
  2. An array containing the system log lines including the search string

The array that is returned in the second return value will contain the time-stamped system log lines containing the search string in the order of hits starting from the first element. If SECONDS expires before the number of hits reaches N times, the second return value will only contain the hit system log lines. If there are not hits, the number of hits will be 0 and the second return value will be nil.

Even if two or more PATTERN exists in a single line of the system log, the number of hits will always be 1 regardless of the PATTERN count. Therefore, the number of hits in the first return value and the number of array elements in the second return value will always match. In short, a hit count indicates the number of system log lines including PATTERN.

For example, if:

rtn, str = rt.syslogwatch("100", 2)

is executed and

"2009/08/22 13: 11: 02: [IKE] SEND ICMP Echo Request to 192.168.100.100"
"2009/08/22 13: 11: 03: [IKE] RECV ICMP Echo Reply from 192.168.100.101"

is output as the system log, the return value will be as described below.

rtn    : 2

str[1] : "2009/08/22 13:11:02: [IKE] SEND ICMP Echo Request to 192.168.100.100"
str[2] : "2009/08/22 13:11:03: [IKE] RECV ICMP Echo Reply from 192.168.100.101"
str[3] : nil

[Example of use]

Send an e-mail when a tunnel down-link is detected.

mail_table = {
	smtp_address = "smtp.xxxx.com",
	from = "rt-admin@xxxx.com",
	to = "rt-admin@xxxx.com", 
	subject = "Tunnel down-link” 
}
rtn, str = rt.syslogwatch("IP Tunnel%[%d+%] Down") 
mail_table.text = "A tunnel down-link was detected\r\n" .. str[1] 
rt.mail(mail_table)

Hardware Library

Starting the Hardware Control

[Format]
rt.hw.open(RESOURCE [, TYPE] )
[Argument]
  • RESOURCE ... A string representing the hardware to be controlled
    • The following are specifiable in firmware with _RT_LUA_VERSION higher than “1.02".
      • "buzzer1" ... Buzzer
      • "status-led1" ... STATUS light (FWX120 and RTX810 only)
      • "alarm-led1" ... ALARM light (RTX5000 only)
      • "thermometer1" ... Thermometer (RTX5000 only)
      • "cpu1" ... CPU
      • "cpu2" ... CPU1 of multi-core CPU (RTX5000 only)
      • "cpu3" ... CPU2 of multi-core CPU (RTX5000 only)
      • "cpu4" ... CPU3 of multi-core CPU (RTX5000 only)
    • The following are specifiable in firmware with _RT_LUA_VERSION higher than “1.04".
      • "keyboard1" ... USB keyboard, USB barcode reader, etc.
        (Restrictions)
        • Only the hardware recognized as a USB keyboard is controllable.
        • Only a single keyboard can be controlled at a time, even on models with two or more USB ports.
  • TYPE ... A string indicating the USB keyboard type ("us" if omitted)
    • "jp" ... Japanese 106 keyboard
    • "us" ... English 101 keyboard

[Description]

Opens the hardware specified in RESOURCE, makes it controllable from a Lua script and returns its descriptor.

You can only specify TYPE when controlling the USB keyboard "keyboard1"; the function will end with an error if it is specified when opening different hardware.

Since the hardware opened using this function is occupied by the calling Lua task, it cannot be controlled by other Lua tasks until it is closed using hwd:close. Hardware other than the thermometer "thermometer1" or the CPU "cpu1" will not perform their normal operations while being occupied by a Lua task, as they will become uncontrollable from other routers' functions.


[Return value]
<< Multi-Value >>
  1. Descriptor
  2. Error message

If the hardware is opened successfully, the first return value will be the descriptor and the second return value will be nil. If the hardware cannot be opened, the first return value will be nil and the second return value will contain the string indicating the error details.


[Example of use]

Activate the buzzer when a failure occurs in the network that is being monitored using the ip keepalive command and stop the buzzer when recovered. If the buzzer cannot be opened, the script will stop and an error message will be displayed.

ptn_unreach = "%[KEEPALIVE%]%s+1%: unreachable"
ptn_reach = "%[KEEPALIVE%]%s+1%: reachable"

while true do
	rtn, str = rt.syslogwatch(ptn_unreach)
	bz, err = rt.hw.open("buzzer1")

	assert(bz, err)

	bz:tone("B2")

	rtn, str = rt.syslogwatch(ptn_reach)

	bz:off()
	bz:close()
end

Ending the Hardware Control

[Format]
hwd:close()
[Argument]

No


[Description]

A method for the hardware descriptor hwd that closes hwd and ends the hardware control.

When the buzzer descriptor is closed, the buzzer will be stopped if it is sounding. When the LED descriptor is closed, the LED will be switched off if it is lit or flashing. If there is an unclosed descriptor at the end of the script execution, this function will be called automatically to close the descriptor.


[Return value]

No


[Example of use]

Switch on the STATUS light for one minute.

led, str = rt.hw.open("status-led1")

if (led) then
	led:on()
	rt.sleep(60)
	led:off()
	led:close()
end

Sounding the Buzzer

[Format]
hwd:tone(TUNE)
[Argument]
  • TUNE ... A string indicating the pitch

[Description]

A method for the buzzer descriptor hwd that triggers the buzzer in the pitch specified in TUNE.

TUNE is a string indicating the pitch and is specified using a combination of an alphabet from C, D, E, F, G, A and B and a one-digit number (e.g. "C1”). The "C" in "C1" represents the musical scale and corresponds to Do, Re, Mi, Fa, So, La and Ti starting from C. "1" represents the pitch of the sound; and increasing this value by 1 raises the pitch by one octave.

The pitches that can be output vary for each model and are limited to those shown in the table below. An input error will occur if you specify a pitch that is not shown in the table.

Model Output pitches
FWX120, RTX810 and RTX5000 B2, E3, B3, B4

Use the hwd:off function to stop the buzzer. To control the time from when the buzzer is started until it is stopped, use a combination of the rt.sleep and hwd:off functions.

In cases where instructions from this function are overlapped, such as when this function is called again while the buzzer is sounding, it will always be reset with the settings from when the function was last called. The buzzer will stop when the descriptor is closed or when the script ends.

If the alarm entire command is set to off, no buzzer sound will be output even when you call this function. The buzzer will stop if you set the alarm entire command to off while the buzzer is sounding.


[Return value]

No


[Example of use]

Sound the B2 and B3 buzzer sounds alternately for 10 seconds.

bz, err = rt.hw.open("buzzer1")

if (bz) then
	for i = 1, 5 do
		bz:tone("B3")
		rt.sleep(1)
		bz:tone("B2")
		rt.sleep(1)
	end

	bz:off()
	bz:close()
end

Switching on the LED

[Format]
hwd:on()
[Argument]

No


[Description]

A method for the LED descriptor hwd that switches on the LED.

Use the hwd:off function to switch off the LED. You can combine the rt.sleep function with the hwd:off function to control the LED on/off time.

In cases where instructions from this function are overlapped, such as when this function is called again while the LED is switched on, it will always be reset with the settings from when the function was last called. If the descriptor is closed or if the script execution ends, the LED will be switched off and return to its original operating state.


[Return value]

No


[Example of use]

Switch on the STATUS light while sending the show log command output data by e-mail.

command = "show log"
mail_table = {
	smtp_address = "mail.xxxx.com",
	from = "net_admin@xxxx.com",
	to = "net_admin@xxxx.com",
	subject = command
}

led, err = rt.hw.open("status-led1")
if (led) then
	led:on()
end

rtn, str = rt.command(command)
if (rtn) and (str) then 
	mail_table.text = string.format ("\"%s\" execution results \r\n\r\n%s", command, str) 
	rt.mail(mail_table)
end

if (led) then
	led:off()
	led:close()
end

[Format]
hwd:blink(INTERVAL_ON, INTERVAL_OFF)
[Argument]
  • INTERVAL_ON ... LED on time (100 to 3000 milliseconds)
  • INTERVAL_OFF ... LED off time (100 to 3000 milliseconds)

[Description]

A method for the LED descriptor hwd that flashes the LED.

INTERVAL_ON / INTERVAL_OFF is the on/off intervals of the flashing LED (in milliseconds) and is specified in the range between 100 and 3000 in 100 milliseconds steps. If specified a value that is not divisible by 100, less than 100 is truncated.

Use the hwd:off function to stop the flashing of the LED. You can combine the rt.sleep function with the hwd:off function to control the LED flashing time.

In cases where instructions from this function are overlapped, such as when this function is called again while the LED is flashing, it will always be reset with the settings from when the function was last called. If the descriptor is closed or if the script execution ends, the flashing LED will go off and return to its original operating state.


[Return value]

No


[Example of use]

If RTX810 does not receive a heartbeat from the monitored router within the specified period, flash the ALARM light for one minute.

ptn = "%[HEARTBEAT%]%s+Not received for a given period"

rtn, str1 = rt.syslogwatch(ptn)
led, str2 = rt.hw.open("alarm-led1")

if (led) then
	led:blink(500, 500)
	rt.sleep(60)

	led:off()
	led:close()
end

Stopping the Buzzer/Switching off the LED

[Format]
hwd:off()
[Argument]

No

[Description]

A method for the descriptor hwd that stops the sounding buzzer if hwd is the descriptor of the buzzer. It also switches off the lighting or flashing LED if hwd is the descriptor of the LED.

[Return value]

No


Reading the Thermometer, Obtaining the CPU Load Factor, and Reading the Keyboard Output

[Format]
hwd:read(N)
[Argument]
  • N ... Number of characters obtained from the USB keyboard

[Description]

A method for the descriptor hwd that reads the internal temperature value of the router if hwd is the descriptor of the thermometer. If hwd is the descriptor of the CPU, it obtains the CPU load factor. If hwd is the descriptor of the USB keyboard, it reads the number of characters specified in N from the keyboard output.

The argument N can only be specified when hwd is the descriptor of the USB keyboard. The script will end with an error if it is specified when hwd is the descriptor of the thermometer or CPU.


[Return value]
  • Temperature (Numeric type) ... When hwd is the descriptor of the thermometer
  • CPU load factor (Table type) ... When hwd is the descriptor of the CPU

    Table content:
    Field name Data type Measurement intervals of the CPU load factor
    load_5s Number type 5 seconds
    load_1m Number type 1 minute
    load_5m Number type 5 minutes
  • Characters output from the USB keyboard (String type) ... When hwd is the descriptor for the USB keyboard

[Example of use 1]

Check the internal temperature of the router every minute and flash the STATUS light if it exceeds 50 deg C.

threshold = 50
sleep_sec = 60

temp = 0

while (true) do
	th, err = rt.hw.open("thermometer1")
	if (th) then
		temp = th:read()
		th:close()
	end

	if (temp > threshold) then
		led, str = rt.hw.open("status-led1")
		if (led) then
			led:blink(500, 500)
		end
	else
		if (led) then
			led:off()
			led:close()
		end
	end

	rt.sleep(sleep_sec)
end

[Example of use 2]

Read five characters of keyboard input and output them to the console.

kbd, err = rt.hw.open("keyboard1", "us")
if kbd then
  data = kbd:read(5)
  print(data)
  kbd:close()
else
  print(err)
end

Reading the Keyboard Output (One Character)

[Format]
hwd:getc([NOWAIT])
[Argument]
  • NOWAIT ... Logical type (Omittable)

[Description]

A method for the USB keyboard descriptor hwd that reads one character from the keyboard output.

If NOWAIT is set to false, the key input can be read without wait time.


[Return value]

Characters output from the USB keyboard (String type)


[Example of use]

Obtain the keyboard input continuously until a new line is inserted.

kbd, str = rt.hw.open("keyboard1")
if kbd then
  str = ""
  n = 0

  data = kbd:getc()
  while data ~= '\n' do
    if data then
	    str = str .. data
	    n = n + 1
      data = kbd:getc()
    end
  end

  kbd:close() 
  print(str .." (" .. tostring(n) ..“Characters)” ) 
else
  print(str)
end

Reading the Keyboard Output (One Character)

[Format]
hwd:getchar()
[Argument]

No


[Description]

A method for the USB keyboard descriptor hwd that reads one character from the keyboard output.

It can be used in the same manner as the hwd:getc function, except that NOWAIT cannot be specified.


[Return value]

Characters output from the USB keyboard (String type)


Reading the Keyboard Output (One Line)

[Format]
hwd:gets()
[Argument]

No


[Description]

A method for the USB keyboard descriptor hwd that reads one line from the keyboard output until it obtains line feed characters.


[Return value]

Characters output from the USB keyboard (String type)


[Example of use]

Read one line of the keyboard input and displays the obtained string in the console.

kbd, str = rt.hw.open("keyboard1")
if kbd then
  data = kbd:gets()
  if data then
    print(data)
  end
  kbd:close()
else
  print(str)
end

HTTP Library

Sending HTTP Request

[Format]
rt.httprequest(TABLE)
[Argument]
  • TABLE ... HTTP request settings table

    Content of the HTTP request settings table:
    Field name Setting value Omittable/Not omittable Default value
    url A string indicating the request destination URL (up to 255 characters)
    It should be entered in the form of "http://server IP address or host name/path name".
    If the server port number is other than 80, it should be specified in the URL in the following format: "http://server IP address or host name:port number/path name".
    Not omittable -
    method A string indicating the HTTP method to be used for the request
    • GET
    • HEAD
    • POST
    Not omittable -
    proxy A string indicating the proxy server to be used for the request (up to 128 characters) Omittable No
    proxy_port Port number of the proxy server to be used for the request (0 to 65535) Omittable No
    auth_type A string indicating the authentication method
    • none .. No authentication
    • basic .. Use Basic authentication
    Omittable none
    auth_name A string indicating the authentication user name (up to 64 characters) Not omittable when
    auth_type="basic"
    No
    auth_pass A string indicating the authentication password (up to 64 characters) Not omittable when
    auth_type="basic"
    No
    timeout Timeout seconds for request processing (1 to 180) Omittable 30
    save_file A string indicating the file path when saving the response data to a file
    (up to 64 characters)
    You can write to the settings file by specifying configN
    (N = 0 to 4).
    This field will be ignored if "HEAD" is specified in the method.
    Omittable No
    post_text A string representing the body of the data sent using the POST method
    (RTX5000: Up to 8000KB, RTX810/FWX120: Up to 640KB)
    This field will be ignored if "GET" or "HEAD" is specified in the method.
    It cannot be specified together with post_file.
    Not omittable when method="POST" No
    post_file A string indicating the path of the file name to
    be sent using the POST method
    (up to 64 characters)
    This field will be ignored if "GET" or "HEAD" is specified in the method.
    It cannot be specified together with post_file.
    Not omittable when method="POST" No
    content_type A string indicating the format of the data to be sent using the POST method
    (up to 128 characters)
    This field will be ignored if "GET" or "HEAD" is specified in the method.
    Not omittable when method="POST" No

[Description]

Sends an HTTP request based on the settings specified in TABLE and receives the response data. This function is returned when the reception of the response data completes. Therefore, if the response from the server is slow or if there is no response, the function may not be returned until the sending/receiving of data to/from the server times out.

"Omittable" fields do not need to exist in TABLE. If a "not omittable" field is omitted in TABLE, it will be treated as an incorrect API argument, and the script execution will be aborted.

If Basic authentication is required for the destination server of the HTTP request, set auth_type to "basic", auth_name to the authentication user name, and auth_pass to the password.

You can save the received data to the RTFS area or external memory as a file by specifying the save destination path in save_file. The file saving capacity depends on the specification of the RTFS and external memory. If configN (N = 0 to 4) has been specified for save_file, data will be written to the settings file. If you specify a relative path in save_file, it will be interpreted as being based on the environment variable PWD. PWD can be changed with the set command, and its default value is "/". If you wish to save a file named configN in the RTFS space or external memory, you need to specify the file's absolute path in save_file, not its relative path.

To send data using the POST method, specify content_type in a format that can be received by the HTTP server. One example of a string that can be specified for content_type is "application/x-www-form-urlencoded". The string specified in post_text and the content of post_file must also be in a format that conforms to content_type. (See Example of use 3 and 4) Since Shift-JIS is used as the internal Japanese Kanji code on the router, the string specified for content_type will be a Shift-JIS string. You can use the Kanji code conversion library to convert the Kanji code into UTF-8, etc.

This function does not support SSL communications.


[Return value]

HTTP request execution result and response data (Table type)

Contents of the return value table:

Field name Data type Content
rtn1 Logical type Result of sending HTTP request
  • true : Received the response successfully
  • false : Failed to receive the response
rtn2 Logical type File input/output result
  • true : File input/output successful
  • false : File input/output failed
err String type Error message
code Number type HTTP status code
header String type Response data header
body String type Response data body

rtn1 represents the send result of the HTTP request; it is set to true if the response data from the server is received successfully and set to false if it fails. rtn2 represents the file input/output result; it is set to true if the file input/output specified in save_file/post_file is successful, and false if it fails. If no file input/output operations are performed, rtn2 will not exist in the return value table. err will contain the error message when an error occurs while sending an HTTP request or during file input/output. If no error occurs, err will not exist in the return value table.

If the response data from the server is received successfully, code will contain the HTTP status code, header will contain the header of the response data, and body will contain the body of the response data. There is an upper limit for the volume of data that can be stored in body. The maximum volume is 2MB for RTX5000, 1MB for RTX810/FWX120. If the volume of the received data exceeds the maximum capacity of body, body will become nil. When saving a large volume of data such as image data, specify a file located on the external memory in save_file. Moreover, body will not exist in the return value table if method has been specified in HEAD or if the response data is empty.


[Note]

In this function, the combination of values stored in the return value table will vary depending on the response data reception result, the writing result to the file specified in save_file, the size of the received file, etc. For example, if the following is executed on RTX810:

req_table = {
	url = "http://www.exmaple.com/doc/manual.doc",
	method = "GET",
	save_file = "usb1:/docs/manual.doc"
}

rsp_table = rt.httprequest(req_table)

The following six patterns of execution results should be considered.

  1. If the file size of manual.doc is smaller than 1MB and writing to usb1: /dir2/manual.doc is successful
  2. If the file size of manual.doc is smaller than 1MB and writing to usb1: /dir2/manual.doc fails
  3. If the file size of manual.doc is larger than 1MB and writing to usb1: /dir2/manual.doc is successful
  4. If the file size of manual.doc is larger than 1MB and writing to usb1: /dir2/manual.doc fails
  5. If a connection to the server could not be established due to timeout
  6. If the specified file does not exist on the server

At this time, the return value table rsp_table will contain the following information. "-" indicates that the field does not exist in the table.

Condition rtn1 rtn2 err code header body
1 true true - 200 (Received header) (Received data body)
2 true false "File write error(usb1: /docs/manual.doc)" 200 (Received header) (Received data body)
3 false true "Received data size is exceeded the upper limit" 200 (Received header) -
4 false false "File write error(usb1: /docs/manual.doc)" 200 (Received header) -
5 false - "Request timeout" - - -
6 true true - 404 (Received header) (Received data body)

In condition 5, rtn2, which is the file input/output result, does not contain any value because a timeout occurred before any file input/output. Note that, as shown in condition 6, the HTTP request and writing of the received data to a file may succeed resulting in both rtn1 and rtn2 values to become true, even if the specified file was not found on the server.


[Example of use]
  1. Connect to the host http://www.exmaple1.com, obtain doc/manual.html and write it to usb1: /dir2/manual.html. Display an error string if the file writing fails.
    req_t = {
    	url = "http://www.exmaple.com/doc/manual.html",
    	method = "GET",
    	save_file = "usb1:/dir2/manual.html"
    }
    
    rsp_t = rt.httprequest(req_t)
    assert(rsp_t.rtn2, rsp_t.err)
    
  2. Connect to host http://www.exmaple2.net, obtain setting/config.txt using the authentication user name and password and write to config1.
    req_t = {
    	url = "http://www.exmaple2.net/setting/config.txt",
    	method = "GET",
    	auth_type = "basic",
    	auth_name = "user1",
    	auth_pass = "password1",
    	save_file = "config1"
    }
    
    rsp_t = rt.httprequest(req_t)
    if (rsp_t.rtn1) and (rsp_t.rtn2) then
    	rt.syslog("info", "[LUA] Download and write config success.")
    end
    
  3. Post the failure situation to the bulletin board when the tunnel goes into the link-down state.
    pattern = "IP Tunnel%[%d+%] Down"
    
    req_t = {
    	url = "http://xxx.com/bbs/bbs.cgi",
    	method = "POST",
    	auth_type = "basic",
    	auth_name = "user2",
    	auth_pass = "password2",
    	content_type = "application/x-www-form-urlencoded"
    }
    
    while (true) do
    	rtn, array = rt.syslogwatch(pattern, 1, 600)
    	if (rtn > 0) then
    		req_t.post_data = string.format("status=Tunnel Down: %s\n", string.match(array[1], pattern)))
    		rt.httprequest(req_t)
    	end
    end
    
  4. Upload the settings file to the server. The script shown in the sample is being executed on the server side.
    ---------------------------------------------------- 
    -- A function that creates the data to be uploaded 
    ---------------------------------------------------- 
    
    -- A function that creates a file name. 
    function make_filename(name)
    	local t = os.date("*t")
    	return string.format("%s_%d%02d%02d%02d%02d%02d.txt",
    			name, t.year, t.month, t.day, t.hour, t.min, t.sec)
    end 
    
    -- A function that creates a boundary string. 
    function make_boundary()
    	math.randomseed(os.time())
    	return string.format("__________%d", math.random(999999))
    end 
    
    -- A function that creates the data to be uploaded. 
    function make_data(f, d, b)
    	local disp = string.format("Content-Disposition: form-data; name=\"config\"; filename=\"%s\"\r\n", f)
    	local type = string.format("Content-type: text/plain\r\n\r\n")
    	return string.format("--%s\r\n%s%s%s\r\n--%s--\r\n\r\n", b, disp, type, d, b)
    end
    
    
    ---------------------------------------------------- 
    -- Script that uploads the settings file 
    ---------------------------------------------------- 
    
    -- Create an HTTP request table. 
    req_t = {
    	url = "http://www.xxx.net/upload_cfg.cgi",
    	method = "POST"
    }
    bound = make_boundary()
    req_t.content_type = "multipart/form-data; boundary=" .. bound 
    
    -- Create the file name to be uploaded. 
    fname = make_filename("config") 
    
    --  Obtain the settings by executing the show config command. 
    rtn, str = rt.command("show config")
    if (rtn) and (str) then 
    	-- Create the data to be uploaded. 
    	req_t.post_text = make_data(fname, str, bound) 
    
    	-- Upload the data that have been created. 
    	rsp_t = rt.httprequest(req_t)
    
    	if (rsp_t.rtn1) then
    		print("Upload success : ", fname)
    	else
    		print("Upload failed.")
    	end
    else
    	print("Upload failed.")
    end
    

Socket Communication Library

The socket communication library is port of the LuaSocket library functions written in C. The LuaSocket version is 2.0.2.

The Lua Socket includes the library functions in C language and the library functions of Lua language. The library functions in C language provide low-level functions such as the one that calls a socket system call. The library functions in Lua language provide functions to use applications including HTTP, FTP, and SMTP.
To Yamaha router, the LuaSocket library functions written in C are ported as APIs. Therefore, the scripts available on the LuaSocket website cannot be used directly for the library functions written in Lua. Use the LuaSocket module file below for Yamaha routers. See the LuaSocket reference for more information on the library functions written in Lua.

LuaSocket module file for the Yamaha router

In this library, you create socket objects and establish object-based communications. The objects have different properties for each protocol, and their states can be changed by specific functions.

  • TCP
    The types of objects used are as described below. Commonly in TCP, a client initiates TCP communication, and a server waits for incoming connections. However, the "server" and "client" of the following objects are based on a concept different from TCP.
    • Master object:
      An object generated by rt.socket.tcp().
    • Server object:
      An object that is in a standby state for TCP connections.
      When the master object calls tcp:listen() and goes into connection standby state, it will change into a server object.
    • Client object:
      An object that is connected to the remote host and is ready to send and receive data. The master object calls connect and changes to a client object; or accept is executed on the server object, and a client object is returned when the connection is established.
  • UDP
    There are two types of UDP objects as described below.
    • connected object:
      An object that only communicates with a specific host. When an unconnected object specifies the connection peer using setpeername, it will change into a connected object. In this object, you need to use the send and receive functions for sending/receiving data.
    • unconnected object:
      An object that can communicate with any host.
  • MIME
    A group of functions that are used for encoding/decoding in Base64 or Quoted-Printable, inserting new lines into outgoing messages, and converting line feed codes.

[Notes]
  • To access a port specified in LuaSocket from outside of the interface with NAT (or IP masquerade), you will need to configure a static NAT (or static masquerade).
  • To prevent a malfunction, make sure that the port numbers specified in LuaSocket and the port numbers used by the router functions are different.
    The port numbers used by the functions available on the router are as described below. Each model incorporates different functions and the actual port numbers used will vary depending on whether particular functions are used or not. However, you should avoid using port numbers that are listed in the table below to prevent dependency on any model or settings.
    * The (*) symbol in the table indicates that the used port number can be changed using a command.

    Protocol Function name Port number
    TCP www settings 80 (*)
    TELNET server 23 (*)
    SSH server 22 (*)
    BGP 179
    PPTP 1723
    SIP 5060
    ONFS 49501, 49502 (*)
    IP masquerade 60000-64095, 49152-59999, 32096-49151 (*) (FWX120)
    TCP (Socket) 1024-5000
    UDP UDP ECHO 7
    Heartbeat 9
    DNS 53, Start point port: 10000-10999 (*)
    DHCP server 67
    DHCP client 68
    TFTP server 69
    SNMP 161
    IKE 500
    System log 514 (*)
    RIP 520
    RIPng 521
    DHCP6 client 546
    DHCP6 agent 547
    RADIUS 1645
    L2TP 1701
    UPnP 1900
    NetVolante DNS 2002 (*)
    MGCP 2427-2433
    NAT Traversal 4500
    Connection between data connection branches 4502
    RTP 5004-5059 (*)
    SIP 5060
    Heartbeat 2 8512
    QoS coupling (Load notification, Bandwidth detection) 59140 (*)
    UDP (Socket) 21024-25000
    IP masquerade 60000-64095, 49152-59999, 32096-49151 (*) (FWX120)

Generating a TCP Object

[Format]
rt.socket.tcp()
[Argument]

No


[Description]

Generates a TCP master object.
It subsequently changes to a server object by calling tcp:listen() after tcp:bind, or it changes to a client object by calling tcp:connect().


[Return value]
<< Multi-Value >>
  1. TCP master object (User data type)
  2. Error message

If the object generation is successful, the first return value will be a user data type master object and the second return value will be nil.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]
  • Generating a TCP object and wait for a connection

    tcp = rt.socket.tcp()
    tcp:setoption("reuseaddr", true)
    res, err = tcp:bind("192.168.100.1", 11111)
    if not res and err then
      print(err)
      os.exit(1)
    end
    res, err = tcp:listen()
    if not res and err then
      print(err)
      os.exit(1)
    end
    
    while 1 do
      control = assert(tcp:accept())
    
      raddr, rport = control:getpeername()
      print("remote host address:" .. raddr .. " port:" .. rport) 
    
      -- Set the reception timeout to 30 seconds. 
      control:settimeout(30)
      while 1 do
        msg, err, partial = control:receive()
    
        if (msg) then
          local data 
          -- Process the received data (The data is output to the console in this example). 
          print(msg) 
    
          -- Send a response. 
          sent, err = control:send(data)
          if (err) then
            print("send error(" .. err .. ")")
            control:close()
            break
          end
        else
          if (err ~= "closed") then
            print(os.date() .. "receive error(" .. err .. ")")
            if (partial) then
              print("receive partial data(" .. partial .. ")")
            end
          end
          control:close()
          break;
        end
      end
    end
    
  • Creating a TCP object, connecting to and transferring data to the remote host

    tcp = rt.socket.tcp()
    
    res, err = sock:connect("192.168.100.1", 11111)
    if not res then
      print("connect error(" .. err .. ")")
      os.exit(1)
    end
    
    print("Connected remote host:" ..host.. " port:" .. port)
    
    lhost, lport = s:getsockname()
    s:settimeout(5)
    s:setoption("tcp-nodelay", true) 
    
    -- Send data. 
    sent, err = s:send("test\n")
    if (err) then
      print("send error(" .. err .. ")")
      s:close()
      os.exit(1)
    end 
    
    -- Receive a response from the server.
    data, err, partial = s:receive()
    if (err) then
      print("receive error("..err..")")
      if (partial) then
        print("receive partial data("..partial..")")
      end
    end 
    -- Process the received data. 
    ...
    
    s:close()
    

Generating a UDP Object

[Format]
rt.socket.udp()
[Argument]

No


[Description]

Generates a UDP object.


[Return value]
<< Multi-Value >>
  1. UDP object (User data type)
  2. Error message

If the object generation is successful, the first return value will be a user data type UDP object and the second return value will be nil.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]
  • Generating an UDP object and waiting for data from the remote host

    host = "192.168.100.1"
    port = 22222
    
    udp = rt.socket.udp()
    res, err = udp:setsockname(host, port)
    if (err) then
      print("setsockname error(" .. err .. ")")
      udp:close()
      os.exit(1)
    end
    
    lhost, lport = udp:getsockname()
    print("Bind to host:" ..lhost.. " and port:" ..lport)
    
    while 1 do
      dgram, ip, port = udp:receivefrom()
      if (dgram ~= nil) then 
        -- Process the received data.
        -- (Here, as an example, the data is output to the console and the received string is returned directly to the peer). 
        print("Received '" .. dgram .. "' from " .. ip .. ":" .. port)
        udp:sendto(dgram, ip, port)
      else
        print(ip)
        udp:close()
        os.exit(0)
      end
    end
    
  • Generating an UDP object and communicating with the remote host

    udp = rt.socket.udp()
    udp:setpeername("192.168.100.1", 22222)
    
    rhost, rport = udp:getpeername()
    print("remote host:" .. rhost .. " port:" .. rport) 
    
    -- Send the data. 
    res, err = udp:send("test")
    if (err) then
      print("send error(" .. err .. ")")
      udp:close()
      os.exit(1)
    end 
    
    udp:settimeout(10) -- Set the reception timeout to 10 seconds.
    
    -- Receive a response from the peer. 
    dgram, err = udp:receive()
    if (not dgram) and err then
      print("receive error("..err..")")
      udp:close()
      os.exit(1)
    end 
    -- Process the received data (The data is output to the console in this example). 
    print(dgram)
    
    udp:close()
    

Waiting for the Socket State Change

[Format]
rt.socket.select(RECVT, SENDT[, TIMEOUT])
[Argument]
  • RECVT ... An array of objects (User data type) waiting for the import-ready state (Specify nil or an empty table if not waiting for import)
  • SENDT ... An array of sockets (User data type) waiting for the export-ready state (Specify nil or an empty table if not waiting for export)
  • TIMEOUT ... Number of seconds to wait for a state change (1 to 2147483647; unlimited if a negative number is set or if omitted)

[Description]

Monitors the sockets and returns an array of objects that have become readable/writable.


[Return value]
<< Multi-Value >>
  1. An array of objects that are ready for import
  2. An array of objects that are ready for export
  3. Error message

The integers and the object itself are the keys in the table returned as the object array.
The error message will contain "timeout" in the event of a timeout; it will be nil in all other cases.


[Example of use]

Waiting for a connection at multiple ports

function create(addr, port)
  s = rt.socket.tcp()
  s:setoption("reuseaddr", true)
  res, err = s:bind(addr, port)
  if not res and err then
    print(err)
    os.exit(1)
  end
  res, err = s:listen()
  if not res and err then
    print(err)
    os.exit(1)
  end

  return s
end

server1 = create("192.168.100.1", 11111)
server2 = create("192.168.100.1", 11112)

while 1 do
  rcv, snd, err = rt.socket.select({server1, server2}, nil)

  if rcv[server1] then
    server = server1
  elseif rcv[server2] then
    server = server2
  else
    print("select error:"..err)
    os.exit(1)
  end

  control = assert(server:accept())

  raddr, rport = control:getpeername()
  print("remote host address:" .. raddr .. " port:" .. rport) 

  -- Clear the statistical information. 
  res = control:setstats(0, 0) 

  -- Set the reception timeout to 30 seconds. 
  control:settimeout(30)

  while 1 do
    msg, err, partial = control:receive()

    if (msg) then 
      -- Process the received data (The data is output to the console in this example). 
      print(msg) 

      -- Send a response. 
      sent, err = control:send("response\n")
      if (err) then
        print("send error(" .. err .. ")")
        control:shutdown()
        break
      end
    else
      if (err ~= "closed") then
        print(os.date() .. "receive error(" .. err .. ")")
        if (partial) then
          print("receive partial data(" .. partial .. ")")
        end
      end
      control:shutdown()
      break;
    end
  end

  rcv, snd, alive = control:getstats() 
  -- Display the statistical information. 
   print("receive: " .. rcv .. "bytes, send: " .. snd .. "bytes, alive time: " .. alive .. "sec")

end

Converting Host Name into IP Address

[Format]
rt.socket.dns.toip(HOSTNAME)
[Argument]
  • HOSTNAME ... IPv4 address or host name

[Description]

Converts the host name into the IP address.


[Return value]
<< Multi-Value >>
  1. Ipv4 address
  2. Information from the resolver

If successful, the first return value will be the IPv4 address and the second return value will contain all information from the resolver. The information from the resolver is returned in the following table.

Key string Setting value Type
name The official name of the host. String type
alias The alias of the host.
(*) An empty table will be returned because the alias of a host cannot be obtained on Yamaha routers.
Array of the string types
ip Ipv4 address.
(*) An array will be returned, but there will only be one Ipv4 address.
Array of the string types

If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]
host = "example.com" -- Specify the host name. 
ip, tbl = rt.socket.dns.toip(host)
if ip then 
  print(ip) -- The IP address is returned if successful.
end

Converting IP Address into Host Name

[Format]
rt.socket.dns.tohostname(ADDRESS)
[Argument]
  • ADDRESS ... IPv4 address or host name

[Description]

Converts the IP address into the host name.


[Return value]
<< Multi-Value >>
  1. Host name
  2. Information from the resolver

If successful, the first return value will be the host name and the second return value will contain all information from the resolver. The information from the resolver is returned in the following table.

Key string Setting value Type
name The official name of the host. String type
alias The alias of the host.
(*) An empty table will be returned because the alias of a host cannot be obtained on Yamaha routers.
Array of the string types
ip Ipv4 address.
(*) An array will be returned, but there will only be one Ipv4 address.
Array of the string types

If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]
ip = "10.0.0.1" -- Specify the IP address.
host, tbl = rt.socket.dns.tohostname(ip)
if host then
  print(host) -- The host name is returned if successful.
end

Returning the Host Name of a Device

[Format]
rt.socket.dns.gethostname()
[Argument]

No


[Description]

Returns the host name of a device.

The NetVolante DNS or the host name of the router itself set by the ip host command will be returned.


[Return value]
<< Multi-Value >>
  1. Host name
  2. Error message

If successful, the first return value will return the host name and the second return value will be nil.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]
host, err = rt.socket.dns.gethostname(host)
if host then 
  print(host) -- The host name of the router itself is returned if successful.
end

Sleep

[Format]
rt.socket.sleep(SECONDS)
[Argument]
  • SECONDS ...Number of sleep seconds (1 to 2147483647)

[Description]

Puts the calling Lua task to the sleep state for the duration of SECONDS.


[Return value]

No


[Example of use]
-- Send UDP packets every 10 minutes. 
udp = rt.socket.udp()
udp:setpeername("192.168.100.1", 22222)

while true do 
-- Send the data. 
  res, err = udp:send("notification")
  if (err) then
    print("send error(" .. err .. ")")
    udp:close()
    os.exit(1)
  end

  rt.socket.sleep(600)
end

udp:close()

Returning the Number of Seconds Elapsed after Starting the Router

[Format]
rt.socket.gettime()
[Argument]

No


[Description]

Returns the number of seconds elapsed after starting the router.


[Return value]

Number of seconds elapsed after starting the router


[Example of use]
t1 = rt.socket.gettime()
-- Perform some processing. 
...
t2 = rt.socket.gettime() - t1
print("execute time:" .. t2)

Generating a Function that is Processed before Notifying an Exception Error

[Format]
rt.socket.newtry(FINALIZER)
[Argument]
  • FINALIZER ... A function that is called before notifying an exception error

[Description]

Generates a function that is processed before notifying an exception error.

FINALIZER is a function that is called in the protected mode before notifying an exception error.


[Return value]

Returns a function that performs the processing when an exception occurs.


[Example of use]
c = rt.socket.tcp()
sample = rt.socket.protect(function() 
    -- Generate a function that calls close() in the event of an error. 
    local try = rt.socket.newtry(function() c:close() end) 
    -- The socket is always closed in the event of an error. 
    try(c:connect("192.168.100.1", 8888))
    try(c:send("test\r\n"))
    local answer = try(c:receive()) 
    -- Process the received data. 
    ...
    return c:close()
end)

ret, err = sample()
if not ret and err then
    print(err)
end

Calling a Function in Protected Mode

[Format]
rt.socket.protect(FUNC)
[Argument]
  • FUNC ... A function that notifies an exception error

[Description]

Calls the function FUNC in protected mode.

As a FUNC, specifies the function that notifies an exception error by calling newtry, assert, or error.


[Return value]

Returns a function that performs similar processing as FUNC but does not notify exceptions. The function, if an error occurs, returns nil as the first return value and the error message as the second return value.


[Example of use]

See rt.socket.newtry().


Discarding an Argument

[Format]
rt.socket.skip(NUM[, RET1, RET2, ..RETN])
[Argument]
  • NUM ... Number of arguments to be discarded (1 to 2147483647)
  • RET1, RET2 ..RETN ... Argument

[Description]

Discards the specified number of arguments and returns the remaining arguments.

Of the enumerated arguments (RET1, RET2..), the first NUM arguments and the remaining arguments from RET\[NUM+1] to RETN will be returned. Using this function eliminates the need to prepare a dummy variable to store an unwanted function return value.


[Return value]
<< Multi-Value >>
  1. NUM+1th argument
  2. From then on, the NUM+2th argument, NUM+3th argument and so on will follow for as long as such arguments exist.

If there are arguments after the NUM+1th argument, then the arguments after the NUM+1th argument will be returned. There will be no return value when NUM is equal to or greater than the argument or when NUM is a negative number.


[Example of use]

Discard the numeric value representing the position matching the pattern (i.e., the first two return values of string.find()) and only receive the captured string.

-- Discard the numerical value representing the location where the pattern is matched, and return only the captured string. 
r = rt.socket.skip(2, string.find("ABCDE", "B(.)D"))
print(r) 

-- The following captured character is displayed in the console. 
-- C

Version of the Socket Communication Library

[Format]
rt.socket._VERSION
[Argument]

No


[Description]

Returns the version of the LuaSocket being used as the socket communication library.


[Return value]

Version number


Receiving a Connection from the TCP Client

[Format]
tcp:accept()
[Argument]

No


[Description]

A method for the TCP object tcp that waits for a connection from the TCP client and returns a client object after the connection has completed.

This function can be used in a server object.


[Return value]
<< Multi-Value >>
  1. Client object
  2. Error message

If the connection has completed, the first return value will return a user data type client object and the second return value will be nil.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.tcp().


Assigning an IP Address and Port Number to an Object

[Format]
tcp:bind(ADDRESS, PORT)
[Argument]
  • ADDRESS ... IPv4 address or host name
  • PORT ... Port number (0 to 65535)

[Description]

A method for the object tcp in TCP that assigns an IP address and port number to a master object.

If "*" is specified for ADDRESS, it will be assigned to all interfaces using INADDR_ANY. If 0 is specified for PORT, the system will automatically assign the port number to be in the range between 1024 and 5000.

If the IP address is to be determined dynamically, such as assigned from the DHCP server, “*” should be specified for ADDRESS.

This function can be used in a master object.


[Return value]
<< Multi-Value >>
  1. 1 or nil
  2. Error message

If successful, the first return value will return 1 and the second return value will be nil.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.tcp().


Setting an Object to Connection Waiting State

[Format]
tcp:listen(BACKLOG)
[Argument]
  • BACKLOG ... Maximum length of the pending connection queue (0 to 128) (32 if omitted)

[Description]

A method for the TCP object tcp that sets the TCP object to connection waiting state.

This function can be used in a master object, and it changes into a server object if successful.


[Return value]
<< Multi-Value >>
  1. 1 or nil
  2. Error message

If successful, the first return value will return 1 and the second return value will be nil.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.tcp().


Closing a TCP Object

[Format]
tcp:close()
[Argument]

No


[Description]

A method for the TCP object tcp that closes a TCP object.

The sockets used in the object will be closed, and the addresses and port numbers assigned for the object will become available in other applications.

This function can be used in a master object, server object or client object.


[Return value]

1 is returned.


[Example of use]

See rt.socket.tcp().


Connecting to a Remote Host

[Format]
tcp:connect(ADDRESS, PORT)
[Argument]
  • ADDRESS ... IPv4 address or host name
  • PORT ... Port number (1 to 65535)

[Description]

A method for the TCP object tcp that establishes a connection to the remote host.

If the connection is successful, the master object that called the function will change into a client object.

This function can be used in a master object.


[Return value]
<< Multi-Value >>
  1. 1 or nil
  2. Error message

If successful, the first return value will return 1 and the second return value will be nil.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.tcp().


Obtaining the Information of the Connection Peer

[Format]
tcp:getpeername()
[Argument]

No


[Description]

A method for the TCP object tcp that obtains the information of the connected remote host.

This function can be used in a client object.


[Return value]
<< Multi-Value >>
  1. IP address or nil
  2. Port number or error message

If successful, the first return value will be the IP address and the second return value will return the port number.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.tcp().


Obtaining the Information of an Object

[Format]
tcp:getsockname()
[Argument]

No


[Description]

A method for the TCP object tcp that obtains the information assigned to an object.

This function can be used in a master object, server object or client object.


[Return value]
<< Multi-Value >>
  1. IP address or nil
  2. Port number or error message

If successful, the first return value will be the IP address and the second return value will return the port number.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.tcp().


Obtaining the Statistics of an Object

[Format]
tcp:getstats()
[Argument]

No


[Description]

A method for the TCP object tcp that obtains the statistics sent/received by an object, including the number of bytes and survival period.

This function can be used in a master object, server object or client object.


[Return value]
<< Multi-Value >>
  1. Bytes received
  2. Bytes sent
  3. Socket survival time (seconds)

[Example of use]

See rt.socket.select().


Receiving Data

[Format]
tcp:receive([PATTERN[, PREFIX]])
[Argument]
  • PATTERN ... Specify the data reception pattern ('*l' if omitted).
    • '*a' ... Read data until the connection is closed.
    • '*l' ... Read one line of text ending with LF (0x0a). CR and LF are not included in the received return value data.
    • Numeric value ... Read the specified bytes of data.
  • PREFIX ... A string to be appended to the beginning of the received data.

[Description]

A method for the TCP object tcp that reads data from an object.

The data are read in the reception pattern specified in PATTERN. If PREFIX has been specified, PREFIX will be appended to the beginning of the received data.

This function can be used in a client object.


[Return value]
<< Multi-Value >>
  1. Received data (String type)
  2. Error message
  3. Data received before the error (String type)

If successful, the first return value will return the received data and the second and third return values will be nil.
If an error occurs, the first return value will be nil and the second return value will contain the error message. The third return value will return the data received before the error. If the connection is closed before the reception of data in the specified pattern completes, "closed" will be returned as the error message.


[Example of use]

See rt.socket.tcp().


Sending Data

[Format]
tcp:send(DATA[, TOP[, TAIL]])
[Argument]
  • DATA ... Data to be sent (String type)
  • TOP ... First position of DATA to be sent (1 if omitted)
  • TAIL ... Last position of DATA to be sent (End of DATA if omitted)

[Description]

A method for the TCP object tcp that sends data.

If TOP and TAIL are selected, the data that exist between the TOP and TAIL positions of DATA will be sent.
If a negative number is specified for TOP or TAIL, the sending position will be the end of DATA minus the specified number. The default value will be applied if the position does not fit inside DATA.
No data will be sent if the TAIL position comes before the TOP position.

This function can be used in a client object.


[Return value]
<< Multi-Value >>
  1. Position of the last sent byte or nil
  2. Error message
  3. Position of the last sent byte

If successful, the first return value will be the last position of the sent DATA and the second and third return values will be nil.
If an error occurs, the first return value will be nil, the second return value will be the error message, and the third value will be the last position of the data sent before the error occurred.


[Example of use]

See rt.socket.tcp().


Configuring the Object Options

[Format]
tcp:setoption(OPTION, VALUE)
[Argument]
OPTION VALUE Description
reuseaddr true Permit the re-use of local addresses
false Do not permit the re-use of local addresses
tcp-nodelay true Enable the Nagle algorithm
false Disable the Nagle algorithm
[Description]

A method for the object tcp in TCP that configures the options for the sockets included in an object.

These options are required in low-level and time-critical applications.

This function can be used in a server object and client object.


[Return value]

1 is returned if successful, and nil is returned in the event of an error.


[Example of use]

See rt.socket.tcp().


Resetting the Statistics

[Format]
tcp:setstats([RECEIVED[, SENT[, AGE]]])
[Argument]
  • RECEIVED ... Bytes received (Current bytes received if omitted)
  • SENT ... Bytes sent (Current bytes sent if omitted)
  • AGE ... Survival time (seconds) (Current survival time if omitted)

[Description]

A method for the TCP object tcp that acquires the statistics of an object.

For example, you can use this function to set RECEIVED and SENT to 0 to measure the amount of data sent/received during a given period of time.

This function can be used in a master object, server object or client object.


[Return value]

1 is returned if successful, and nil is returned in the event of an error.


[Example of use]

See rt.socket.select().


Configuring the Timeout Period

[Format]
tcp:settimeout(VALUE[, MODE])
[Argument]
  • VALUE ... Timeout period
    • Seconds (0 to 2147483647)
    • Block indefinitely if nil or negative number
  • MODE ... Timeout mode
    • 'b' ... Timeout period. Block timeout Specify the blocking time before an input/output operation is performed. (applicable if omitted)
    • 't' ... Specify the blocking time before returning from the library function.

[Description]

A method for the TCP object tcp that sets the timeout period of an object.

In an object is in its default state, all input/output operations are performed in blocking mode. Therefore, the execution of the send, receive, and accept functions will be blocked indefinitely until the command completion.

If a timeout period is set and the specified period expires, the blocked function will be stopped returning an error.

This function can be used in a master object, server object or client object.


[Return value]
<< Multi-Value >>
  1. 1 or nil
  2. Error message

If successful, the first return value will return 1 and the second return value will be nil. If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.tcp().


Blocking a Transfer

[Format]
tcp:shutdown([MODE])
[Argument]
  • MODE ... Blocking direction (String type)
    • 'both' ... Block send and receive (applicable if omitted)
    • 'send' ... Block send only
    • 'receive' ... Block receive only

[Description]

A method for the TCP object tcp that blocks the sending or receiving of data, or both.

This function can be used in a client object.


[Return value]

1 is returned.


[Example of use]

See rt.socket.select().


Closing a UDP Object

[Format]
udp:close()
[Argument]

No


[Description]

A method for the UDP object udp that closes a UDP object.

The sockets used in the object will be closed, and the addresses and port numbers assigned for the object will become available in other applications.

This function can be used in connected and unconnected objects.


[Return value]

1 is returned.


[Example of use]

See rt.socket.udp().


Obtaining the Information of the Connection Peer

[Format]
udp:getpeername()
[Argument]

No


[Description]

A method for the UDP object udp that obtains the information of the connected remote host.

This function can be used in a connected object.


[Return value]
<< Multi-Value >>
  1. IP address or nil
  2. Port number or error message

If successful, the first return value will be the IP address and the second return value will return the port number.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.udp().


Obtaining the Information of an Object

[Format]
udp:getsockname()
[Argument]

No


[Description]

A method for the UDP object udp that obtains the IP address and port number assigned to an object.

In UDP, no addresses are bound until either setsockname or sendto is called first. If neither is called, a wildcard address and a temporary port number will be bound.

This function can be used in connected and unconnected objects.


[Return value]
<< Multi-Value >>
  1. IP address or nil
  2. Port number or error message

If successful, the first return value will be the IP address and the second return value will return the port number.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.udp().


Receiving Data

[Format]
udp:receive([SIZE])
[Argument]
  • SIZE ... Maximum size of received datagram (1 .. 2048, 2048 bytes if omitted)

[Description]

A method for the UDP object udp that reads data from an object.

Use either the data size specified in SIZE or the default maximum size (2048 bytes), whichever is smaller.

This function can be used in connected and unconnected objects.
A connected object only receives data from a connected peer, and an unconnected object receives data from any host.


[Return value]
<< Multi-Value >>
  1. Received data (String type)
  2. Error message

If successful, the first return value will return the received data and the second and third return values will be nil.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.udp().


Receiving Data

[Format]
udp:receivefrom([SIZE])
[Argument]
  • SIZE ... Maximum size of received datagram (1 .. 2048, 2048 bytes if omitted)

[Description]

A method for the UDP object udp that reads data from an object.

Use either the data size specified in SIZE or the default maximum size (2048 bytes), whichever is smaller.

While udp:receive() only returns the data it received, udp:receivefrom() returns the received data as well as the remote information (IP address and port number).

This function can be used in an unconnected object.


[Return value]
<< Multi-Value >>
  1. Received data (String type)
  2. IP address or error message
  3. Port number

If successful, the first return value will return the received data, the second return value will return the IP address of the host that sent the data, and the third return value will return the port number.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.udp().


Sending Data

[Format]
udp:send(DATAGRAM)
[Argument]
  • DATAGRAM ... Data to be sent (String type)

[Description]

A method for the UDP object udp that sends data.

No data will be blocked when sending via UDP.

This function can be used in a connected object.


[Return value]
<< Multi-Value >>
  1. Number of bytes sent or nil
  2. Error message

If successful, the first return value will return the number of bytes sent and the second return value will be nil.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.udp().


Sending Data to the Specified Host

[Format]
udp:sendto(DATAGRAM, IP, PORT)
[Argument]
  • DATAGRAM ... Data to be sent (String type)
  • IP ... Destination Ipv4 address
  • PORT ... Destination port number (1 to 65535)

[Description]

A method for the UDP object udp that sends data to the specified destination.

An IP address is specified for IP.

No data will be blocked when sending via UDP.

This function can be used in an unconnected object.


[Return value]
<< Multi-Value >>
  1. Number of bytes sent or nil
  2. Error message

If successful, the first return value will return the number of bytes sent and the second return value will be nil.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.udp().


Specifying/Resetting the Communication Peer

[Format]
udp:setpeername(ADDRESS, PORT)
[Argument]
  • ADDRESS ... IP address or host name, '*'
  • PORT ... Port number (1 to 65535)

[Description]

A method for the UDP object udp that specifies or resets the destination that the object will be communicating with.

This function can be used in connected and unconnected objects.
It changes into a connected object when an association is made with the peer specified in the unconnected object. In a connected object, you need to use the send and receive functions for sending/receiving data.
To reset the association with the communication peer in a connected object, you need to specify '*' for ADDRESS and omit PORT. It will change into an unconnected object when the association with the communication peer is reset.


[Return value]
<< Multi-Value >>
  1. 1 or nil
  2. Error message

If successful, the first return value will return 1 and the second return value will be nil.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.udp().


Assigning an IP Address and Port Number to an Object

[Format]
udp:setsockname(ADDRESS, PORT)
[Argument]
  • ADDRESS ... IP address or host name, '*'
  • PORT ... Port number (0 to 65535)

[Description]

A method for the UDP object udp that assigns an IP address and port number to an object.

If "*" is specified for ADDRESS, associations will be made for all local interfaces using INADDR_ANY.
If PORT is set to 0, a temporary port number will be assigned by the system. The assigned port number will be in the range between 21024 and 25000.

This function can only be used once before sending data using an unconnected object. If this function is omitted, the system will make associations for all local interfaces and temporary port assignments when sending data using UDP.


[Return value]
<< Multi-Value >>
  1. 1 or nil
  2. Error message

If successful, the first return value will return 1 and the second return value will be nil.
If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.udp().


Configuring the Timeout Period

[Format]
udp:settimeout(VALUE)
[Argument]
  • VALUE ... Timeout period
    • Seconds (0 to 2147483647)
    • Block indefinitely if nil or negative number

[Description]

A method for the UDP object udp that sets the timeout period of an object.

In an object is in its default state, all input/output operations are performed in blocking mode. Therefore, the execution of the receive and receivefrom functions will be blocked indefinitely until the command completion.
Since send and sendto are not blocked in UDP, sending of data will not be affected by this function.

If a timeout period is set and the specified period expires, the blocked function will be stopped returning an error.

This function can be used in connected and unconnected objects.


[Return value]
<< Multi-Value >>
  1. 1 or nil
  2. Error message

If successful, the first return value will return 1 and the second return value will be nil. If an error occurs, the first return value will be nil and the second return value will contain the error message.


[Example of use]

See rt.socket.udp().


Encoding in Base64

[Format]
rt.mime.b64(DATA1[, DATA2])
[Argument]
  • DATA1, DATA2 ... A string or binary data to be encoded (String type)

[Description]

Performs encoding in Base64.

If DATA 2 is specified, DATA1 and DATA2 will be linked and encoded in Base64. No padding will be performed, and the remaining byte data (string type) that could not be encoded will be stored in the second return value.
If DATA2 is omitted, DATA1 will be encoded in Base64. Padding will be added as required at this time.


[Return value]
<< Multi-Value >>
  1. Encoded data
  2. nil or the remaining byte data that could not be encoded (String type)

If DATA2 is omitted, the first return value will contain the data from the encoded DATA1. At this time, padding will be added as needed so that the entire DATA1 will be encoded. The second return value will be nil.
If DATA2 is specified, the first return value will contain the encoded string from the DATA1/DATA2-linked data. The remaining string that cannot be encoded will be stored in the second return value. No padding will be added.


[Example of use]
estr = rt.mime.b64("test")
print(estr)
-- estr = dGVzdA==

Enabling the Transfer of Messages Containing <CRLF.CRLF>

[Format]
rt.mime.dot(NUM[, DATA])
[Argument]
  • NUM ... Number of line feeds at the end of the immediately preceding data
  • DATA ... Message to be transferred (String type)

[Description]

Converts the relevant sections to enable the transfer of messages containing <CRLF.CRLF>.
* CRLF: * CRLF: A code representing a line feed (CR: 0x0D, LF: 0x0A in ASCII codes)

In SMTP, the message completion is notified to the peer by sending <CRLF.CRLF>. The data will only be sent halfway if this pattern is included in the middle of the message that is being sent.
If CRLF is followed by a period (.) in the outgoing message, another period (.) should be added immediately after it so that the entire message will be sent.

If the outgoing message is split into multiple blocks, a numeric value should be specified for NUM as follows, according to the pattern of the string at the end of the immediately preceding block.

NUM Description
1 If the last 1 byte of the immediately preceding block is CR
2 If the last 2 bytes of the immediately preceding block are CRLF
0 If neither of the above is applicable

SMTP message body is defined to start with CRLF. Therefore, to convert it into a correct message, you need to specify 2 for NUM when calling this function for the first time.


[Return value]
<< Multi-Value >>
  1. Converted message (String type)
  2. Number of line feed codes at the end of DATA

The first return value will contain the message converted from DATA and the second return value will contain the number of line feed codes at the end of DATA. The number of line feed codes (i.e., the second return value) will be 1 if DATA ends with CR and 2 if it ends with CRLF. Even if there is LF at the end, the second return value will be 0 if it is not immediately preceded by CR.
If DATA is nil or omitted, the first return value will return nil and the second return value will be 2.


[Example of use]
-- It is described as CR="\r", LF="\n" in Lua script. 
dotstr, num = rt.mime.dot(2, ".\r\nSend message.\r\n.\r\n.test\r\n")
print(dotstr) 

--[[ The string after conversion. ".” is added if CRLF is followed by ".". 
..
Send message.
..
..test
]]

Converting a Line Feed Code

[Format]
rt.mime.eol(CODE[, DATA[, MARKER]])
[Argument]
  • CODE ... The ASCII code of the final character of the immediately preceding block data (String type), if the string to be converted has been split into multiple blocks
  • DATA ... The string to be converted
  • MARKER ... Line feed code (CRLF if omitted)

[Description]

Converts a line feed code.
A line feed code refers to one of the following: CR, LF, CRLF or LFCR.

A line feed code included in DATA will be replaced by the line feed code specified in MARKER.
If the string to be converted has been split into multiple blocks, CODE will contain the second return value from when the immediately preceding data was converted using this function. This should be set to 0 if it is the first string or if it has not been split into multiple blocks.


[Return value]
<< Multi-Value >>
  1. The string after line feed code conversion
  2. If there is a line feed code at the end, its ASCII codes will be returned. 0 will be returned in all other cases.

If DATA is nil or omitted, the first return value will return nil and the second return value will be 0.


[Example of use]
-- It is described as CR="\r", LF="\n" in Lua script. 
str, num = rt.mime.eol(0, "test\rexample\rtest\r", "\r\n")
print(str) 
-- Visualize and display the line feed code. 
print(string.gsub(str, "\r\n", "\\r\\n")) 

--[[ Conversion result (The string output to the console):
test
example
test

test\r\nexample\r\ntest\r\n     3
]]

Encoding in Quoted-Printable

[Format]
rt.mime.qp(DATA1[, DATA2[, MARKER]])
[Argument]
  • DATA1, DATA2 ... A string or binary data to be encoded (String type)
  • MARKER ... Line feed code (CRLF if omitted)

[Description]

Performs encoding in Quoted-Printable.

If DATA 2 is specified, DATA1 and DATA2 will be linked and encoded in Quoted-Printable. No padding will be performed, and the remaining byte data that could not be encoded will be stored in the second return value.
If DATA2 is, DATA1 will be encoded in Quoted-Printable. Padding will be added as required at this time.

If a line feed code (CRLF) exists in DATA1 or DATA2, it will be replaced by the line feed code specified in MARKER.


[Return value]
<< Multi-Value >>
  1. Encoded string
  2. nil or the remaining byte data that could not be encoded (String type)

If DATA2 is omitted, the first return value will contain the string from the encoded DATA1. At this time, padding will be added as needed so that the entire DATA1 will be encoded. The second return value will be nil.
If DATA2 is specified, the first return value will contain the encoded string from the DATA1/DATA2-linked data. The remaining data that cannot be encoded will be stored in the second return value. No padding will be added. If there is a data block following, this function should be called specifying the second return value for DATA1 of the first argument and the following data block for DATA2.


[Example of use]
estr, rem = rt.mime.qp("test") 
print(estr)
-- estr = =83e=83X=83g

Inserting a New Line into a String Encoded in Quoted-Printable

[Format]
rt.mime.qpwrp(NUM[, DATA[, LENGTH]])
[Argument]
  • LEFT_LEN ... The superfluous length after subtracting the length of the final line of the first return value from LENGTH (Numeric type)
  • DATA ... A string encoded in Quoted-Printable
  • LENGTH ... Line length (76 if omitted)

[Description]

Inserts a new line into a string encoded in Quoted-Printable at the specified length.

If the length specified in LENGTH is reached in the middle of a string encoded in Quoted-Printable (such as "=XX”), a new line will be inserted n front of the characters encoded in Quoted-Printable. If the string contains a line feed code (CRLF), a new line will be inserted in the position of the line feed code even if the line is shorter than LENGTH.

If the string has been split into multiple blocks, LEFT_LEN should be set to the superfluous length of the final line that is output when the immediately preceding block is processed using this function. The superfluous length will be returned as the second return value when the immediately preceding block is processed using this function.
If the string to be processed is the first data or if it is not split into multiple blocks, NUM should be set to 0.


[Return value]
<< Multi-Value >>
  1. A string with a new line inserted at the specified length
  2. The superfluous length after subtracting the length of the final line of the first return value from LENGTH (Numeric type)

The first return value will contain a string (i.e., DATA with a new line inserted at the specified length), and the second value will contain the value of LENGTH minus the length of the final line. If any chunks exist after DATA, the second return value should be specified as LEFT_LEN of the first argument.


[Example of use]
--[[ 
--Array of the strings encoded with Quoted-Printable:

tbl = {
 "=82=A0=82=A2=82=A4=82=A6=82=A8=82=A9=82=AB=82=AD=82=AF=82=B1",
 "=82=B3=82=B5=82=B7=82=B9=82=BB=82=BD=82=BF=82=C2=82=C4=82=C6"
}

estr = {}
len = 0
for i, v in ipairs(tbl) do
  estr[i], len = rt.mime.qpwrp(len, v, 16)
end
print(estr[1] .. estr[2]) 

--[[ Conversion result (The string output to the console): 
=
=82=A0=82=A2=82=
=A4=82=A6=82=A8=
=82=A9=82=AB=82=
=AD=82=AF=82=B1=
=82=B3=82=B5=82=
=B7=82=B9=82=BB=
=82=BD=82=BF=82=
=C2=82=C4=82=C6
]]

Decoding in Base64

[Format]
rt.mime.unb64(DATA1[, DATA2])
[Argument]
  • DATA1, DATA2 ... Data encoded in Base64 (String type)

[Description]

Decodes a string or byte data encoded in Base64.

If DATA 2 is specified, DATA1 and DATA2 will be linked and decoded. The remaining string that could not be decoded will be stored in the second return value.
If DATA2 is omitted, only DATA1 will be decoded.


[Return value]
<< Multi-Value >>
  1. Decoded data (String type)
  2. nil or the remaining string that could not be decoded

If DATA2 is omitted, the first return value will contain the data from the decoded DATA1. The second return value will be nil at this time.
If DATA2 is specified, the first return value will contain the decoded data from the DATA1/DATA2-linked string. The remaining string that cannot be decoded will be stored in the second return value.


[Example of use]
-- Decode the string encoded in base64. 
estr = "gqKC64LNgsmC2YLWgsY="

str = rt.mime.unb64(estr)
print(str) 

--[[The decoding result (The string output to the console):

]]

Decoding in Quoted-Printable

[Format]
rt.mime.unqp(DATA1[, DATA2])
[Argument]
  • DATA1, DATA2 ... Data encoded in Quoted-Printable (String type)

[Description]

Decodes a string or byte data encoded in Quoted-Printable.

If DATA 2 is specified, DATA1 and DATA2 will be linked and decoded in Quoted-Printable. The remaining string that could not be decoded will be stored in the second return value.
If DATA2 is omitted, DATA1 will be decoded in Quoted-Printable.


[Return value]
<< Multi-Value >>
  1. Decoded data (String type)
  2. nil or the remaining string that could not be decoded

If DATA2 is omitted, the first return value will contain the data from the decoded DATA1. The second return value will be nil.
If DATA2 is specified, the first return value will contain the decoded data from the DATA1/DATA2-linked data. The remaining string that cannot be encoded will be stored in the second return value.


[Example of use]
--[[ 
- Decode a string encoded in Quoted-Printable.
data = "=83e=83X=83g"

str = rt.mime.unqp(data)
print(str) 

--[[ Output result to the console:
test
]]

Inserting a New Line into the Text

[Format]
rt.mime.wrp(NUM[, DATA[, LENGTH]])
[Argument]
  • LEFT_LEN ... The superfluous length after subtracting the length of the final line of the first return value from LENGTH (Numeric type)
  • DATA ... A string
  • LENGTH ... Line length (76 if omitted)

[Description]

Inserts a new line into DATA at the specified length.

A new line is inserted into the string at the specified length in LENGTH. If the string specified in DATA contains a line feed code (CRLF), a new line will be inserted in the position of the line feed code even if the line is shorter than LENGTH.

If the string has been split into multiple blocks, LEFT_LEN should be set to the superfluous length of the final line that is output when the immediately preceding block is processed using this function. The superfluous length will be returned as the second return value when the immediately preceding block is processed using this function.
If the string to be processed is the first data or if it is not split into multiple blocks, NUM should be set to 0.


[Return value]
<< Multi-Value >>
  1. A string with a new line inserted
  2. The superfluous length after subtracting the length of the final line of the first return value from LENGTH (Numeric type)

The first return value will contain data (i.e., DATA with a new line inserted at the specified length), and the second value will contain the value of LENGTH minus the length of the final line. If any blocks exist after DATA, the second return value should be specified as LEFT_LEN of the first argument.


[Example of use]
-- An array of strings:
tbl = {
 "abcdefghijklmnopqrstuvwxyz",
 "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
 "0123456789"
}

estr = {}
len = 0
for i, v in ipairs(tbl) do
  estr[i], len = rt.mime.wrp(len, v, 10)
end

print(estr[1] .. estr[2] .. estr[3]) 


--[[ The result after line feed (The string output to the console):

abcdefghij
klmnopqrst
uvwxyzABCD
EFGHIJKLMN
OPQRSTUVWX
YZ01234567
89
]]

SYSLOG Message List

The following table shows the SYSLOG messages that are output after the API execution. The prefix "[LUA]" will be appended to the actual output message.

Level Output message Meaning
DEBUG Task(N) executed rt.command("COMMAND"): success The router command "COMMAND” was executed successfully in the Lua task having Lua task number N.
Task(N) executed rt.command("COMMAND"): failure Failed to execute the router command "COMMAND" in the Lua task having Lua task number N.
Task(N) executed rt.mail: true E-mail was successfully in the Lua task having Lua task number N.
Task(N) executed rt.mail: false Failed to send e-mail in the Lua task having Lua task number N.
Task(N) started rt.syslogwatch The SYSLOG monitoring was started in the Lua task having Lua task number N.
Task(N) detected timeout in rt.syslogwatch A timeout occurred in the SYSLOG monitoring being executed in the Lua task having Lua task number N.
Task(N) completed rt.syslogwatch The SYSLOG monitoring being executed in the Lua task having Lua task number N has completed.
Task(N) opened RESOURCE Opened the hardware/RESOURCE in the Lua task having Lua task number N.
Task(N) failed to open RESOURCE Failed to open the hardware/RESOURCE in the Lua task having Lua task number N.
Task(N) closed RESOURCE Closed the hardware/RESOURCE in the Lua task having Lua task number N.
Task(N) started rt.httprequest Sending of HTTP request was started in the Lua task having Lua task number N.
Task(N) detected timeout in rt.httprequest A timeout occurred in the sending of HTTP request or receiving of response data being executed in the Lua task having Lua task number N.
Task(N) completed rt.httprequest Sending of HTTP request and receiving of response data being executed in the Lua task having Lua task number N have completed.
Task(N) TCP(UDP) Initialize failed Failed to initialize TCP or UDP in the Lua task having Lua task number N.

In addition to the above, an INFO type error message will be output to the SYSLOG if the script cannot be executed due to incorrect API argument or script syntax error. See the Notes for details.


Return to Top