Настройка маршрутизаторов на основе openwrt

MTD (Memory Technology Device) and MTDSPLIT

The Linux kernel treats “raw/host-managed” flash memory (NOR and NAND alike) as an MTD (Memory Technology Device). An MTD is different to a block device or a character device.

On a common block device such as a hard drive, the storage space is split up into “blocks”, which are also named “sectors”, of a size of 512 Bytes or 4096 Bytes. Blocks do not get corrupted during common operation, but only exceptionally. In the very rare case this happens, the LBA hard disk controller takes care, that accesses to such a bad block are redirected to a replacement block. Block devices support 2 main operations — read a whole block and write a whole block. When a block device is partitioned, the information is stored in the MBR or the GPT.

Flash memory using MTD is different from this.

The storage space of a MTD is split up into “erase-blocks”, of a size of e.g 64 KiB, 128 KiB or much more, which themselves are split up into “blocks”, which are more correctly named “pages”, of smaller sizes.

A single “page” can be written to, but it cannot be overwritten, but instead the entire “erase block” that page is part of, has to be erased before it becomes possible to re-write its “pages”. Erase-blocks do become worn out after some number of erase cycles – typically 100K-1G for SLC NAND and NOR flashes, and 1K-10K for MLC NAND flashes. Erase-blocks may become bad (only NAND). In case of “FTL flash”, the controller should notice and avoid further access to bad erase-blocks. In case of “raw flash”, the operating system should deal with such cases.

MTD devices support 3 main operations — read from some offset within an erase block, write to some offset within an erase-block, and erase a whole erase-block.

The utility program mtd can be used to manage MTD devices.

MTD partitions

The MTD device is often subdivided into logical chunks of memory called partitions. Each partition start at the beginning of an erase-block and end at the end of an erase-block.

The partitioning of MTD devices is not stored in some MBR/GPT, but it is done in the Linux Kernel using MTD-specific partition parsers determining the location and size of these partitions. (sometimes the partitioning is implemented independently in the bootloader as well!).

The kernel boot process involves discovering of partitions within the NOR flash and it can be done by various target-dependent means:

  • some bootloaders store a partition table at a known location
  • some pass the partition layout via kernel command line
  • some pass the partition layout using Device Tree
  • some targets require specifying the kernel command line at the compile time (thus overriding the one provided by the bootloader).

Some of these schemes but not all are implemented in the mainline Linux kernel. The standard kernel can usually detect the top level coarse partitioning scheme, but not the more fine-grained sub-partitions.

MTDSPLIT

In order to deal with some of the custom flash partitioning schemes directly in the kernel, OpenWrt has developed which is a set of patches currently maintained separately from the mainline kernel, but used in OpenWrt to parse different flash layouts and split them into further “logical” partitions.

This is done recursively so that further split of a new “child” partition may be attempted. Whether an attempt is made to split a partition depends on the partition name.

  • is hardcoded to be split.
  • can be used to control whether attempt is made on partition. The most common splitting here is kernel, followed by padding, followed by SquashFS root filesystem, followed by padding, followed by free space.

During splitting, the kernel walks the erase blocks and detects magic bytes via parsers. Each partition type (usually determined from name) has its own list of parsers.

New partitions are usually some offset into the start of the original partition. The size and number of the “children” depends on what is detected. For example if SquashFS image is found then the partition is added. For SquashFS image the splitter also automatically adds to the list of the available mtd partitions, setting this partition’s beginning to the first appropriate address after the SquashFS end and size to the remainder of the partition.

The resulting list of split off partitions is stored in RAM only, so no partition table of any kind gets actually modified. This also includes detection and creation of partition and others, as well as for vendor-specific layouts.

Методика

1. Делайте все под обычным пользователем (не под суперпользователем, non-root)
2. Выполняйте все команды в каталоге , например
  1. Скачайте исходные коды OpenWrt, либо, если они уже скачаны, обновите исходные коды OpenWrt.
  2. Обновите и установите пакеты из репозитория.
  3. Настройте параметры сборки.
  4. Запустите сборку. Будет произведена автоматическая компиляция набора инструментов (toolchain), кросс-компиляция исходных кодов и пакетов, и в конце будет сгенерирован образ готовый к прошивке.
  5. Приступите к установке OpenWrt

