понедельник, 2 февраля 2015 г.

Смена языка

Reloaded firmware
I recently bricked my new IPcam while trying to patch the firmware to remove the NAS format issue. So, I had to refresh the firmware. I downloaded a new image from Hikvision's website. I obtained their pdf explaining the reload process which had a link to the TFTP tool imbedded in the pdf. It did not work. I looked around the web for a TFTP tool. I found several but none worked. Then, I discovered the Hikvision TFTP tool on this website. It worked first time. Be sure and use their tool. When the camera is first powered on, it looks briefly (2-3 seconds) for a handshake from the TFTP tool. Be sure to have it setup EXACTLY as stated in the pdf instructions. No cross over cable needed, just a regular ethernet will do. Once the firmware reports loaded, wait 2-3 minutes extra before power cycling.

TFTP Firmware tool:
ftp://Hikcustomer:welcome@125.99.126.50

Change the Default Language
The camera web interface with new firmware is now Chinese. It was English before. I worked a few days to perfect this change which can easily be done on the camera to change the default language to any of those available. The change survives a reboot.

First, you need to enable SSH on the camera. Go to the web interface and you'll have to hack your way to find it. Login, click the 4th item on the top which is Configuration. The, third category on the left is Advanced Configuration. 5th item down is Security. 5th tab is Security Service. 2nd item is SSH. Click the box to enable, save.

Startup Script
Wouldn't it be nice to be able to execute your own scripts at camera startup? There just isn't any mechanism for this ... until now. I'll show you have since we need this to change the web language. This can be used to start all kinds of personal processes. Enjoy!

SSH to your camera and login. All this is in english. You are in the top directory. The directory /dav contains the firmware images, boot scripts and this directory survives a reboot. 

On boot, the script /dav/initrun.sh is run. We will leverage this. Create a directory in /dav to place your script.

mkdir /dav/scripts

Let's modify /dav/initrun.sh to execute our script at the conclusion of the boot process. You might want to look at this file before modifying it. BE VERY CAREFUL with this series of commands in case you make an error. There is no editor on the camera and care means you can avoid having to copy to/from a NAS for corrections. 

View the file: cat /dav/initrun.sh
backup the file: cp /dav/initrun.sh /dav/initrun-back.sh
Modify it by appending a line: echo "bash /dav/scripts/startup.sh &" >> /dav/initrun.sh

If you mess up, simple copy from the backup and try again. 

cp /dav/initrun-back.sh /dav/initrun.sh

OK, we now have the camera firing off your non-existent script called startup.sh on boot. We'll create the script shortly.

Let's find the website files. The website files are recreated fresh on boot. Let's look at the language files:
ls /home/doc/xml

You see directories containing the various languages. The file Languages.xml tells the website what to use. Despite the default stated in this file to be English, it defaults to Chinese. So, we won't mess with that file. Instead, we will trick the system. We will change the directory containing Chinese to a different name and replace that directory with a symbolic link to English (or whatever language you want). When the website uses Chinese, it actually uses what we want. If you want a language other than English, make note of the directory name. You will use this in place of "en" as we move forward.

Let's create the startup.sh script. We want to change our directory to the xml area. We move the Chinese language from directory zh to zh1. We create a symbolic link for zh that points to en. That's all the script does but it works. We will use echo to create the script.

echo "cd /home/doc/xml
mv zh zh1
ln -s en zh" > /dav/scripts/startup.sh

Check it's contents: cat /dav/scripts/startup.sh

The script will survive a reboot. The language will change and remain this way until you replace the firmware. You now have a great new feature - a startup script. You can add to this script to run other things, change the firewall, change which ports are used or run your own scripts. Be sure to watch the memory use. See the memory available with the "df" command.

Good luck!

четверг, 25 декабря 2014 г.

Описание файлов

devCfg.bin

Добавление английского языка на примере DS-7108N-SN

Взято с http://diyservice.blogspot.ru/2014/12/hikvision-ds-7108n-sn.html

Сегодня я расскажу, как у китайской версии сетевого видеорегистратора (NVR) модельHikVision DS-7108N-SN переделать язык оболочки на английский.

Этот регистратор я приобрел на аукционе ТаоБао по достаточно демократичной цене. После подключения оказалось, что Web-интерфейс доступен на английском языке, однако оболочка представлена только на китайском и нигде нет возможности выбора языка.

Поиск прошивок в интернете не дал никаких результатов.
Поэтому я решил попробовать сделать все самостоятельно. Все прошло успешно, а процедурой «декитаезации» я с удовольствием поделюсь с вами!

Сразу скажу, что процедура в некотором плане опасна, есть вполне реальная вероятность получить на выходе нерабочее устройство. Поэтому за возможные проблемы, никакой ответственности я не несу, физически помочь восстановить не смогу. Все что вы делаете, вы делаете на свой страх и риск и должны осознавать возможные последствия!