Скачивание исходных кодов

Скачайте исходные коды:
Свежая версия (trunk)

git clone https://github.com/openwrt/openwrt.git

(Последний) релиз Chaos Calmer 15.05.1

git clone https://github.com/openwrt/openwrt.git -b v15.05.1

Последняя версия в ветке Chaos Calmer

git clone https://github.com/openwrt/openwrt.git -b chaos_calmer

Обновление исходных кодов

Обновите исходные коды :

git pull

Исходные коды OpenWrt часто изменяются. Рекомендуется использовать исходные коды последней редакции.

Обновление репозитория

Обновите репозиторий:

./scripts/feeds update -a

“Установите” загруженные пакеты (не обязательно, но требуется, если вы хотите , к примеру, собрать прошивку с LuCI).

Эта процедура создаст символьные ссылки на подкаталоги пакетов в основном “дереве” исходных текстов.

Для установки индивидуальных пакетов:

./scripts/feeds install 

Чтобы собрать всё дерево пакетов:

./scripts/feeds install -a

ПРЕДУПРЕЖДЕНИЕ Это может занять много времени и не требуется, если вы не планируете развертывание репозитория пакетов для своей сборки.

Аппаратная часть

Сведения

Набор команд: Архитектура MIPS MIPS 74Kc
Поставщик: Qualcomm Atheros
bootloader: U-Boot
Чип (SOC): AR9344 (MIPS)
Процессор/Частота 560 МГц
Память:
Размер памяти: 8192 КБ
Оперативная память: 128 Мб
Основной радиомодуль: встроенный в SoC: Atheros AR9340 2×2 MIMO для 2.4ГГц 802.11b/g/n
Дополнительный радиомодуль: самостоятельный чип: Atheros AR9580 3×3 MIMO для 5ГГц 802.11a/n
Коммутатор: Atheros AR8327N
USB: Два порта версии 2.0 (чип GL850G — поддержка до четырёх портов)
Serial:
JTAG:

PSU (блок питания)

TL-WDR4300 DE (v1.1) комплектуется следующими блоками питания:

Характеристики:

Производитель/Модель Leader Electronics Inc / LEI F7
Вход 100-240В~ (50/60Гц, 0.6А)
Выход 12.0В 1.5А
Измереный выход 12.15В
Характеристики разъёма на роутере:
Внешний диаметр 5.5мм
Внутренний диаметр 2.1мм
Глубина разъёма 9.5мм

Hardware Highlights

DO NOT BUY DEVICES WITH 4MB FLASH / 32MB RAM if you intend to flash an up-to-date and secure OpenWrt version (18.06 or later) onto it! See 4/32 warning for details.

1) 4/32 devices do not have sufficient resources (flash and/or RAM) to provide secure and reliable operation. See OpenWrt on 4/32 devices what you can do now.

2) OpenWrt support for 4/32 devices will end after 2019. After 19.07, no further OpenWrt images will be built for 4/32 devices. See OpenWrt on 4/32 devices what you can do now.

↓ Model Version SoC CPU MHz Flash MB RAM MB WLAN Hardware WLAN 2.4 100M ports USB
TL-MR3220 v1 Atheros AR7241 400 4 32 Atheros AR9285 b/g/n 5 1x 2.0
TL-MR3220 v2 Atheros AR9331 400 4 32 Atheros AR9331 b/g/n 5 1x 2.0
TL-MR3420 v1, v1.1, v1.2, v1.3 Atheros AR7241 400 4 32 Atheros AR9287 b/g/n 5 1x 2.0
TL-MR3420 v2, v2.1, v2.2, v2.3, v2.4 Atheros AR9341 535 4 32 Atheros AR9341 b/g/n 5 1x 2.0

Types of flash memory

Non-mechanical wear

Moving parts are prone to wear (german: Verschleiß) and experience all sorts of “mechanical breakage/mechanical failure”. But how can a non-moving part possibly break? Possibly by electromigration, by whisker growth, etc.

Non-mechanical wear does not only occur when flash memory is erased!

1. Flash memory is more likely to experience failure than a Hard_disk_drive (the ones with the platters rotating at 5400–15000 RPM)
2. Some types of flash memory seem to experience more non-mechanical wear then other types
3. How do we deal with failure?

Host-managed vs. self-managed

Based on how the flash memory chip is connected with the SoC (i.e. the “host”) we at OpenWrt distinguish between “raw flash” or “host-managed” and “FTL (Flash Translation Layer) flash” or “self-managed”: in case the flash memory chip is connected directly with the SoC we call it “raw flash” / “host-managed” and in case there is an additional controller chip between the flash memory chip and the SoC, we call it “FTL flash” / “self-managed”. Primarily the controller chip does wear-leveling and manages known bad blocks, but it may do other stuff as well. The flash memory cannot be accessed directly, but only through this controller. The controller has to be considered a black box.

Embedded systems almost exclusively use “raw flash”, while solid-state drives (SSDs) and USB memory sticks, almost exclusively use “FTL flash”!

NOR flash vs NAND flash

Additionally we at OpenWrt distinguish between the two basic types of flash memory: and .

“Raw NOR flash” in typical routers is generally small (4 MiB – 16 MiB) and error-free, i.e. there cannot be bad erase blocks. Because raw NOR flash is error-free, the installed file system(s) do not need to take bad erase blocks into account, and neither SquashFS nor JFFS2 do! The combination of OverlayFS with SquashFS and JFFS2 has been the default OpenWrt setup since the beginning, and it works flawlessly on “raw NOR flash”.

“Raw NAND flash” in typical routers is generally larger (32 MiB – 256 MiB) and not error-free, i.e. it may contain bad erase blocks. A solution to deal with bad erase blocks comprises three provisions:

  1. the manufacturer of the “raw NAND flash” has to guarantee that certain erase blocks are error-free:

    • namely the one(s) which the bootloader is to be written to
    • but also the ones which the Linux kernel and the SquashFS are to be written to, because the firmware image file is generated on some desktop computer, that cannot know which erase blocks of the “raw NAND flash” of the device are bad.
  2. the Image Generator has be constrained to build only file sizes that are equal or smaller than the size of the area of the “raw NAND flash”, that consists of guaranteed error-free erase blocks.
  3. OpenWrt would replace JFFS2 with , and the entire area of the “raw NAND flash”, that consists of potentially bad erase blocks, would be written to exclusively from an installed OpenWrt system through UBIFS.
Older routers generally have “raw NOR flash” but many newer routers have “raw NAND flash”.

MLC vs. SLC flash

The main difference between SLC and MLC is durability.
single-level cell (SLC) flash memory may have a lifetime of about 50,000 to 100,000 program/erase cycles, while multi-level cell (MLC) flash may have a lifetime of about 1,000 to 10,000 program/erase cycles.

To be noted that it is NOT RIGHT to estimate the life of a NAND flash in embedded devices using the same method for SSD!

Подготовка

Необходимые пакеты

Первым делом поставьте необходимые пакеты.

Драйверы для USB из списка (если Вы качали образ под конкретный маршрутизатор, то скорее всего нужные пакеты уже установлены):

  • kmod-usb2 (aka EHCI);

  • kmod-usb3 (aka XHCI);

  • kmod-usb-ohci — основной вариант драйвера USB 1.1;

  • kmod-usb-uhci — устаревший вариант драйвера USB 1.1.

В Backfire:

Поддержка USB-serial для управления вашим модемом.

kmod-usb-serial, и

kmod-usb-serial-option, и

kmod-usb-serial-wwan, или

kmod-usb-acm , Зависит от вашего оборудования.