Итак, версия моей прошивки с завода: V3.0.7 build 140725
Версия регистратора: HikVision DS-7108N-SN

Вам потребуется:
  • Машина с любой ОС Linux или Windows
  • Установленный на ней TFTP Сервер (я использовал tftpd-hpa);
и собственно все.

1. Заходим в Web-интерфейс регистратора и в меню «Network-settings – Advanced» включаем доступ по Telnet.


2. Заходим через Telnet на регистратор. Имя пользователя root (не admin), пароль по-умолчанию «12345».



3. В домашней папке /home вы увидите app и hikКак видно на скриншоте ниже, hik примонтирован к mtdblock1а app – tmpfs в ОЗУ.



4. Зайдите в /home/hikНас тут интересуют два файла — это загрузочный скрипт (start.shи архив app.tar.lzmaсжатый lzma, где хранятся текстуры кнопок и конфигурационный файл с языками.


5. На самом регистраторе нет нужных утилит для редактирования, поэтому проще всего перекинуть файлы через TFTP на «большой» компьютер.
tftp -p -l start.sh YOUR-TFTP-SERVER

tftp -p -l app.tar.lzma YOUR-TFTP-SERVER

6. На компьютере открываем скрипт start.sh и добавляем в начало строчку для запуска демона Telnet. Это необходимо для случая, если после наших манипуляций оболочка регистратора не загрузится, то мы все равно будем иметь доступ через Telnet. 

Добавляем
[ -e /usr/sbin/telnetd ] && /usr/sbin/telnetd 32

7. Распакуйте архив app.tar.lzma


8. В папке config вы увидите файл конфигурации 1024x768.cfg
Полистайте файл, обратите внимание, что в нем, помимо китайского, уже присутствует английский язык.


Как видите в строчках, заканчивающихся на _cap0 хранится английская версия, а в строчке _cap1 – китайская.
Не мудрствуя лукаво, чтобы не искать, где же задается текущий язык, я решил просто закопировать английскую строку на китайскую.

Подобных строк там тысячи, поэтому вручную изменять их было бы глупо, а я не сумасшедший, поэтому воспользуемся AWK.
awk '{ if ( /_cap0=/ ) {print $0; gsub("_cap0=", "_cap1="); print $0} else { if (! /_cap1=/ ) print $0 } }' 1024x768.cfg >> test.cfg

Логика проста: производится поиск строк и...
Если строка содержит cap0, то она дублируется с подменой cap0 на cap1
Если строка содержит cap1, то эта строка удаляется из файла
Все остальные строки остаются без изменений.

Для Windows

Gawk for Windows http://gnuwin32.sourceforge.net/packages/gawk.htm

awk "{ if ( /_cap0=/ ) {print $0; gsub(/_cap0=/, \"_cap1=\", $0); print $0} else {if (! /_cap1=/ ) print $0 } }" 1024x768.cfg >> 1024x768x1.cfg

awk "{ if ( /_lang0=/ ) {print $0; gsub(/_lang0=/, \"_lang0=\", $0); print $0} else {if (! /_lang0=/ ) print $0 } }" 1024x768x1.cfg >> 1024x768x2.cfg

Собственно все. Теперь надо запаковать все в архив и закинуть обратно на регистратор.

Обратите внимание, что для сжатия используется первая версия LZMA 1.

Да, еще хочу заметить, как безобразно заданы права и владельцы у файлов регистратора. Практически у всех файлов доступ 777! Я пока не стал экспериментировать что, да как, поэтому просто задал такие же права у файлов.

В корне распакованного app.tar.lzma выполняем
find . | sudo xargs chmod 777
find . | sudo xargs chown nobody:nogroup

Создаем архив tar:
tar -cpvf ~/app.tar `ls`
Тоже меняем права и владельца:
chmod 777 ~/app.tar
chown nobody:nogroup ~/app.tar
Сжимаем архив lzma
lzma -6 < ~/app.tar > ~/app.tar.lzma
 или так
lzma --lzma1 -z -c ~/app.tar >> ~/app.tar.lzma
8. Снова заходим через Telnet на регистратор и закидываем файлы обратно

Места на разделе mtdblock1 мало, поэтому будем писать в память:
cd /home/app/
mkdir test
cd test

tftp -g -r app.tar.lzma YOUR_TFTP_SERVER

Далее, проверим на всякий случай, что архив будет распаковываться:
/bin/tar xaf /home/app/test/app.tar.lzma -C /home/app/test
Если все успешно, подменяем файл:
rm /home/hik/app.tar.lzma
mv /home/app/test/app.tar.lzma /home/hik
chmod 777 /home/hik/app.tar.lzma
 Думаю, что менять права на 777 не требуется, но так было с завода, поэтому делаем так же.


Не забываем заменить скрипт start.sh. Думаю, вы это сделаете самостоятельно.


Все, перезагружаем регистратор. Радуемся английскому языку!


Спасибо за внимание!