kmod-usb-serial-option недоступен на ядре версии 2.4, Установите kmod-usb-serial и добавьте “usbserial vendor=0x12d1 product=0x1003 maxSize=2048” в /etc/modules.d/60-usb-serial заменив значения vendor и product на свои.

modeswitching tools, если в ваш модем еще и кардридер:

usb-modeswitch и usb-modeswitch-data (рекомендуется) Утилиты смены режима модема

Внимание! Если вы планируете использовать модуль памяти в кардридере модема для extrootа — утилита .

sdparm — Утилита для посылки SCSI команнд (только на Ovation MC935D)

luci-proto-3g Для нормального отображения в luci в RC6 и старше

В Barrier Breaker (14.07):

  • luci-proto-3g — вставляет в веб-интерфейс выбор “UMTS/GSM/CDMA-EVDO” при создании интерфейса;
  • kmod-usb-serial-option — добавляет поддержку переключаемых USB-устройств (модемов);
  • usb-modeswitch — программа для переключения режима модема;
  • kmod-usb-serial-ipw — поддержка модемов GSM, 3G и 4G;
  • остальные пакеты устанавливаются по зависимостям.

Зависимости

Если вы делаете off-line установку , Вам могут понадобиться следующие пакеты

  • kmod-usb-core, есть во всех релизах от 10.03 RC3

  • chat, зависимость comgt

  • ppp, зависимость chat, есть во всех релизах от 10.03 RC3

  • kmod-usb-serial, зависимость kmod-usb-serial-option

Extras

Details

LuCI is installed as a ‘meta package’ which installs several other packages by having these defined as a dependency.
Notably, it installs the uHTTPd web server, configured for use with LuCI.

In case you want to use uHTTPd, there is little configuration necessary as uHTTPd is configured with CGI to make LuCI work with the Lua interpreter.
By default this is organised as follows.
By default is the standard document root.
Thus, by requesting this docroot (by pointing your browser to the devices IP address) an index file such as is searched for (per uHTTPd settings).
The file (installed with LuCI) is prepared such that when requested, it redirects you to , which is the default CGI gateway for LuCI.
This is just a script, which basically calls Lua at .
uhttpd is configured by default to load pages as CGI in the path, and thus starts serving these pages with the script.

It is also possible to run LuCI with Lua as an embedded process.
uhttpd supports this; see the corresponding section of the article on the UCI configuration of uhttpd.

LuCI on other web servers

LuCI on nginx

LuCI on nginx is currently supported by using uwsgi as plain-cgi interpreter.
You need to install one of this 2 variants of the LuCI meta-package:

  • luci-nginx — Autoinstall nginx, uwsgi-cgi and the default config file to make luci work on nginx.
  • luci-ssl-nginx — Autoinstall nginx-ssl, uwsgi-cgi and the default config file to make luci wok on nginx.

It does also create a self-signed certificate for nginx and redirect http traffic to https by default.

Currently LuCI on nginx is fully supported (maybe only in master snapshots for now, as of 16-Feb-2019).
If any problem is found, report them to the support forum.

Support forum for LuCI on Nginx

Offline installation

  • luci
  • luci-app-firewall
  • luci-i18n-english
  • luci-lib-core
  • luci-lib-ipkg
  • luci-lib-nixio
  • luci-lib-sys
  • luci-lib-web
  • luci-mod-admin-core
  • luci-mod-admin-full
  • luci-proto-core
  • luci-proto-ppp
  • luci-sgi-cgi
  • luci-theme-base
  • luci-theme-openwrt
# Upload the packages to the router
scp *.ipk root@openwrt.lan:tmp
 
# Log into the router
ssh root@openwrt.lan
 
# Installed the packages
opkg install tmp/*.ipk
 
# Clean up
rm -f tmp/*.ipk

Minimalistic offline installation

You can also install a minimal version of LuCI with following packages selected for installation.
Download and transfer the packages to your OpenWrt router onto the RAM disk in .

mkdir -p tmpluci-offline-packages; cd tmpluci-offline-packages
  • liblua
  • lua
  • libuci-lua
  • libubus
  • libubus-lua
  • uhttpd
  • rpcd
  • luci-base
  • luci-lib-ip
  • luci-lib-nixio
  • luci-theme-bootstrap
  • luci-mod-admin-full
  • luci-lib-jsonc

and install them with:

opkg install tmpluci-offline-packages/*.ipk

Or use this script bellow.
Note, the script assumes you have internet access through the router where you are installing LuCI.
If you do not, then you will need to either manually download required packages, or run the script in two parts.
First part till the last statement to be executed when connected to the internet:

#!/bin/sh
#assumes the user has egrep, wget, ssh, and scp
 
set -e
 
# Change this to match your router
architecture="arm_cortex-a7_neon-vfpv4"
target="ipq40xx"
 
# These should be fine unless you've changed something
user="root"
ip_address="openwrt.lan"
 
tmpdir="/tmp/luci-offline"
 
base="liblua lua libuci-lua libubus libubus-lua uhttpd rpcd"
baseurl="https://downloads.openwrt.org/snapshots/packages/${architecture}/base"
 
luci="luci-base liblucihttp liblucihttp-lua luci-lib-ip luci-lib-nixio luci-theme-bootstrap luci-mod-admin-full luci-lib-jsonc luci-mod-status luci-mod-system luci-mod-network"
luciurl="https://downloads.openwrt.org/snapshots/packages/${architecture}/luci"
 
targets="libiwinfo libiwinfo-lua"
targetsurl="https://downloads.openwrt.org/snapshots/targets/${target}/generic/packages"
mkdir -p "${tmpdir}"
 
for pkgdir in base luci targets; do
    url=$(eval echo '${'${pkgdir}'url}')
    echo "${url}/Packages"
    wget -N -P "${tmpdir}" "${url}/Packages"
    for pkg in $(eval echo '${'${pkgdir}'}'); do
        pkgfile="$(egrep -o -e " ${pkg}*_.+\.ipk" "${tmpdir}/Packages" | tail -c +2)"
        pkgurl="${url}/${pkgfile}"
        echo "${pkg} ${pkgurl}"
        wget -N -P "${tmpdir}" --quiet "${pkgurl}"
    done
done
 
ssh "${user}@${ip_address}" mkdir -p "${tmpdir}"
scp "${tmpdir}"/*.ipk "${user}@${ip_address}:${tmpdir}"
ssh "${user}@${ip_address}" opkg install "${tmpdir}"/*.ipk
ssh "${user}@${ip_address}" rm -r -f "${tmpdir}"
 
rm -r -f "${tmpdir}"
  • Secure access to LuCI via SSH-tunnel

  • LuCI Technical Reference

Сборка образа

Теперь все готово для сборки образа(ов), которая осуществляется с помощью одной команды:

make

или (то же самое)

make world

Эта простая команда вызовет последовательность событий. Как уже говорилось, произойдет:

  1. компиляция набора инструментов (toolchain)
  2. потом кросс-компиляция исходных кодов с этим инструментарием
  3. создание opkg-пакетов
  4. создание образа прошивки, готового к прошивке.

Последовательность работы make

Команда сама выполняет следующую последовательность команд:

Вы можете выполнить каждую из них отдельно. Например, если процесс компиляции какого-либо пакета прервался с ошибкой, после устранения ошибки можно продолжить сборку (без удаления уже сделанного):

Отладка

Параметр указывает уровень выдачи сообщений в процессе сборки.

Значением можно указать:

  • или — выводить путь к каталогу при входе в него и после выхода из него;
  • или — выводить полную информацию о сборке, обычные сообщения жёлтым, ошибки красным, отладочные чёрным.

Примеры:

make V=w

Трассировка каталогов (путей).

make V=s
make V=99

Трассировка с полной информацией о сборке.

make V=sw

Тоже полная трассировка. (Если указать два значения, работает более полный вывод.)

Сборка на многоядерном процессоре

Процесс сборки можно ускорить запустив несколько параллельных задания с использованием параметра :

make -j 3
  • Используйте стандартную формулу

  • Если это приводит к случайным ошибкам сборки запустите компиляцию еще раз, но без параметра

Фоновая сборка

Если вы собираетесь использовать вашу систему во время процесса сборки, вы можете выполнять сборку используя только простой ввода/вывода и мощности процессора, например так (двухъядерный процессор):

ionice -c 3 nice -n 20 make -j 2

Сборка одиночных пакетов

При разработке или создании пакетов для OpenWrt удобно иметь возможность сборки только нужного пакета (пример с пакетом ):

make package/cups/compile V=99

Обнаружение ошибок сборки

Если по какой-то причине сборка не удается, то самый простой способ определить ошибки это:

make V=99 2>&1 | tee build.log | grep -i error

Команда сохраняет полную подробную копию вывода сборки (с stdout переданный в stderr) в и показывает на экране только ошибки.

Другой пример:

ionice -c 3 nice -n 20 make -j 2 V=99 CONFIG_DEBUG_SECTION_MISMATCH=y 2>&1 | tee build.log | egrep -i '(warn|error)'

еще один:

somthing something screen

Команда сохраняет полную подробную копию вывода сборки (с stdout переданный в stderr) в build.log и показывает только предупреждения и ошибки в процессе сборки используя только фоновые ресурсы двухъядерного процессора.

Включение звуковых уведомлений

В зависимости от вашего процессора этот процесс займет некоторое время или дольше. Если вы хотите включить звуковые уведомления можете использовать ‘:

make V=99 ; echo -e '\a'

Basic configuration

Since this part is identical for all devices, see Basic configuration.

Note: (TP-Link MR3420 v1.2) In case the vlan switch configuration is not created automagically (⇐ 10.03.1) and there is eth0 and eth1 after bootup change /etc/config/network to reflect the vlan setup by adding the lines below. Also replace the ‘option ifname “ethX”’ accordingly (eth0.1, eth0.2). The proper ethernet port layout has still to be confimed.

config switch eth0                   
      	option reset 1                     
      	option enable_vlan 1             
                                     
config switch_vlan
        option device eth0          
        option vlan 1               
        option ports "0t 1 2 3 4" 
                                                                      
config switch_vlan         
        option device eth0       
      	option vlan 2            
      	option ports "0t 5"

In MR3220 v1.2 is:

config 'switch'
	option 'name' 'eth0'
	option 'reset' '1'
	option 'enable_vlan' '1'
      
config 'switch_vlan'
	option 'device' 'eth0'
	option 'vlan' '1'
	option 'ports' '0 1 2 3 4'

Failsafe

Failsafe is a quite popular feature, of this router, thats lets you recover instantly from a misconfiguration above.

Use the QSS button instead of reset button, everything else is identical to generic failsafe document.

Note for MR-3220 running on 12.09-rc1 (r34185): I did not get any UDP packets to port 4919 as promised either when connected to LAN or WAN, however repeatedly pushing the front button made the router to enter the failsafe mode, which allowed me to gain again access to the router. The problem almost bricking my router was in my network configuration, for some reason setting a fixed MAC address for a bridge caused the router to hang at /etc/init./network start.

Details

generic

The flash chip can be represented as a large block of continuous space:

start of flash …………….. end of flash

There is no ROM to boot from; at power up the CPU begins executing the code at the very start of the flash. Luckily this isn’t the firmware or we’d be in real danger every time we reflashed. Boot is actually handled by a section of code we tend to refer to as the bootloader (the BIOS of your PC is a bootloader).

Boot Loader Partition Firmware Partition
Atheros U-Boot firmware
Broadcom CFE firmware
Atheros RedBoot firmware

The partition or partitions containing so called Special Configuration Data differ very much from each other. Example: The -partition you will meet in conjunction with Atheros-Wireless and U-Boot, contains only data regarding the wireless driver, while the -partition of broadcom devices is used for much more then only that.

broadcom with CFE

If you dig into the “firmware” section you’ll find a trx. A trx is just an encapsulation, which looks something like this:

trx-header
HDR0 length crc32 flags pointers data

“HDR0” is a magic value to indicate a trx header, rest is 4 byte unsigned values followed by the actual contents. In short, it’s a block of data with a length and a checksum. So, our flash usage actually looks something like this:

CFE trx containing firmware NVRAM

Except that the firmware is generally pretty small and doesn’t use the entire space between CFE and NVRAM:

CFE trx firmware unused NVRAM

(: The .bin files are nothing more than the generic *.trx file with an additional header appended to the start to identify the model. The model information gets verified by the vendor’s upgrade utilities and only the remaining data – the trx – gets written to the flash. When upgrading from within OpenWrt remember to use the *.trx file.)

So what exactly is the firmware?

The boot loader really has no concept of filesystems, it pretty much assumes that the start of the trx data section is executable code. So, at the very start of our firmware is the kernel. But just putting a kernel directly onto flash is quite boring and consumes a lot of space, so we compress the kernel with a heavy compression known as LZMA. Now the start of firmware is code for an LZMA decompress:

lzma decompress lzma compreszsed kernel

Now, the boot loader boots into an LZMA program which decompresses the kernel into memory and executes it. It adds one second to the bootup time, but it saves a large chunk of flash space. (And if that wasn’t amusing enough, it turns out the boot loader does know gzip compression, so we gzip compressed the LZMA decompression program)

Immediately following the kernel is the filesystem. We use SquashFS for this because it’s a highly compressed readonly filesystem – remember that altering the contents of the trx in any way would invalidate the crc, so we put our writable data in a JFFS2 partition, which is outside the trx. This means that our firmware looks like this:

trx gzip’d lzma decompress lzma’d kernel (SquashFS filesystem)

And the entire flash usage looks like this —

CFE trx gz’d lzma lzma’d kernel SquashFS JFFS2 filesystem NVRAM

That’s about as tight as we can possibly pack things into flash.

logd

is configured in . After changing the file, run

/etc/init.d/log restart
/etc/init.d/system restart

to read in the new configuration and restart the service.

There are three basic destinations for log messages: the RAM ring-buffer (the default), a local persistent file, a remote destination listening for messages on a TCP or UDP port.

The full set of options for are defined in
System Configuration

logread

This is the default interface and the simplest. It is a local executable that will read the ring-buffer records and display them chronologically.

Local File Logging

In order to log to a local file on the router, one needs to set the following options:

config system 
...
   option log_file '/var/log/mylog'
   option log_remote '0'

Network Logging

In order to log remotely one needs to set the following options in

config system
...
   option log_ip 
   option log_port 
   option log_proto 

For the destination port, if you’ll be manually reading the logs on the remote system as an unprivileged user (such as via the netcat command given below), then specify a high port (e.g. 5555). If you’re sending to a syslog server, use whatever port the syslog server is listening on (typically 514).

Additionally, the firewall3 default is to ACCEPT all LAN traffic. If the router blocks LAN-side access, add the following firewall3 rule to to ACCEPT tcp/udp traffic from the router to the LAN-side.

config rule
      option target 'ACCEPT'
      option dest 'lan'
      option proto 'tcp udp'
      option dest_port '5555'
      option name 'ACCEPT-LOG-DEVICE-LAN'

and then reload the rules using .

For the LAN-side station/client, there are a large number of mechanisms to listen for log messages. One of the simplest is ncat:

  • (TCP)
  • (UDP)

The advantage to using TCP is reliability — it logs every event. The disadvantage is it can cause some performance degradation on the router if the logging level is high. There is a section on iptable event logging which can cause a noticable latency in traffic throughput using TCP socket logging.

Test Runtime Logging Support

If you want to test the logging out, just run a command like

and it should be written to the configured destination. If an event is not logged, check:

* is running; it should have an argument of indicating the size of the ring-buffer,
* is configured correctly in ,
* restart it using and check for warnings/errors

Ссылка на основную публикацию