diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..227936cf --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +# Built application files +*.apk +*.ap_ + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# Intellij +*.iml +.idea/ + +# Keystore files +*.jks + +# Mac OS X clutter +*.DS_Store + +# Windows clutter +Thumbs.db diff --git a/CHANGELOG b/CHANGELOG new file mode 100644 index 00000000..36da38d8 --- /dev/null +++ b/CHANGELOG @@ -0,0 +1,701 @@ +Changelog (English) +=================== + +2.0.0 +The application interface is rewritten with Material Design +Completed transition to the new CLI +Added support for work without root permissions (based on PRoot) +Added an option to keep CPU running to do work while the screen is off +Added an option to change the delay of start after opening XServer XSDL +Added interface for managing from TELNET (based on telnetd) +Added web interface (based on httpd, websocket.sh and xterm.js) +Added synchronization of the operating environment with server or other device +Added function to generate a random password for user (instead changeme) +Added function to track changes in the network and update the current container +Added ability to add users to groups aid_ * from the application interface +Added support for initialization systems run-parts and sysv +Extended syntax description of mount points, you can now specify to mount /from/dir:/to/dir +Restore Android after closing Xorg session in framebuffer mode +Make an unified container profiles for CLI and the application interface +Created a repository of containers + +1.5.6 +Fixed apt resolve in stretch and xenial +Added support kali-rolling in Kali Linux +Added target type "Auto" for manual prepare target path +Added timestamp support to log filename (${TIMESTAMP} variable) +End of support Debian Squeeze and Kali Moto +Added support /dev/net/tun (for OpenVPN) +Automatically switch to root (unchroot) +Mount root with options "exec,suid,dev" +Fixed Arch Linux packages (close #529) + +1.5.5 +Open a shell from Android Terminal Emulator +Added support CentOS +Translated into Korean + +1.5.4 +Fixed a problem with user password that contains uppercase letters +Added support system BusyBox, a built-in is no longer supported +Added option to display a time stamp +Improved support for framebuffer +Translated into Portuguese + +1.5.3 +Added an option to change the chroot directory +Added unchroot script +Implemented integration with Android +Implemented integration with XServer XSDL +Translated into Slovak and French +Automatically select the language + +1.5.2 +Added support Slackware +Added support Kali Linux 2.0 (sana) +Added support tar.xz for RootFS installation +Added support x86_64 (amd64) distributions +Added export a container as rootfs archive (tgz or tbz2) +Modified update ENV mechanism +Updated command line interface +Added ability to change password from GUI +Translated into Vietnamese +Updated root checker +Added support aarch64 for Arch Linux +Fixed autostart problem + +1.5.1 +Added support for installation type in RAM +Updated command "status" +Updated security groups +Added fix for tty0 (use X options: "-sharevts vt0") +Added handling for shutdown event +Added support Ubuntu 15.10 (Wily Werewolf) +Added support Fedora 22 (armhfp only) +Added more locales +Translated into German, Italian, Spanish and Chinese + +1.5.0 +Added support for devices with an Intel architecture +Added support for cross-architecture installation x86 <-> ARM based on QEMU (binfmt_misc require support in the kernel) +Updated built-in BusyBox to version 1.23.0 (builds with PIE and without PIE) +Added support Ubuntu 15.04 (Vivid Vervet) +Added suits kali-dev and kali-rolling in Kali Linux +Bugfix "Couldn't find these debs: 0" +Fixed Gentoo installation problems +Updated linuxdeploy shell + +1.4.9 +Added support for third-party BusyBox (required /system/xbin/ash) +Added support Ubuntu 14.10 (Utopic Unicorn) +Added support arm64/aarch64 for some distributions + +1.4.8 +Added support Android 5 (PIE support) +Added support Fedora 21 (armhfp only) +Fixed LD_PRELOAD errors + +1.4.7 +Fixed packages list of Arch Linux (issue #161) +Fixed error with VNC_ARGS (issue #153) +User root is added to the group aid_inet be default (ticket #135) +Takes into account changes in openSUSE repository (ticket #154) +Save and restore SELinux state (ticket #167) + +1.4.6 +Added option to disable the built-in shell +Operating environment by default: /data/data/ru.meefik.linuxdeploy/linux +Added sync in framebuffer +Added ACCESS_SUPERUSER permission +Fixed packages list of Arch Linux (issue #136) +Fixed packages list of openSUSE + +1.4.5 +Added support SELinux +BusyBox dynamically linked (fixed DNS resolver) +Added support Ubuntu 14.04 (Trusty Tahr) +Fixed X Window System startup +Fixed dbus configuration + +1.4.4 +Added support Fedora 20 (armhfp) +Added VNC options +Bugs fixed +Fixed broken packages in Arch Linux + +1.4.3 +Added support Ubuntu 13.10 (Saucy Salamander) +Added three modes Android UI freeze +Added autostart dbus in X-server mode and framebuffer +Added an property "X options" for framebuffer +Fixed list of packages openSUSE installation +Change tightvnc to tigervnc in Arch Linux + +1.4.2 +Added support Debian 8.0 (jessie) +Interface improvements +Added ability to choose components to install + +1.4.1 +Added support for installation from rootfs archives (tgz, tbz2) +Added custom installation type (install without make new image file and filesystem) +Bugfix: changing font size +Improved mechanism of disk image file creation (fast re-creation) +Improved framebuffer support + +1.4.0 +Added function of import/export profiles +Support Android 2.1 (API 7) +Updated list of packages openSUSE (armv7hl) +Added support Fedora 19 +Automatic detection of screen resolution (for VNC) +Improved command line utility linuxdeploy + +1.3.9 +Added support Gentoo (installation requires at least 4 GB of free space) +Limitation of scroll buffer size +Automatic mount /dev/shm +Updated debootstrap up to 1.0.48 +Support for multiple input devices in framebuffer mode (in xorg.conf changed lines are marked as #linuxdeploy) +Hide icon in notification bar after you exit the application +Solved problem with running SSH in Arch Linux +Takes into account changes in Arch Linux packages +Bugfix: conflict with SSH applications in Android + +1.3.8 +Added support Ubuntu 13.04 Raring Ringtail +Added option for stop Android UI in framebuffer mode +Added Wi-Fi lock +Added support armv5tel architecture for openSUSE (VNC now works) +Bugfix: autostart problem + +1.3.7 +Added support Kali Linux +Added ability to display GUI through framebuffer +Fixed list of packages openSUSE installation +Bugfix: pacman error "invalid option" + +1.3.6 +Added support Fedora 18 +Takes into account changes in openSUSE repository +Takes into account changes in Arch Linux packages +Added application icon in notification bar +Bugfix: dbus error in Arch Linux and Fedora +Bugfix: /dev/pts wrong mount mode + +1.3.5 +Redesigned interface (include ActionBarSherlock) +Improved autostart feature +Automatic update operating environment +Added check superuser permissions (root) +Double tap for select profile +Bugfix: incorrect use of default parameter + +1.3.4 +Added command status to linuxdeploy script +Added function startup GNU/Linux when running Android (Settings -> Autostart) +Excluded lost package insserv form openSUSE installation +Added DPI property for VNC +Improved algorithm displaying reports + +1.3.3 +Added xorg-fonts-misc package in Arch Linux GUI installation +Bugfix: dbus error in Debian/Ubuntu +Bugfix: update configuration file after change profile + +1.3.2 +Added support openSUSE installation +Improved Arch Linux mirrors settings +Updated BusyBox +Configuration file is updated only when the parameters are updated +Script linuxdeploy can now be run from Android console +Now can create a symbolic link to linuxdeploy in /system/bin (Settings -> Create symlink) +Notification of need to update the operating environment +Bugfix: wrong information size of image file in automatic calculation mode +Bugfix: crashes when VNC display not integer number + +1.3.1 +Added support Fedora installation +Improved Arch Linux locale support + +1.3.0 +Added support Arch Linux installation +Added automatic calculation of image size (90% of free space, but not more than 4095 MB) +Added subitem desktop environment "Other" (for manual settings) +Interface improvements + +1.2.9 +Bugfix: sudo, upstart, gnome-session, XKL_XMODMAP_DISABLE +Added support ext3 file system +Improved preferences organization +Improved automatic detection of file system +Optimize of making disk image file + +1.2.8 +Bugfix: problem installing BusyBox on some devices (error updating the operating environment) +Added support installation in directory +Added checking mount points before installation +Rebuilding image file at change the size +Improved custom mounting + +1.2.7 +Bugfix: incorrect startup GNOME session on Ubuntu +Added support X Window System (startup GUI over X server) +Added automatic DNS configuration +Added support Unity desktop environment + +1.2.6 +Bugfix: incorrect profile management +Added support Ubuntu installation +Added information of active Linux system in SysInfo +Improved wake lock + +1.2.5 +Added support for profiles +Added select file system +Added separate localization settings +Change TWM to XTerm + +1.2.4 +Added information of available mount points and partitions in SysInfo +Added ability to select and copy text in the main window (Android 3+) + +1.2.3 +Added themes support (dark and light) + +1.2.2 +Improved resources release function +Improved auto-scrolling + +1.2.1 +Bugfix: error set user password on third-party images +Default user name changed to android + +1.2.0 +Improved function of the system configuration for third-party images + +1.1.9 +Added ability to select a desktop environment (TWM, LXDE, XFCE, GNOME, KDE) +Added support for startup as root +Added check for reserved usernames +Added ability to change DNS server + +1.1.8 +Support mounting custom partitions from /dev (e.g. /dev/block/sda1) +Interface improvements + +1.1.7 +Support for architectures ARMv5TE and above +Added feature mounting custom partitions +Added feature to run multiple custom scripts + +1.1.6 +Bugfix: error starting custom script +Added tracing mode +Added feature save logs to file + +1.1.5 +Bugfix: conflict with existing BusyBox +Updated BusyBox up to v1.21.0 + +1.1.4 +Improved WiFi control +Interface improvements + +1.1.3 +Bugfix: error updating the operating environment on some devices + +1.1.2 +Added support for ext4 file system + +1.1.1 +Bugfix: error making new user during the installation of Debian Squeeze (it also error starting VNC server) + +1.1.0 +Added ability to install OS on SD card (without loop device) +Added debug mode + +1.0.9 +Language of OS matched the language of interface + +1.0.8 +Bugfix: error make a disk image larger than 1 GB + +1.0.7 +Added script /bin/linuxchroot +Added information of mounted parts in SysInfo + +1.0.6 +Added information of storages in SysInfo + +1.0.5 +ARMEL/ARMHF support for SFTP (sftp-server) + +1.0.4 +Bugfix: incomplete removal +Interface improvements + +1.0.3 +Bugfix: problem with permissions via SFTP from Linux +Added function to reconfigure the system +Improved backlight control + +1.0.2 +Bugfix: SysInfo check SSH is running + +1.0.1 +Bugfix: error of disk image creation +Added information about ports on the title bar +Updated list packages of base system installation + + +История изменений (Русский) +=========================== + +2.0.0 +Интерфейс приложения переписан под Material Design +Выполнен переход на новый CLI +Добавлена поддержка работы без прав суперпользователя (на базе PRoot) +Добавлена опция предотвращения торможения процессора при отключении экрана +Добавлена опция изменения задержки перед запуском контейнера после открытия приложения XServer XSDL +Добавлен интерфейс управление по TELNET (на базе telnetd) +Добавлен веб-интерфейс (на базе httpd, websocket.sh и xterm.js) +Добавлена функция синхронизации рабочего окружения с сервером или другим устройством +Добавлена генерация случайного пароля пользователя (вместо changeme) +Добавлена функция отслеживания изменения сети и обновления текущего контейнера +Добавлена возможность добавлять пользователей в группы aid_* из интерфейса приложения +Добавлена поддержка систем инициализации run-parts и sysv +Расширен синтаксис описания точек монтирования, теперь можно указывать откуда и куда монтировать (/from/dir:/to/dir) +Восстановление работы Android после завершение сессии Xorg в режиме кадрового буфера +Сделаны единые профили контейнеров для CLI и интерфейса приложения +Создан репозиторий контейнеров + +1.5.6 +Исправлена проблема c apt в stretch и xenial +Добавлена ветка kali-rolling в Kali Linux +Добавлен тип установки "Автоопределение" для ручной настройки места установки +В логфайл добавлена временная метка (переменная ${TIMESTAMP}) +Закончена поддержка Debian Squeeze и Kali Moto +Добавлена поддержка /dev/net/tun (для OpenVPN) +Автоматическое переключение к root (unchroot) +Монтирование корневого раздела с опциями "exec,suid,dev" +Исправление в пакетах Arch Linux (тикет #529) + +1.5.5 +Открытие командной оболочки в Android Terminal Emulator +Добавлена поддержка CentOS +Переведено на корейский язык + +1.5.4 +Исправлена проблема с установкой пароля, содержащего заглавные буквы +Добавлена поддержка системного BusyBox, встроенный больше не поддерживается +Добавлена опция отображения отметки времени +Улучшена поддержка кадрового буфера +Переведено на португальский язык + +1.5.3 +Добавлена опция изменения chroot директории +Добавлен скрипт unchroot +Реализована интеграция с Android +Реализована интеграция с XServer XSDL +Переведено на словацкий и французский +Автоматический выбор языка интерфейса + +1.5.2 +Добавлена поддержка Slackware +Добавлена поддержка Kali Linux 2.0 (sana) +Добавлена поддержка архивов tar.xz для установки типа RootFS +Добавлена поддержка x86_64 (amd64) дистрибутивов +Добавлена функция экспорта контейнера как rootfs архива (tgz или tbz2) +Изменен механизм обновления рабочего окружения +Обновлен интерфейс командной строки +Добавлена возможность изменять пароль из интерфейса приложения +Переведено на вьетнамский язык +Изменен механизм проверки прав суперпользователя +Добавлена поддержка aarch64 для Arch Linux +Исправлена проблема с автозапуском + +1.5.1 +Добавлена поддержка установки дистрибутивов в оперативную память +Обновлена команда "состояние" +Обновлены группы безопасности +Добавлено исправление для tty0 (используйте опции X-сервера: "-sharevts vt0") +Добавлена обработка события отключения питания устройства +Добавлена поддержка Ubuntu 15.10 (Wily Werewolf) +Добавлена поддержка Fedora 22 (только armhfp) +Добавлено больше локализаций +Переведено на немецкий, итальянский, испанский и китайский языки + +1.5.0 +Добавлена поддержка устройств с Intel архитектурой +Добавлена поддержка кросс-архитектурной инсталляции x86 <-> ARM на основе QEMU (требуется поддержка binfmt_misc на уровне ядра) +Обновлен встроенный BusyBox до версии 1.23.0 (сборки с PIE и без PIE) +Добавлена версия Ubuntu 15.04 (Vivid Vervet) +Добавлены ветки kali-dev и kali-rolling в Kali Linux +Исправлена ошибка "Couldn't find these debs: 0" +Истранены проблемы с установкой Gentoo +Обновлен linuxdeploy shell + +1.4.9 +Добавлена поддержка сторонних сборок BusyBox (требуется /system/xbin/ash) +Добавлена поддержка Ubuntu 14.10 (Utopic Unicorn) +Добавлена поддержка arm64/aarch64 для некоторых дистрибутивов + +1.4.8 +Добавлена поддержка Android 5 (поддержка PIE) +Добавлена поддержка Fedora 21 (только armhfp) +Исправление ошибок LD_PRELOAD + +1.4.7 +Исправлен список пакетов в Arch Linux (тикет #161) +Исправлена ошибка, связанная с VNC_ARGS (тикет #153) +Пользователь root добавлен в группу aid_inet по умолчанию (тикет #135) +Учтены изменения в репозитории openSUSE (тикет #154) +Сохранение и восстановление состояния SELinux (тикет #167) + +1.4.6 +Добавлена опция для отключения встроенного командного интерпретатора +Путь рабочего окружения по умолчанию: /data/data/ru.meefik.linuxdeploy/linux +Добавлена команда sync перед переходом в режим фрем-буфера +Добавлено разрешение ACCESS_SUPERUSER +Исправлен список пакетов в Arch Linux (тикет #136) +Исправлен список пакетов в openSUSE + +1.4.5 +Добавлена поддержка SELinux +BusyBox динамически слинкован (исправлена проблема с DNS резолвером) +Добавлена поддержка Ubuntu 14.04 (Trusty Tahr) +Исправлена ошибка запуска X Window System +Исправлена ошибка при конфигурации dbus + +1.4.4 +Добавлена поддержка Fedora 20 (armhfp) +Добавлен параметр VNC options +Исправление ошибок +Исправлены битые пакеты в Arch Linux + +1.4.3 +Добавлена поддержка Ubuntu 13.10 (Saucy Salamander) +Добавлено три режима заморозки Android UI +Добавлен автозапуск dbus в режиме X-сервера и фрейм-буфера +Добавлен параметр "Опции X-сервера" для фрейм-буфера +Исправлен список пакетов установки openSUSE +В Arch Linux заменен пакет tightvnc на tigervnc + +1.4.2 +Добавлена поддержка Debian 8.0 (jessie) +Доработки интерфейса +Добавлена возможность выбирать компоненты для установки + +1.4.1 +Добавлена поддержка установки дистрибутивов из rootfs архивов (tgz, tbz2) +Добавлен пользовательский тип установки (установка без создания файла образа диска и файловой системы) +Исправлено изменение размера шрифта +Улучшен механизм создания файла образа диска (быстрое пересоздание) +Улучшена поддержка фрейм-буфера + +1.4.0 +Добавлена ​​функция импорта/экспорта профилей +Поддержка Android 2.1 (API 7) +Обновлен список пакетов openSUSE (armv7hl) +Добавлена поддержка Fedora 19 +Автоматическое определение разрешение экрана (для VNC) +Доработана консольная утилита linuxdeploy + +1.3.9 +Добавлена поддержка Gentoo (для установки необходимо не менее 4 GB свободного места) +Ограничение размера буфера прокрутки +Автоматическое монтирование /dev/shm +Обновлен debootstrap до версии 1.0.48 +Поддержка нескольких устройств ввода в режиме фрейм-буфера (в xorg.conf изменяемые строки отмечены как #linuxdeploy) +Скрытие значка на панели уведомлений после выхода из приложения +Решена проблема с запуском SSH в Arch Linux +Учтены изменения в пакетах Arch Linux +Исправлен конфликт с SSH-приложениями в Android + +1.3.8 +Добавлена поддержка Ubuntu 13.04 Raring Ringtail +Добавлена опция отключения графического интерфейса Android в режиме фрейм-буфера +Добавлена функция блокировки Wi-Fi +Добавлена ​​поддержка архитектуры armv5tel для openSUSE (VNC теперь работает) +Исправлена проблема с автозапуском + +1.3.7 +Добавлена поддержка Kali Linux +Добавлена ​​возможность отображения графического интерфейса через фрейм-буфер +Исправлен список пакетов установки openSUSE +Исправлена ошибка: pacman error "invalid option" + +1.3.6 +Добавлена поддержка Fedora 18 +Учтены изменения в репозитории openSUSE +Учтены изменения в пакетах Arch Linux +Добавлен значок на панель уведомлений +Исправлена ошибка dbus в Arch Linux и Fedora +Исправлен режим монтирования /dev/pts + +1.3.5 +Переработан интерфейс (добавлен ActionBarSherlock) +Доработана функция автозапуска +Автоматическое обновление рабочего окружения +Добавлена проверка привилегий суперпользователя (root) +Двойное нажатие для выбора профиля +Исправлена ошибка применения некорректных параметров по умолчанию + +1.3.4 +Добавлена команда status в скрипт linuxdeploy +Добавлена функция запуска GNU/Linux при загрузке Android (Настройки -> Автозапуск) +Из базовой установки openSUSE исключен потерянный пакет insserv +Добавлен параметр DPI для VNC +Доработан алгоритм отображения отчетов + +1.3.3 +Добавлен пакет xorg-fonts-misc к установке GUI в Arch Linux +Исправлена ошибка dbus в Debian/Ubuntu +Исправлена ошибка обновления конфигурационного файла после смены профиля + +1.3.2 +Добавлена ​​поддержка установки openSUSE +Доработана настройка зеркал в Arch Linux +Обновлен BusyBox +Обновление конфигурационного файла теперь происходит только при изменении параметров +Скрипт linuxdeploy теперь можно запускать из консоли Android +Добавлена возможность создания символьной ссылки на linuxdeploy в /system/bin (Настройки -> Создать симлинк) +Уведомление о необходимости обновить рабочее окружение +Исправлена ошибка отображения размера образа в режиме автоматического расчета +Исправлена ошибка падения приложения, когда VNC дисплей не целое число + +1.3.1 +Добавлена ​​поддержка установки Fedora +Доработана поддержка локализации в Arch Linux + +1.3.0 +Добавлена ​​поддержка установки Arch Linux +Добавлена функция автоматического расчета размера образа диска (90% от свободного пространства, но не больше 4095 МБ) +Добавлен подпункт окружения рабочего стола "Другое" (для ручной настройки) +Доработки интерфейса + +1.2.9 +Исправлены ошибки, связанные с sudo, upstart, gnome-session, XKL_XMODMAP_DISABLE +Добавлена поддержка файловой системы ext3 +Улучшена организация настроек и параметров +Доработано автоматическое определение файловой системы +Оптимизирован механизм создания файла образа диска + +1.2.8 +Устранена проблема установки BusyBox на некоторых устройствах (ошибка обновления рабочего окружения) +Добавлена поддержка установки в каталог +Добавлена проверка точек монтирования перед установкой +Пересоздание образа при изменении размера +Доработана функция выборочного монтирования + +1.2.7 +Исправлена ошибка запуска сессии GNOME в Ubuntu +Добавлена поддержка X Window System (запуск GUI через X-сервер) +Добавлена автоматическая конфигурация DNS +Добавлена поддержка окружения рабочего стола Unity + +1.2.6 +Исправлена ошибка некорректного управления профилями +Добавлена ​​поддержка установки Ubuntu +Добавлена информация об активной системе Linux +Доработана функция управления переходом в спящий режим + +1.2.5 +Добавлена поддержка профилей +Добавлена возможность выбора файловой системы +Выбор локализации системы вынесен в отдельных пункт настроек +Заменен TWM на XTerm + +1.2.4 +Добавлена информация о доступных точках монтирования и разделах +Добавлена возможность выделения и копирования текста в главном окне (Android 3+) + +1.2.3 +Добавлена поддержка тем интерфейса (темная и светлая) + +1.2.2 +Доработана функция освобождения ресурсов перед размонтированием разделов +Доработана автоматическая прокрутка + +1.2.1 +Исправлена ошибка установки пароля пользователя на некоторых образах +Имя пользователя по умолчанию изменено на android + +1.2.0 +Доработана функция переконфигурации системы для сторонних образов + +1.1.9 +Добавлена возможность выбора окружения рабочего стола (TWM, LXDE, XFCE, GNOME, KDE) +Добавлена поддержка запуска системы под пользователем root +Добавлена проверка на зарезервированные имена пользователей +Добавлена возможность изменять адрес DNS сервера + +1.1.8 +Поддержка выборочного монтирования разделов из /dev (например, /dev/block/sda1) +Доработки интерфейса + +1.1.7 +Реализована ​​поддержка архитектуры ARMv5TE и выше +Добавлена функция выборочного монтирования разделов +Добавлена ​​возможность запуска нескольких пользовательских сценариев + +1.1.6 +Исправлена ошибка запуска пользовательского сценария +Добавлен режим трассировки +Добавлена ​​функция сохранения журнала в файл + +1.1.5 +Исправлен конфликт с уже установленным в системе BusyBox +Обновлен BusyBox до версии 1.21.0 + +1.1.4 +Доработана функция управления WiFi +Доработки интерфейса + +1.1.3 +Исправлена ошибка обновления рабочего окружения на некоторых устройствах + +1.1.2 +Добавлена поддержка файловой системы ext4 + +1.1.1 +Исправлена ошибка создания нового пользователя при установке версии Debian Squeeze (она же ошибка запуска VNC) + +1.1.0 +Добавлена возможность установки ОС на SD карту (без использования образа диска) +Добавлен режим отладки + +1.0.9 +Язык устанавливаемой системы теперь соответствует языку интерфейса программы + +1.0.8 +Исправлена ошибка создания образа диска больше 1 ГБ + +1.0.7 +Добавлен скрипт /bin/linuxchroot +Обновлена информация о системе, добавлен статус смонтированных разделов + +1.0.6 +Добавлена информация о доступных внешних накопителях + +1.0.5 +Поддержка обоих архитектур ARMEL/ARMHF для SFTP (sftp-server) + +1.0.4 +Исправлена ошибка неполного удаления +Доработки интерфейса + +1.0.3 +Устранена проблема с правами доступа через SFTP из Linux +Добавлена функция переконфигурации системы +Доработано управление подсветкой экрана + +1.0.2 +Исправлена функция проверки статуса SSH сервера + +1.0.1 +Добавлена информация о портах в строке заголовка +Исправлена ошибка при создании образа диска +Обновлен список пакетов базовой установки + diff --git a/COPYRIGHT b/COPYRIGHT new file mode 100644 index 00000000..3472f7c3 --- /dev/null +++ b/COPYRIGHT @@ -0,0 +1,14 @@ +Copyright (C) 2012-2016 Anton Skshidlevksy + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 00000000..baf71417 --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ +Linux Deploy +============ + +Copyright (C) 2012-2016 Anton Skshidlevsky, [GPLv3](http://opensource.org/licenses/gpl-3.0.html) + +This application is open source software for quick and easy installation of the operating system (OS) GNU/Linux on your Android device. + +The application creates a disk image on a flash card, mounts it and installs an OS distribution. Applications of the new system are run in a chroot environment and working together with the Android platform. All changes made on the device are reversible, i.e. the application and components can be removed completely. Installation of a distribution is done by downloading files from official mirrors online over the internet. The application requires superuser rights (ROOT). + +The program supports multi language interface. You can manage the process of installing the OS, and after installation, you can start and stop services of the new system (there is support for running your scripts) through the UI. The installation process is reported as text in the main application window. During the installation, the program will adjust the environment, which includes the base system, SSH server, VNC server and desktop environment. The program interface can also manage SSH and VNC settings. + +Installing a new operating system takes about 30 minutes. The recommended minimum size of a disk image is 1024 MB (with LXDE), and without a GUI - 512 MB. When you install Linux on the flash card with the FAT32 file system, the image size should not exceed 4095 MB! After the initial setup the default password for SSH and VNC is changeme. The password can be changed through standard OS tools. + +#### Features: #### +* Supported distributions: Debian, Ubuntu, Kali Linux, Arch Linux, Fedora, CentOS, Gentoo, openSUSE, Slackware, RootFS (tgz, tbz2, txz) +* Installation type: image file, directory, disk partition, RAM +* Supported file systems: ext2, ext3, ext4 +* Supported architectures: ARM, ARM64, x86, x86_64, emulation mode (ARM ~ x86) +* Control interface: CLI, SSH, VNC, X11, Framebuffer +* Desktop environment: XTerm, LXDE, Xfce, GNOME, KDE, other (manual configuration) +* Supported languages: multilingual interface + +#### Install #### +You can install the app from: +* GitHub: +* Google Play: + +#### Performance #### +SD card read / write speed (10 class) on Android (Samsung Galaxy S II) for file systems vfat, ext2, ext4: +* **vfat**: read speed 14.1 MB/s; write speed 12.0 MB/s +* **ext2**: read speed 14.9 MB/s; write speed 3.9 MB/s +* **ext4**: read speed 14.9 MB/s; write speed 16.6 MB/s +* **ext2 (loop)**: read speed 17.0 MB/s; write speed 7.4 MB/s +* **ext4 (loop)**: read speed 17.2 MB/s; write speed 8.8 MB/s + +Installation time and use space on disk (Debian wheezy/armhf on Samsung Galaxy S II): +* **Without GUI** ~ 0:12 / 260 MB +* **XTerm** ~ 0:14 / 290 MB +* **LXDE** ~ 0:19 / 450 MB +* **XFCE** ~ 0:20 / 495 MB +* **GNOME** ~ 0:55 / 1.3 GB +* **KDE** ~ 1:20 / 1.3 GB + +#### Source code #### +Source code: . The project is written using Android Studio. + +#### Donations #### + diff --git a/README.ru.md b/README.ru.md new file mode 100644 index 00000000..4493f17d --- /dev/null +++ b/README.ru.md @@ -0,0 +1,42 @@ +Linux Deploy +============ + +Copyright (C) 2012-2016 Антон Скшидлевский, [GPLv3](http://opensource.org/licenses/gpl-3.0.html) + +Это приложение с открытым исходным кодом, предназначенное для автоматизации процесса установки, конфигурирования и запуска GNU/Linux дистрибутивов на платформе Android внутри контейнера chroot. Приложение создает образ диска на карте памяти или ином носителе, монтирует его и устанавливает туда выбранный Linux-дистрибутив. Поддерживается установка в файл, прямо на раздел карты памяти, в директорию с файловой системой ext2/ext3/ext4 и в оперативную память. Приложения из Linux-дистрибутива запускаются в chroot окружении, работают параллельно с основной системой и сопоставимы с ней по скорости. Все вносимые изменения на устройстве обратимы, т.е. приложение и созданные им компоненты можно полностью удалить. Установка Linux-дистрибутива осуществляется по сети с официальных зеркал в интернете. Поскольку работа Linux Deploy базируется на системном вызове ядра Linux, то в роли "гостевых" систем могут выступать только дистрибутивы Linux. Через интерфейс программы можно управлять процессом установки Linux-дистрибутива, а после установки можно запускать и останавливать сервисы установленной системы (есть поддержка запуска собственных сценариев). Процесс установки отображается в виде текстовых отчетов в главном окне приложения. Во время установки программа сама настраивает рабочее окружение, которое включает в себя базовую систему, сервер SSH, сервер VNC и графическую среду на выбор. Также через интерфейс программы можно управлять параметрами серверов SSH и VNC. Установка Linux-дистрибутива занимает около 30 минут. Рекомендованный минимальный размер образа диска без графического интерфейса - 512 МБ, а с графическим интерфейсом - 1024 МБ (для LXDE). После начальной установки пароль для доступа по SSH и VNC назначается как "changeme", который можно сменить стандартными средствами дистрибутива, либо через параметры приложения. + +#### Характеристики: #### +* Поддерживаемые дистрибутивы: Debian, Ubuntu, Kali Linux, Arch Linux, Fedora, CentOS, Gentoo, openSUSE, Slackware, RootFS (tgz, tbz2, txz) +* Тип установки: файл образа, директория, раздел диска, оперативная память +* Поддерживаемые файловые системы: ext2, ext3, ext4 +* Поддерживаемые архитектуры: ARM, ARM64, x86, x86_64, режим эмуляции (ARM ~ x86) +* Интерфейс управления: CLI, SSH, VNC, X11, фрейм-буфер +* Окружение рабочего стола: XTerm, LXDE, Xfce, GNOME, KDE, другое (ручная настройка) +* Поддерживаемые языки: мультиязычный интерфейс + +#### Установка #### +Вы можете установить это приложение из: +* GitHub: +* Google Play: + +#### Производительность #### +Скорость чтения/записи SD карты (10 класс) на Android (Samsung Galaxy S II) для файловых систем vfat, ext2, ext4: +* **vfat**: скорость чтения 14.1 МБ/с; скорость записи 12.0 МБ/с +* **ext2**: скорость чтения 14.9 МБ/с; скорость записи 3.9 МБ/с +* **ext4**: скорость чтения 14.9 МБ/с; скорость записи 16.6 МБ/с +* **ext2 (loop)**: скорость чтения 17.0 МБ/с; скорость записи 7.4 МБ/с +* **ext4 (loop)**: скорость чтения 17.2 МБ/с; скорость записи 8.8 МБ/с + +Время установки и занимаемое место на диске (Debian wheezy/armhf на Samsung Galaxy S II): +* **Без графики** ~ 0:12 / 260 МБ +* **XTerm** ~ 0:14 / 290 МБ +* **LXDE** ~ 0:19 / 450 МБ +* **XFCE** ~ 0:20 / 495 МБ +* **GNOME** ~ 0:55 / 1.3 ГБ +* **KDE** ~ 1:20 / 1.3 ГБ + +#### Исходный код #### +Исходный код доступен по адресу: . Проект создан в Android Studio. + +#### Поддержать проект #### + diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 00000000..796b96d1 --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 00000000..bb0994e0 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,27 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 24 + buildToolsVersion "24.0.0" + + defaultConfig { + applicationId "ru.meefik.linuxdeploy" + minSdkVersion 10 + targetSdkVersion 24 + versionCode 202 + versionName "2.0.0" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + compile "com.android.support:support-v4:24.1.1" + compile 'com.android.support:appcompat-v7:24.1.1' + compile 'com.android.support:design:24.1.1' +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 00000000..2498c6a3 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /home/anton/Android/Sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/app/src/androidTest/java/ru/meefik/linuxdeploy/ApplicationTest.java b/app/src/androidTest/java/ru/meefik/linuxdeploy/ApplicationTest.java new file mode 100644 index 00000000..a8889b11 --- /dev/null +++ b/app/src/androidTest/java/ru/meefik/linuxdeploy/ApplicationTest.java @@ -0,0 +1,13 @@ +package ru.meefik.linuxdeploy; + +import android.app.Application; +import android.test.ApplicationTestCase; + +/** + * Testing Fundamentals + */ +public class ApplicationTest extends ApplicationTestCase { + public ApplicationTest() { + super(Application.class); + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..3364575c --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/assets/bin/all/websocket.sh b/app/src/main/assets/bin/all/websocket.sh new file mode 100755 index 00000000..16aff22a --- /dev/null +++ b/app/src/main/assets/bin/all/websocket.sh @@ -0,0 +1,120 @@ +#!/data/data/ru.meefik.linuxdeploy/bin/sh +# websocket.sh +# (C) 2016 Anton Skshidlevsky , MIT +# The cross platform WebSocket implementation for SH. +# https://github.com/meefik/websocket.sh + +[ -n "$WS_SHELL" ] || WS_SHELL="sh" + +# read pipe as hex without separating and add \x for each byte +split_hex() +{ + local hex code + while read -n 2 code + do + if [ -n "$code" ] + then + hex="$hex\x$code" + fi + done + echo -n "$hex" +} + +# get arguments, first argument - 2 +get_arg() +{ + eval "echo -n \$$1" +} + +# check contains a byte 81 +is_packet() +{ + echo -n "$1" | grep -q $(printf '\x81') +} + +# read N bytes from pipe and convert to unsigned decimal 1-byte units (space seporated) +read_dec() +{ + dd bs=$1 count=1 2>/dev/null | od -A n -t u1 -w$1 +} + +# read pipe and convert to websocket frame +# see RFC6455 "Base Framing Protocol" https://tools.ietf.org/html/rfc6455 +ws_send() +{ + local data length + while true + do + # Text frame: 0x81 [length] [data] + # Length: 00-7D -> 0xXX; 0000-FFFF -> 0xXXXX + # base64 max length: 7D -> 93; FFFF -> 48513 + data=$(dd bs=48513 count=1 2>/dev/null | base64) + length=${#data} + # exit if received 0 bytes + [ "$length" -gt 0 ] || break + if [ "$length" -gt 125 ] + then + printf "\x81\x7E$(printf '%04x' ${length} | split_hex)$data" + else + printf "\x81\x$(printf '%02x' ${length})$data" + fi + done +} + +# initialize websocket connection +ws_connect() +{ + local line outkey + while read line + do + if printf "%s" "$line" | grep -q $'^\r$'; then + outkey=$(printf "%s" "$sec_websocket_key" | tr '\r' '\n') + outkey="${outkey}258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + outkey=$(printf "%s" "$outkey" | sha1sum | cut -d ' ' -f 1 | printf $(split_hex) | base64) + #outkey=$(printf %s "$outkey" | openssl dgst -binary -sha1 | openssl base64) + printf "HTTP/1.1 101 Switching Protocols\r\n" + printf "Upgrade: websocket\r\n" + printf "Connection: Upgrade\r\n" + printf "Sec-WebSocket-Accept: %s\r\n" "$outkey" + printf "\r\n" + break + else + case "$line" in + Sec-WebSocket-Key*) + sec_websocket_key=$(get_arg 3 $line) + ;; + esac + fi + done +} + +# main loop +ws_server() +{ + local flag header length byte i + while read -n 1 flag + do + # each packet starts at byte 81 + is_packet "$flag" || continue + # read next 5 bytes: + # 1 -> length + # 2-5 -> encoding bytes + header=$(read_dec 5) + # get packet length + let length=$(get_arg 2 $header)-128 + [ "$length" -gt 0 -a "$length" -le 125 ] || continue + # read packet + let i=0 + for byte in $(read_dec $length) + do + # decoding byte: byte ^ encoding_bytes[i % 4] + let byte=byte^$(get_arg $(($i % 4 + 3)) $header) + printf "\x$(printf '%02x' $byte)" + let i=i+1 + done | base64 -d + done | $WS_SHELL 2>&1 | ws_send +} + +# start +ws_connect && +ws_server diff --git a/app/src/main/assets/bin/arm/busybox b/app/src/main/assets/bin/arm/busybox new file mode 100755 index 00000000..8303c010 Binary files /dev/null and b/app/src/main/assets/bin/arm/busybox differ diff --git a/app/src/main/assets/bin/arm/mke2fs b/app/src/main/assets/bin/arm/mke2fs new file mode 100755 index 00000000..c8f40d2f Binary files /dev/null and b/app/src/main/assets/bin/arm/mke2fs differ diff --git a/app/src/main/assets/bin/arm/pkgdetails b/app/src/main/assets/bin/arm/pkgdetails new file mode 100755 index 00000000..912cae7f Binary files /dev/null and b/app/src/main/assets/bin/arm/pkgdetails differ diff --git a/app/src/main/assets/bin/arm/proot b/app/src/main/assets/bin/arm/proot new file mode 100755 index 00000000..634d21d5 Binary files /dev/null and b/app/src/main/assets/bin/arm/proot differ diff --git a/app/src/main/assets/bin/arm/qemu-i386-static b/app/src/main/assets/bin/arm/qemu-i386-static new file mode 100755 index 00000000..ac9ea9fe Binary files /dev/null and b/app/src/main/assets/bin/arm/qemu-i386-static differ diff --git a/app/src/main/assets/bin/intel/busybox b/app/src/main/assets/bin/intel/busybox new file mode 100755 index 00000000..ec0056ed Binary files /dev/null and b/app/src/main/assets/bin/intel/busybox differ diff --git a/app/src/main/assets/bin/intel/mke2fs b/app/src/main/assets/bin/intel/mke2fs new file mode 100755 index 00000000..531d6285 Binary files /dev/null and b/app/src/main/assets/bin/intel/mke2fs differ diff --git a/app/src/main/assets/bin/intel/pkgdetails b/app/src/main/assets/bin/intel/pkgdetails new file mode 100755 index 00000000..e8f76fba Binary files /dev/null and b/app/src/main/assets/bin/intel/pkgdetails differ diff --git a/app/src/main/assets/bin/intel/proot b/app/src/main/assets/bin/intel/proot new file mode 100755 index 00000000..e0b45415 Binary files /dev/null and b/app/src/main/assets/bin/intel/proot differ diff --git a/app/src/main/assets/bin/intel/qemu-arm-static b/app/src/main/assets/bin/intel/qemu-arm-static new file mode 100755 index 00000000..3fb961b9 Binary files /dev/null and b/app/src/main/assets/bin/intel/qemu-arm-static differ diff --git a/app/src/main/assets/env/cli.sh b/app/src/main/assets/env/cli.sh new file mode 100755 index 00000000..7c2e5207 --- /dev/null +++ b/app/src/main/assets/env/cli.sh @@ -0,0 +1,1303 @@ +#!/bin/bash +################################################################################ +# +# Linux Deploy CLI +# (C) 2012-2016 Anton Skshidlevsky , GPLv3 +# +################################################################################ + +VERSION="2.0.8" + +################################################################################ +# Common +################################################################################ + +msg() +{ + echo "$@" +} + +is_ok() +{ + if [ $? -eq 0 ]; then + if [ -n "$2" ]; then + msg "$2" + fi + return 0 + else + if [ -n "$1" ]; then + msg "$1" + fi + return 1 + fi +} + +get_platform() +{ + local arch="$1" + if [ -z "${arch}" ]; then + arch=$(uname -m) + fi + case "${arch}" in + arm*|aarch64) + echo "arm" + ;; + i[3-6]86|x86*|amd64) + echo "intel" + ;; + *) + echo "unknown" + ;; + esac +} + +get_qemu() +{ + local arch="$1" + local qemu="" + local host_platform=$(get_platform) + local guest_platform=$(get_platform "${arch}") + if [ "${host_platform}" != "${guest_platform}" ]; then + case "${guest_platform}" in + arm) + qemu="qemu-arm-static" + ;; + intel) + qemu="qemu-i386-static" + ;; + *) + qemu="" + ;; + esac + fi + echo ${qemu} +} + +get_uuid() +{ + cat /proc/sys/kernel/random/uuid +} + +multiarch_support() +{ + if [ -d "/proc/sys/fs/binfmt_misc" ]; then + return 0 + else + return 1 + fi +} + +selinux_support() +{ + if [ -d "/sys/fs/selinux" ]; then + return 0 + else + return 1 + fi +} + +loop_support() +{ + if [ -n "$(losetup -f)" ]; then + return 0 + else + return 1 + fi +} + +user_home() +{ + [ -e "${CHROOT_DIR}/etc/passwd" ] || return 1 + local user_name="$1" + [ -n "${user_name}" ] || return 1 + echo $(grep -m1 "^${user_name}:" "${CHROOT_DIR}/etc/passwd" | awk -F: '{print $6}') +} + +user_shell() +{ + [ -e "${CHROOT_DIR}/etc/passwd" ] || return 1 + local user_name="$1" + [ -n "${user_name}" ] || return 1 + echo $(grep -m1 "^${user_name}:" "${CHROOT_DIR}/etc/passwd" | awk -F: '{print $7}') +} + +is_mounted() +{ + local mount_point="$1" + [ -n "${mount_point}" ] || return 1 + if $(grep -q " ${mount_point%/} " /proc/mounts); then + return 0 + else + return 1 + fi +} + +is_archive() +{ + local src="$1" + [ -n "${src}" ] || return 1 + if [ -z "${src##*gz}" -o -z "${src##*bz2}" -o -z "${src##*xz}" ]; then + return 0 + fi + return 1 +} + +get_pids() +{ + local pid pidfile pids + for pid in $* + do + pidfile="${CHROOT_DIR}${pid}" + if [ -e "${pidfile}" ]; then + pid=$(cat "${pidfile}") + fi + if [ -e "/proc/${pid}" ]; then + pids="${pids} ${pid}" + fi + done + if [ -n "${pids}" ]; then + echo ${pids} + return 0 + else + return 1 + fi +} + +is_started() +{ + get_pids $* >/dev/null +} + +is_stopped() +{ + is_started $* + test $? -ne 0 +} + +kill_pids() +{ + local pids=$(get_pids $*) + if [ -n "${pids}" ]; then + kill -9 ${pids} + return $? + fi + return 0 +} + +remove_files() +{ + local item target + for item in $* + do + target="${CHROOT_DIR}${item}" + if [ -e "${target}" ]; then + rm -f "${target}" + fi + done + return 0 +} + +make_dirs() +{ + local item target + for item in $* + do + target="${CHROOT_DIR}${item}" + if [ -d "${target%/*}" -a ! -d "${target}" ]; then + mkdir "${target}" + fi + done + return 0 +} + +chroot_exec() +{ + unset TMP TEMP TMPDIR LD_PRELOAD LD_DEBUG + local path="${PATH}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + if [ "$1" = "-u" ]; then + local username="$2" + shift 2 + fi + case "${METHOD}" in + chroot) + if [ -n "${username}" ]; then + if [ $# -gt 0 ]; then + chroot "${CHROOT_DIR}" /bin/su - ${username} -c "$*" + else + chroot "${CHROOT_DIR}" /bin/su - ${username} + fi + else + PATH="${path}" chroot "${CHROOT_DIR}" $* + fi + ;; + proot) + if [ -z "${PROOT_TMP_DIR}" ]; then + export PROOT_TMP_DIR="${TEMP_DIR}" + fi + local mounts="-b /proc -b /dev -b /sys" + if [ -n "${MOUNTS}" ]; then + mounts="${mounts} -b ${MOUNTS// / -b }" + fi + local emulator + if [ -z "${EMULATOR}" ]; then + EMULATOR=$(get_qemu ${ARCH}) + fi + if [ -n "${EMULATOR}" ]; then + emulator="-q ${EMULATOR}" + fi + if [ -n "${username}" ]; then + if [ $# -gt 0 ]; then + proot -r "${CHROOT_DIR}" -w / ${mounts} ${emulator} -0 -l -e /bin/su - ${username} -c "$*" + else + proot -r "${CHROOT_DIR}" -w / ${mounts} ${emulator} -0 -l -e /bin/su - ${username} + fi + else + PATH="${path}" proot -r "${CHROOT_DIR}" -w / ${mounts} ${emulator} -0 -l -e $* + fi + ;; + esac +} + +sync_env() +{ + local env_url="$1" + [ -n "${env_url}" ] || return 1 + msg -n "Synchronization with server ... " + [ -e "${ENV_DIR}" ] || mkdir -p "${ENV_DIR}" + wget -q -O - "${env_url}" | tar xz -C "${ENV_DIR}" 1>&2 + is_ok "fail" "done" +} + +################################################################################ +# Params +################################################################################ + +params_read() +{ + local conf_file="$1" + [ -e "${conf_file}" ] || return 1 + local item key val + while read item + do + key=$(echo ${item} | grep -o '^[0-9A-Z_]\{1,32\}') + val=${item#${key}=} + if [ -n "${key}" ]; then + eval ${key}="${val}" + if [ -n "${OPTLST##* ${key} *}" ]; then + OPTLST="${OPTLST}${key} " + fi + fi + done < ${conf_file} +} + +params_write() +{ + local conf_file="$1" + [ -n "${conf_file}" ] || return 1 + echo "# ${conf_file##*/} $(date '+%F %R')" > ${conf_file} + local key val + for key in ${OPTLST} + do + eval "val=\$${key}" + if [ -n "${key}" -a -n "${val}" ]; then + echo "${key}=\"${val}\"" >> ${conf_file} + fi + done +} + +params_parse() +{ + OPTIND=1 + if [ $# -gt 0 ] ; then + local item key val + for item in "$@" + do + key=$(expr "${item}" : '--\([0-9a-z-]\{1,32\}=\{0,1\}\)' | tr '\-abcdefghijklmnopqrstuvwxyz' '\_ABCDEFGHIJKLMNOPQRSTUVWXYZ') + if [ -n "${key##*=*}" ]; then + val="true" + else + key=${key%*=} + val=$(expr "${item}" : '--[0-9a-z-]\{1,32\}=\(.*\)') + fi + if [ -n "${key}" ]; then + eval ${key}=\"${val}\" + let OPTIND=OPTIND+1 + if [ -n "${OPTLST##* ${key} *}" ]; then + OPTLST="${OPTLST}${key} " + fi + fi + done + fi + #echo ${OPTLST} | tr ' ' '\n' | awk '!x[$0]++' +} + +params_check() +{ + local params_list="$@" + local key val params_lost + for key in ${params_list} + do + eval "val=\$${key}" + if [ -z "${val}" ]; then + params_lost="${params_lost} ${key}" + fi + done + if [ -n "${params_lost}" ]; then + if [ "${DEBUG_MODE}" = "true" ]; then + msg "Missing parameters:${params_lost}" + fi + return 1 + fi + return 0 +} + + +################################################################################ +# Configs +################################################################################ + +config_which() +{ + local conf_file="$1" + if [ -n "${conf_file}" ]; then + if [ -n "${conf_file##*/*}" ]; then + conf_file="${CONFIG_DIR}/${conf_file}.conf" + fi + echo "${conf_file}" + fi +} + +config_update() +{ + local source_conf="$1"; shift + local target_conf="$1"; shift + params_read "${source_conf}" + params_parse "$@" + params_write "${target_conf}" +} + +config_list() +{ + local conf_file="$1" + local conf + for conf in $(ls "${CONFIG_DIR}/") + do + ( + unset DISTRIB ARCH SUITE INCLUDE + . "${CONFIG_DIR}/${conf}" + formated_desc=$(printf "%-15s %-10s %-10s %-10s %.30s\n" "${conf%.conf}" "${DISTRIB}" "${ARCH}" "${SUITE}" "${INCLUDE}") + msg "${formated_desc}" + ) + done +} + +config_remove() +{ + local conf_file="$1" + if [ -e "${conf_file}" ]; then + rm -f "${conf_file}" + else + return 1 + fi +} + +################################################################################ +# Components +################################################################################ + +component_is_compatible() +{ + local target="$@" + [ -n "${target}" ] || return 0 + local item + for item in ${target} + do + case "${DISTRIB}:${ARCH}:${SUITE}" in + ${item}) + return 0 + ;; + esac + done + return 1 +} + +component_is_exclude() +{ + local component="$1" + [ -n "${component}" ] || return 1 + for item in ${EXCLUDE_COMPONENTS} + do + case "${component}" in + ${item}*) + return 0 + ;; + esac + done + return 1 +} + +component_depends() +{ + local components="$@" + [ -n "${components}" ] || return 0 + local component conf_file TARGET DEPENDS + for component in ${components} + do + component="${component%/}" + # check deadlocks + [ -z "${IGNORE_DEPENDS##* ${component} *}" ] && continue + IGNORE_DEPENDS="${IGNORE_DEPENDS}${component} " + # check component exist + conf_file="${INCLUDE_DIR}/${component}/deploy.conf" + [ -e "${conf_file}" ] || continue + # read component variables + eval $(grep -e '^TARGET=' -e '^DEPENDS=' "${conf_file}") + # check compatibility + if [ "${WITHOUT_CHECK}" != "true" ]; then + component_is_compatible ${TARGET} || continue + fi + if [ "${REVERSE_DEPENDS}" = "true" ]; then + # output + echo ${component} + # process depends + component_depends ${DEPENDS} + else + # process depends + component_depends ${DEPENDS} + # output + echo ${component} + fi + done +} + +component_exec() +{ + local components="$@" + if [ "${WITHOUT_DEPENDS}" != "true" ]; then + components=$(IGNORE_DEPENDS=" " component_depends ${components}) + fi + [ -n "${components}" ] || return 1 + (set -e + for COMPONENT in ${components} + do + COMPONENT_DIR="${INCLUDE_DIR}/${COMPONENT}" + [ -d "${COMPONENT_DIR}" ] || continue + unset NAME DESC TARGET PARAMS DEPENDS EXTENDS + TARGET='*:*:*' + # read config + . "${COMPONENT_DIR}/deploy.conf" + # default functions + do_install() { return 0; } + do_configure() { return 0; } + do_start() { return 0; } + do_stop() { return 0; } + do_status() { return 0; } + do_help() { return 0; } + # load extends + for component in ${EXTENDS} ${COMPONENT} + do + if [ -e "${INCLUDE_DIR}/${component}/deploy.sh" ]; then + . "${INCLUDE_DIR}/${component}/deploy.sh" + fi + done + # exclude components + component_is_exclude ${COMPONENT} && continue + # check parameters + [ "${WITHOUT_CHECK}" != "true" ] && params_check ${PARAMS} + # exec action + [ "${DEBUG_MODE}" = "true" ] && msg "## ${COMPONENT} : ${DO_ACTION}" + set +e + eval ${DO_ACTION} || exit 1 + set -e + done + exit 0) + is_ok || return 1 +} + +component_list() +{ + local components="$@" + local component output DESC + if [ -z "${components}" ]; then + components=$(cd "${INCLUDE_DIR}" && find . -type f -name "deploy.conf" | while read f + do + component="${f%/*}" + component="${component#*/}" + echo "${component}" + done) + fi + components=$(IGNORE_DEPENDS=" " component_depends ${components} | sort) + for component in $components + do + # output + DESC='' + eval $(grep '^DESC=' "${INCLUDE_DIR}/${component}/deploy.conf") + output=$(printf "%-30s %.49s\n" "${component}" "${DESC}") + msg "${output}" + done +} + +################################################################################ +# Containers +################################################################################ + +container_mounted() +{ + if [ "${METHOD}" = "chroot" ]; then + is_mounted "${CHROOT_DIR}" + else + return 0 + fi +} + +mount_part() +{ + case "$1" in + root) + msg -n "/ ... " + if ! is_mounted "${CHROOT_DIR}" ; then + [ -d "${CHROOT_DIR}" ] || mkdir -p "${CHROOT_DIR}" + local mnt_opts + [ -d "${TARGET_PATH}" ] && mnt_opts="bind" || mnt_opts="rw,relatime" + mount -o ${mnt_opts} "${TARGET_PATH}" "${CHROOT_DIR}" && + mount -o remount,exec,suid,dev "${CHROOT_DIR}" + is_ok "fail" "done" || return 1 + else + msg "skip" + fi + ;; + proc) + msg -n "/proc ... " + local target="${CHROOT_DIR}/proc" + if ! is_mounted "${target}" ; then + [ -d "${target}" ] || mkdir -p "${target}" + mount -t proc proc "${target}" + is_ok "fail" "done" + else + msg "skip" + fi + ;; + sys) + msg -n "/sys ... " + local target="${CHROOT_DIR}/sys" + if ! is_mounted "${target}" ; then + [ -d "${target}" ] || mkdir -p "${target}" + mount -t sysfs sys "${target}" + is_ok "fail" "done" + else + msg "skip" + fi + ;; + selinux) + selinux_support || return 0 + msg -n "/sys/fs/selinux ... " + local target="${CHROOT_DIR}/sys/fs/selinux" + if ! is_mounted "${target}" ; then + if [ -e "/sys/fs/selinux/enforce" ]; then + cat /sys/fs/selinux/enforce > "${TEMP_DIR}/selinux_state" + echo 0 > /sys/fs/selinux/enforce + fi + mount -t selinuxfs selinuxfs "${target}" && + mount -o remount,ro,bind "${target}" + is_ok "fail" "done" + else + msg "skip" + fi + ;; + dev) + msg -n "/dev ... " + local target="${CHROOT_DIR}/dev" + if ! is_mounted "${target}" ; then + [ -d "${target}" ] || mkdir -p "${target}" + [ -e "/dev/fd" ] || ln -s /proc/self/fd /dev/ + [ -e "/dev/stdin" ] || ln -s /proc/self/fd/0 /dev/stdin + [ -e "/dev/stdout" ] || ln -s /proc/self/fd/1 /dev/stdout + [ -e "/dev/stderr" ] || ln -s /proc/self/fd/2 /dev/stderr + mount -o bind /dev "${target}" + is_ok "fail" "done" + else + msg "skip" + fi + ;; + tty) + msg -n "/dev/tty ... " + if [ ! -e "/dev/tty0" ]; then + ln -s /dev/null /dev/tty0 + is_ok "fail" "done" + else + msg "skip" + fi + ;; + pts) + msg -n "/dev/pts ... " + local target="${CHROOT_DIR}/dev/pts" + if ! is_mounted "${target}" ; then + [ -d "${target}" ] || mkdir -p "${target}" + mount -o "mode=0620,gid=5" -t devpts devpts "${target}" + is_ok "fail" "done" + else + msg "skip" + fi + ;; + shm) + msg -n "/dev/shm ... " + local target="${CHROOT_DIR}/dev/shm" + if ! is_mounted "${target}" ; then + [ -d "${target}" ] || mkdir -p "${target}" + mount -t tmpfs tmpfs "${target}" + is_ok "fail" "done" + else + msg "skip" + fi + ;; + tun) + msg -n "/dev/net/tun ... " + [ -d "/dev/net" ] || mkdir -p /dev/net + if [ ! -e "/dev/net/tun" ]; then + mknod /dev/net/tun c 10 200 + is_ok "fail" "done" + else + msg "skip" + fi + ;; + binfmt_misc) + multiarch_support || return 0 + local binfmt_dir="/proc/sys/fs/binfmt_misc" + msg -n "${binfmt_dir} ... " + if [ ! -e "${binfmt_dir}/register" ]; then + mount -t binfmt_misc binfmt_misc "${binfmt_dir}" + is_ok "fail" "done" + else + msg "skip" + fi + ;; + esac + + return 0 +} + +container_mount() +{ + [ "${METHOD}" = "chroot" ] || return 0 + + if [ $# -eq 0 ]; then + container_mount root proc sys selinux dev tty pts shm tun binfmt_misc + return $? + fi + + params_check CHROOT_DIR TARGET_PATH || return 1 + + msg "Mounting partitions: " + local item + for item in $* + do + mount_part ${item} || return 1 + done + + return 0 +} + +container_umount() +{ + params_check CHROOT_DIR TARGET_PATH || return 1 + container_mounted || { msg "The container is not mounted." ; return 0; } + + msg -n "Release resources ... " + local is_release=0 + local lsof_full=$(lsof | awk '{print $1}' | grep -c '^lsof') + if [ "${lsof_full}" -eq 0 ]; then + local pids=$(lsof | grep "${CHROOT_DIR%/}" | awk '{print $1}' | uniq) + else + local pids=$(lsof | grep "${CHROOT_DIR%/}" | awk '{print $2}' | uniq) + fi + kill_pids ${pids}; is_ok "fail" "done" + + msg "Unmounting partitions: " + local is_mnt=0 + local mask + for mask in '.*' '*' + do + local parts=$(cat /proc/mounts | awk '{print $2}' | grep "^${CHROOT_DIR%/}/${mask}$" | sort -r) + local part + for part in ${parts} + do + local part_name=$(echo ${part} | sed "s|^${CHROOT_DIR%/}/*|/|g") + msg -n "${part_name} ... " + if [ -z "${part_name##*selinux*}" -a -e "/sys/fs/selinux/enforce" -a -e "${TEMP_DIR}/selinux_state" ]; then + cat "${TEMP_DIR}/selinux_state" > /sys/fs/selinux/enforce + fi + umount ${part} + is_ok "fail" "done" + is_mnt=1 + done + done + [ "${is_mnt}" -eq 1 ]; is_ok " ...nothing mounted" + + msg -n "Disassociating loop device ... " + local loop=$(losetup -a | grep "${TARGET_PATH%/}" | awk -F: '{print $1}') + if [ -n "${loop}" ]; then + losetup -d "${loop}" + fi + is_ok "fail" "done" + + return 0 +} + +container_start() +{ + params_check CHROOT_DIR || return 1 + container_mounted || { msg "The container is not mounted." ; return 1; } + + DO_ACTION='do_start' + if [ $# -gt 0 ]; then + component_exec $@ + else + component_exec ${INCLUDE} + fi +} + +container_stop() +{ + params_check CHROOT_DIR || return 1 + container_mounted || { msg "The container is not mounted." ; return 1; } + + DO_ACTION='do_stop' + if [ $# -gt 0 ]; then + component_exec $@ + else + component_exec ${INCLUDE} + fi +} + +container_shell() +{ + params_check CHROOT_DIR || return 1 + container_mounted || container_mount || return 1 + + DO_ACTION='do_start' + component_exec core + + USER="root" + SHELL="$(user_shell $USER)" + HOME="$(user_home $USER)" + [ -n "${TERM}" ] || TERM="linux" + [ -n "${PS1}" ] || PS1="\u@\h:\w\\$ " + export USER SHELL HOME TERM PS1 + + if [ -e "${CHROOT_DIR}/etc/motd" ]; then + msg $(cat "${CHROOT_DIR}/etc/motd") + fi + + chroot_exec "$@" 2>&1 + + return $? +} + +rootfs_import() +{ + local rootfs_file="$1" + [ -n "${rootfs_file}" ] || return 1 + + params_check CHROOT_DIR || return 1 + container_mounted || container_mount root || return 1 + + case "${rootfs_file}" in + *gz) + msg -n "Importing rootfs from tar.gz archive ... " + if [ -e "${rootfs_file}" ]; then + tar xzvf "${rootfs_file}" -C "${CHROOT_DIR}" 1>&2 + elif [ -z "${rootfs_file##http*}" ]; then + wget -q -O - "${rootfs_file}" | tar xzv -C "${CHROOT_DIR}" 1>&2 + else + msg "fail"; return 1 + fi + is_ok "fail" "done" || return 1 + ;; + *bz2) + msg -n "Importing rootfs from tar.bz2 archive ... " + if [ -e "${rootfs_file}" ]; then + tar xjvf "${rootfs_file}" -C "${CHROOT_DIR}" 1>&2 + elif [ -z "${rootfs_file##http*}" ]; then + wget -q -O - "${rootfs_file}" | tar xjv -C "${CHROOT_DIR}" 1>&2 + else + msg "fail"; return 1 + fi + is_ok "fail" "done" || return 1 + ;; + *xz) + msg -n "Importing rootfs from tar.xz archive ... " + if [ -e "${rootfs_file}" ]; then + tar xJvf "${rootfs_file}" -C "${CHROOT_DIR}" 1>&2 + elif [ -z "${rootfs_file##http*}" ]; then + wget -q -O - "${rootfs_file}" | tar xJv -C "${CHROOT_DIR}" 1>&2 + else + msg "fail"; return 1 + fi + is_ok "fail" "done" || return 1 + ;; + *) + msg "Incorrect filename, supported only gz, bz2 or xz archives." + return 1 + ;; + esac + return 0 +} + +rootfs_export() +{ + local rootfs_file="$1" + [ -n "${rootfs_file}" ] || return 1 + + params_check CHROOT_DIR || return 1 + container_mounted || container_mount root || return 1 + + case "${rootfs_file}" in + *gz) + msg -n "Exporting rootfs as tar.gz archive ... " + tar czvf "${rootfs_file}" --exclude='./dev' --exclude='./sys' --exclude='./proc' -C "${CHROOT_DIR}" . 1>&2 + is_ok "fail" "done" || return 1 + ;; + *bz2) + msg -n "Exporting rootfs as tar.bz2 archive ... " + tar cjvf "${rootfs_file}" --exclude='./dev' --exclude='./sys' --exclude='./proc' -C "${CHROOT_DIR}" . 1>&2 + is_ok "fail" "done" || return 1 + ;; + *xz) + msg -n "Exporting rootfs as tar.xz archive ... " + tar cJvf "${rootfs_file}" --exclude='./dev' --exclude='./sys' --exclude='./proc' -C "${CHROOT_DIR}" . 1>&2 + is_ok "fail" "done" || return 1 + ;; + *) + msg "Incorrect filename, supported only gz, bz2 or xz archives." + return 1 + ;; + esac +} + +container_status() +{ + local model=$(getprop ro.product.model) + if [ -n "${model}" ]; then + msg -n "Device: " + msg "${model}" + fi + + local android=$(getprop ro.build.version.release) + if [ -n "${android}" ]; then + msg -n "Android: " + msg "${android}" + fi + + msg -n "Architecture: " + msg "$(uname -m)" + + msg -n "Kernel: " + msg "$(uname -r)" + + msg -n "Memory: " + local mem_total=$(grep ^MemTotal /proc/meminfo | awk '{print $2}') + let mem_total=${mem_total}/1024 + local mem_free=$(grep ^MemFree /proc/meminfo | awk '{print $2}') + let mem_free=${mem_free}/1024 + msg "${mem_free}/${mem_total} MB" + + msg -n "Swap: " + local swap_total=$(grep ^SwapTotal /proc/meminfo | awk '{print $2}') + let swap_total=${swap_total}/1024 + local swap_free=$(grep ^SwapFree /proc/meminfo | awk '{print $2}') + let swap_free=${swap_free}/1024 + msg "${swap_free}/${swap_total} MB" + + msg -n "SELinux: " + selinux_support && msg "yes" || msg "no" + + msg -n "Loop devices: " + loop_support && msg "yes" || msg "no" + + msg -n "Support binfmt_misc: " + multiarch_support && msg "yes" || msg "no" + + msg -n "Supported FS: " + local supported_fs=$(printf '%s ' $(grep -v nodev /proc/filesystems | sort)) + msg "${supported_fs}" + + [ -n "${CHROOT_DIR}" ] || return 0 + + msg -n "Installed system: " + local linux_version=$([ -r "${CHROOT_DIR}/etc/os-release" ] && . "${CHROOT_DIR}/etc/os-release"; [ -n "${PRETTY_NAME}" ] && echo "${PRETTY_NAME}" || echo "unknown") + msg "${linux_version}" + + msg "Status of components: " + local DO_ACTION='do_status' + local component + component_exec "${INCLUDE}" + + msg "Mounted parts: " + local is_mnt=0 + local item + for item in $(grep "${CHROOT_DIR%/}" /proc/mounts | awk '{print $2}' | sed "s|${CHROOT_DIR%/}/*|/|g") + do + msg "* ${item}" + local is_mnt=1 + done + [ "${is_mnt}" -ne 1 ] && msg " ...nothing mounted" + + msg "Available mount points: " + local is_mountpoints=0 + local mp + for mp in $(grep -v "${CHROOT_DIR%/}" /proc/mounts | grep ^/ | awk '{print $2":"$3}') + do + local part=$(echo ${mp} | awk -F: '{print $1}') + local fstype=$(echo ${mp} | awk -F: '{print $2}') + local block_size=$(stat -c '%s' -f ${part}) + local available=$(stat -c '%a' -f ${part} | awk '{printf("%.1f",$1*'${block_size}'/1024/1024/1024)}') + local total=$(stat -c '%b' -f ${part} | awk '{printf("%.1f",$1*'${block_size}'/1024/1024/1024)}') + if [ -n "${available}" -a -n "${total}" ]; then + msg "* ${part} ${available}/${total} GB (${fstype})" + is_mountpoints=1 + fi + done + [ "${is_mountpoints}" -ne 1 ] && msg " ...no mount points" + + msg "Available partitions: " + local is_partitions=0 + local dev + for dev in /sys/block/*/dev + do + if [ -f ${dev} ]; then + local devname=$(echo ${dev} | sed -e 's@/dev@@' -e 's@.*/@@') + [ -e "/dev/${devname}" ] && local devpath="/dev/${devname}" + [ -e "/dev/block/${devname}" ] && local devpath="/dev/block/${devname}" + [ -n "${devpath}" ] && local parts=$(fdisk -l ${devpath} | grep ^/dev/ | awk '{print $1}') + local part + for part in ${parts} + do + local size=$(fdisk -l ${part} | grep 'Disk.*bytes' | awk '{ sub(/,/,""); print $3" "$4}') + local type=$(fdisk -l ${devpath} | grep ^${part} | tr -d '*' | awk '{str=$6; for (i=7;i<=10;i++) if ($i!="") str=str" "$i; printf("%s",str)}') + msg "* ${part} ${size} (${type})" + local is_partitions=1 + done + fi + done + [ "${is_partitions}" -ne 1 ] && msg " ...no available partitions" +} + +helper() +{ +cat <&1 +if [ "${DEBUG_MODE}" != "true" -a "${TRACE_MODE}" != "true" ]; then + exec 2>/dev/null +fi +if [ "${TRACE_MODE}" = "true" ]; then + set -x +fi + +# which config +CONF_FILE=$(config_which "${PROFILE}") +PROFILE=$(basename "${CONF_FILE}" ".conf") + +# read config +OPTLST=" " # space is required +params_read "${CONF_FILE}" + +# fix params +WITHOUT_CHECK="false" +WITHOUT_DEPENDS="false" +REVERSE_DEPENDS="false" +EXCLUDE_COMPONENTS="" +case "${METHOD}" in +proot) + CHROOT_DIR="${TARGET_PATH}" +;; +*) + METHOD="chroot" +;; +esac + +# exec command +OPTCMD="$1"; shift +case "${OPTCMD}" in +config|conf) + if [ $# -eq 0 ]; then + config_list "${CONF_FILE}" + exit $? + fi + conf_file="${CONF_FILE}" + + # parse options + OPTIND=1 + while getopts :i:rxla FLAG + do + case "${FLAG}" in + r) + config_remove "${CONF_FILE}" + exit $? + ;; + x) + dump_flag="true" + ;; + i) + conf_file=$(config_which "${OPTARG}") + ;; + l) + list_flag="true" + ;; + a) + WITHOUT_CHECK="true" + ;; + *) + if [ ${OPTIND} -gt 1 ]; then + let OPTIND=OPTIND-1 + fi + break + ;; + esac + done + shift $((OPTIND-1)) + + if [ "${dump_flag}" = "true" ]; then + [ -e "${CONF_FILE}" ] && cat "${CONF_FILE}" + elif [ "${list_flag}" = "true" ]; then + if [ $# -eq 0 ]; then + component_list "${INCLUDE}" + else + component_list "$@" + fi + else + config_update "${conf_file}" "${CONF_FILE}" "$@" + fi +;; +deploy) + DO_ACTION='do_install && do_configure' + + # parse options + OPTIND=1 + while getopts :n:ic FLAG + do + case "${FLAG}" in + i) + DO_ACTION='do_install' + ;; + c) + DO_ACTION='do_configure' + ;; + n) + EXCLUDE_COMPONENTS="${EXCLUDE_COMPONENTS} ${OPTARG}" + ;; + *) + if [ ${OPTIND} -gt 1 ]; then + let OPTIND=OPTIND-1 + fi + break + ;; + esac + done + shift $((OPTIND-1)) + + if [ $# -gt 0 ]; then + component_exec "$@" + else + component_exec "${INCLUDE}" + fi +;; +import) + rootfs_import "$@" +;; +export) + rootfs_export "$@" +;; +shell) + container_shell "$@" +;; +mount) + container_mount +;; +umount) + container_umount +;; +start) + # parse options + OPTIND=1 + while getopts :m FLAG + do + case "${FLAG}" in + m) + mount_flag="true" + ;; + *) + if [ ${OPTIND} -gt 1 ]; then + let OPTIND=OPTIND-1 + fi + break + ;; + esac + done + shift $((OPTIND-1)) + + if [ "${mount_flag}" = "true" ]; then + container_mount || exit 1 + fi + + container_start "$@" +;; +stop) + # parse options + OPTIND=1 + while getopts :u FLAG + do + case "${FLAG}" in + u) + umount_flag="true" + ;; + *) + if [ ${OPTIND} -gt 1 ]; then + let OPTIND=OPTIND-1 + fi + break + ;; + esac + done + shift $((OPTIND-1)) + + container_stop "$@" || exit 1 + + if [ "${umount_flag}" = "true" ]; then + container_umount + fi +;; +sync) + sync_env "$@" +;; +status) + container_status +;; +help) + if [ $# -eq 0 ]; then + helper + if [ -n "${INCLUDE}" ]; then + msg "PARAMETERS: " + WITHOUT_CHECK="true" + REVERSE_DEPENDS="true" + DO_ACTION='do_help' + component_exec "${INCLUDE}" || + msg -e ' Included components do not have parameters.\n' + fi + else + WITHOUT_CHECK="true" + WITHOUT_DEPENDS="true" + DO_ACTION='do_info && do_help' + component_exec "$@" + fi +;; + +*) + helper +;; +esac diff --git a/app/src/main/assets/env/include/bootstrap/archlinux/deploy.conf b/app/src/main/assets/env/include/bootstrap/archlinux/deploy.conf new file mode 100644 index 00000000..ab162934 --- /dev/null +++ b/app/src/main/assets/env/include/bootstrap/archlinux/deploy.conf @@ -0,0 +1,7 @@ +# Linux Deploy Component +# (c) Anton Skshidlevsky , GPLv3 + +NAME="archlinux" +DESC="Bootstrap for Arch Linux" +PARAMS="CHROOT_DIR SOURCE_PATH ARCH SUITE" +DEPENDS="bootstrap" diff --git a/app/src/main/assets/env/include/bootstrap/archlinux/deploy.sh b/app/src/main/assets/env/include/bootstrap/archlinux/deploy.sh new file mode 100644 index 00000000..eb0896dc --- /dev/null +++ b/app/src/main/assets/env/include/bootstrap/archlinux/deploy.sh @@ -0,0 +1,108 @@ +#!/bin/sh +# Linux Deploy Component +# (c) Anton Skshidlevsky , GPLv3 + +[ -n "${SUITE}" ] || SUITE="latest" + +pacman_install() +{ + local packages="$@" + [ -n "${packages}" ] || return 1 + (set -e + #rm -f ${CHROOT_DIR}/var/lib/pacman/db.lck || true + chroot_exec -u root pacman -Syq --force --noconfirm ${packages} + rm -f "${CHROOT_DIR}"/var/cache/pacman/pkg/* || true + exit 0) + return $? +} + +pacman_repository() +{ + if [ "$(get_platform ${ARCH})" = "intel" ] + then local repo_url="${SOURCE_PATH%/}/\$repo/os/\$arch" + else local repo_url="${SOURCE_PATH%/}/\$arch/\$repo" + fi + sed -i "s|^[[:space:]]*Architecture[[:space:]]*=.*$|Architecture = ${ARCH}|" "${CHROOT_DIR}/etc/pacman.conf" + sed -i "s|^[[:space:]]*\(CheckSpace\)|#\1|" "${CHROOT_DIR}/etc/pacman.conf" + sed -i "s|^[[:space:]]*SigLevel[[:space:]]*=.*$|SigLevel = Never|" "${CHROOT_DIR}/etc/pacman.conf" + if $(grep -q "^[[:space:]]*Server" "${CHROOT_DIR}/etc/pacman.d/mirrorlist") + then sed -i "s|^[[:space:]]*Server[[:space:]]*=.*|Server = ${repo_url}|" "${CHROOT_DIR}/etc/pacman.d/mirrorlist" + else echo "Server = ${repo_url}" >> "${CHROOT_DIR}/etc/pacman.d/mirrorlist" + fi +} + +do_install() +{ + is_archive "${SOURCE_PATH}" && return 0 + + msg ":: Installing ${COMPONENT} ... " + + local basic_packages="filesystem acl archlinux-keyring attr bash bzip2 ca-certificates coreutils cracklib curl db e2fsprogs expat findutils gawk gcc-libs gdbm glibc gmp gnupg gpgme grep keyutils krb5 libarchive libassuan libcap libgcrypt libgpg-error libgssglue libidn libksba libldap libsasl libssh2 libtirpc linux-api-headers lz4 lzo ncurses nettle openssl pacman pacman-mirrorlist pam pambase perl pinentry pth readline run-parts sed shadow sudo tzdata util-linux xz which zlib" + + if [ "$(get_platform ${ARCH})" = "intel" ] + then local repo_url="${SOURCE_PATH%/}/core/os/${ARCH}" + else local repo_url="${SOURCE_PATH%/}/${ARCH}/core" + fi + + local cache_dir="${CHROOT_DIR}/var/cache/pacman/pkg" + + msg "URL: ${repo_url}" + + msg -n "Preparing for deployment ... " + (set -e + cd "${CHROOT_DIR}" + mkdir etc + echo "root:x:0:0:root:/root:/bin/bash" > etc/passwd + echo "root:x:0:" > etc/group + touch etc/fstab + mkdir tmp; chmod 1777 tmp + mkdir -p var/tmp; chmod 1777 var/tmp + mkdir -p var/games; chmod 775 var/games + mkdir -p var/spool/mail; chmod 1777 var/spool/mail + mkdir -p "${cache_dir}" + exit 0) + is_ok "fail" "done" || return 1 + + msg -n "Retrieving packages list ... " + local pkg_list=$(wget -q -O - "${repo_url}/" | sed -n '/]*href="\([^\"]*\)".*$/\1/p' | awk -F'/' '{print $NF}' | sort -rn) + is_ok "fail" "done" || return 1 + + msg "Retrieving base packages: " + for package in ${basic_packages}; do + msg -n "${package} ... " + local pkg_file=$(echo "${pkg_list}" | grep -m1 -e "^${package}-[[:digit:]].*\.xz$" -e "^${package}-[[:digit:]].*\.gz$") + test "${pkg_file}"; is_ok "fail" || return 1 + # download + local i + for i in 1 2 3 + do + wget -q -c -O "${cache_dir}/${pkg_file}" "${repo_url}/${pkg_file}" && break + sleep 30s + done + # unpack + case "${pkg_file}" in + *gz) tar xzf "${cache_dir}/${pkg_file}" -C "${CHROOT_DIR}" --exclude='./dev' --exclude='./sys' --exclude='./proc' --exclude='.INSTALL' --exclude='.MTREE' --exclude='.PKGINFO';; + *bz2) tar xjf "${cache_dir}/${pkg_file}" -C "${CHROOT_DIR}" --exclude='./dev' --exclude='./sys' --exclude='./proc' --exclude='.INSTALL' --exclude='.MTREE' --exclude='.PKGINFO';; + *xz) tar xJf "${cache_dir}/${pkg_file}" -C "${CHROOT_DIR}" --exclude='./dev' --exclude='./sys' --exclude='./proc' --exclude='.INSTALL' --exclude='.MTREE' --exclude='.PKGINFO';; + *) msg "fail"; return 1;; + esac + is_ok "fail" "done" || return 1 + done + + component_exec core/emulator core/mnt core/net + + msg -n "Updating repository ... " + pacman_repository + is_ok "fail" "done" + + msg "Installing base packages: " + extra_packages=$(chroot_exec -u root /usr/bin/pacman --noconfirm -Sg base | awk '{print $2}' | grep -v -e 'linux' -e 'kernel' | xargs) + pacman_install ${basic_packages} ${extra_packages} + is_ok || return 1 + + msg -n "Clearing cache ... " + rm -f "${cache_dir}"/* $(find "${CHROOT_DIR}/etc" -type f -name "*.pacorig") + is_ok "skip" "done" + + return 0 +} diff --git a/app/src/main/assets/env/include/bootstrap/centos/deploy.conf b/app/src/main/assets/env/include/bootstrap/centos/deploy.conf new file mode 100644 index 00000000..8b2becfb --- /dev/null +++ b/app/src/main/assets/env/include/bootstrap/centos/deploy.conf @@ -0,0 +1,7 @@ +# Linux Deploy Component +# (c) Anton Skshidlevsky , GPLv3 + +NAME="centos" +DESC="Bootstrap for CentOS" +PARAMS="CHROOT_DIR SOURCE_PATH ARCH SUITE" +DEPENDS="bootstrap" diff --git a/app/src/main/assets/env/include/bootstrap/centos/deploy.sh b/app/src/main/assets/env/include/bootstrap/centos/deploy.sh new file mode 100644 index 00000000..62a23544 --- /dev/null +++ b/app/src/main/assets/env/include/bootstrap/centos/deploy.sh @@ -0,0 +1,106 @@ +#!/bin/sh +# Linux Deploy Component +# (c) Anton Skshidlevsky , GPLv3 + +yum_install() +{ + local packages="$@" + [ -n "${packages}" ] || return 1 + (set -e + chroot_exec -u root yum install ${packages} --nogpgcheck --skip-broken -y + chroot_exec -u root yum clean all + exit 0) + return $? +} + +yum_groupinstall() +{ + local groupname="$@" + [ -n "${groupname}" ] || return 1 + (set -e + chroot_exec -u root yum groupinstall ${groupname} --nogpgcheck --skip-broken -y + chroot_exec -u root yum clean all + exit 0) + return $? +} + +yum_repository() +{ + chroot_exec -u root yum-config-manager --disable '*' >/dev/null + local repo_file="${CHROOT_DIR}/etc/yum.repos.d/CentOS-${SUITE}-${ARCH}.repo" + local repo_url="${SOURCE_PATH%/}/${SUITE}/os/${ARCH}" + echo "[centos-${SUITE}-${ARCH}]" > "${repo_file}" + echo "name=CentOS ${SUITE} - ${ARCH}" >> "${repo_file}" + echo "failovermethod=priority" >> "${repo_file}" + echo "baseurl=${repo_url}" >> "${repo_file}" + echo "enabled=1" >> "${repo_file}" + echo "metadata_expire=7d" >> "${repo_file}" + echo "gpgcheck=0" >> "${repo_file}" + chmod 644 "${repo_file}" +} + +do_install() +{ + is_archive "${SOURCE_PATH}" && return 0 + + msg ":: Installing ${COMPONENT} ... " + + local basic_packages="audit-libs basesystem bash bzip2-libs ca-certificates centos-release chkconfig coreutils cpio cracklib cracklib-dicts cryptsetup-libs curl cyrus-sasl-lib dbus dbus-libs device-mapper device-mapper-libs diffutils elfutils-libelf elfutils-libs expat file-libs filesystem gawk gdbm glib2 glibc glibc-common gmp gnupg2 gpgme grep gzip info keyutils-libs kmod kmod-libs krb5-libs libacl libassuan libattr libblkid libcap libcap-ng libcom_err libcurl libdb libdb-utils libffi libgcc libgcrypt libgpg-error libidn libmount libpwquality libselinux libsemanage libsepol libssh2 libstdc++ libtasn1 libuser libutempter libuuid libverto libxml2 lua ncurses ncurses-base ncurses-libs nspr nss nss-softokn nss-softokn-freebl nss-sysinit nss-tools nss-util openldap openssl-libs p11-kit p11-kit-trust pam pcre pinentry pkgconfig popt pth pygpgme pyliblzma python python-chardet python-iniparse python-kitchen python-libs python-pycurl python-urlgrabber pyxattr qrencode-libs readline rootfiles rpm rpm-build-libs rpm-libs rpm-python sed selinux-policy setup shadow-utils shared-mime-info sqlite sudo systemd systemd-libs tzdata ustr util-linux vim-minimal which xz-libs yum yum-metadata-parser yum-plugin-fastestmirror yum-utils zlib" + local repo_url="${SOURCE_PATH%/}/${SUITE}/os/${ARCH}" + + msg "URL: ${repo_url}" + + msg -n "Preparing for deployment ... " + tar xzf "${COMPONENT_DIR}/filesystem.tgz" -C "${CHROOT_DIR}" + is_ok "fail" "done" || return 1 + + msg -n "Retrieving packages list ... " + local pkg_list="${CHROOT_DIR}/tmp/packages.list" + (set -e + repodata=$(wget -q -O - "${repo_url}/repodata/repomd.xml" | sed -n '/]*href="\([^\"]*\-primary\.xml\.gz\)".*$/\1/p') + [ -z "${repodata}" ] && exit 1 + wget -q -O - "${repo_url}/${repodata}" | gzip -dc | sed -n '/]*href="\([^\"]*\)".*$/\1/p' > "${pkg_list}" + exit 0) + is_ok "fail" "done" || return 1 + + msg "Retrieving base packages: " + local package i pkg_url pkg_file + for package in ${basic_packages}; do + msg -n "${package} ... " + pkg_url=$(grep -m1 -e "^.*/${package}-[0-9][0-9\.\-].*\.rpm$" "${pkg_list}") + test "${pkg_url}"; is_ok "skip" || continue + pkg_file="${pkg_url##*/}" + # download + for i in 1 2 3 + do + wget -q -c -O "${CHROOT_DIR}/tmp/${pkg_file}" "${repo_url}/${pkg_url}" && break + sleep 30s + done + [ "${package}" = "filesystem" ] && { msg "done"; continue; } + # unpack + (cd "${CHROOT_DIR}"; rpm2cpio "./tmp/${pkg_file}" | cpio -idmu) + is_ok "fail" "done" || return 1 + done + + component_exec core/emulator + + msg -n "Updating a packages database ... " + chroot_exec /bin/rpm -iv --excludepath / --force --nosignature --nodeps --justdb /tmp/*.rpm >/dev/null + is_ok "fail" "done" || return 1 + + msg -n "Clearing cache ... " + rm -rf "${CHROOT_DIR}"/tmp/* + is_ok "skip" "done" + + component_exec core/mnt core/net + + msg -n "Updating repository ... " + yum_repository + is_ok "fail" "done" + + msg "Installing minimal environment: " + yum_groupinstall "Minimal Install" --exclude filesystem,openssh-server + is_ok || return 1 + + return 0 +} diff --git a/app/src/main/assets/env/include/bootstrap/centos/filesystem.tgz b/app/src/main/assets/env/include/bootstrap/centos/filesystem.tgz new file mode 100644 index 00000000..c2f8db27 Binary files /dev/null and b/app/src/main/assets/env/include/bootstrap/centos/filesystem.tgz differ diff --git a/app/src/main/assets/env/include/bootstrap/debian/debootstrap/debootstrap b/app/src/main/assets/env/include/bootstrap/debian/debootstrap/debootstrap new file mode 100644 index 00000000..79ec37f6 --- /dev/null +++ b/app/src/main/assets/env/include/bootstrap/debian/debootstrap/debootstrap @@ -0,0 +1,678 @@ +#!/bin/sh -e + +VERSION='1.0.67-meefik' + +unset TMP TEMP TMPDIR || true + +# might not be exported if we're running from init=/bin/sh or similar +export PATH + +########################################################################### + +if [ -z "$DEBOOTSTRAP_DIR" ]; then + if [ -x /debootstrap/debootstrap ]; then + DEBOOTSTRAP_DIR=/debootstrap + else + DEBOOTSTRAP_DIR=/usr/share/debootstrap + fi +fi + +. $DEBOOTSTRAP_DIR/functions +exec 4>&1 + +LANG=C +USE_COMPONENTS=main +KEYRING="" +DISABLE_KEYRING="" +VARIANT="" +ARCH="" +HOST_ARCH="" +HOST_OS="" +KEEP_DEBOOTSTRAP_DIR="" +USE_DEBIANINSTALLER_INTERACTION="" +SECOND_STAGE_ONLY="" +PRINT_DEBS="" +CHROOTDIR="" +MAKE_TARBALL="" +KEEP_DEBOOTSTRAP_DIR="" +EXTRACTOR_OVERRIDE="" +UNPACK_TARBALL="" +ADDITIONAL="" +EXCLUDE="" +VERBOSE="" +CERTIFICATE="" +CHECKCERTIF="" +PRIVATEKEY="" + +DEF_MIRROR="http://ftp.us.debian.org/debian" +DEF_HTTPS_MIRROR="https://mirrors.kernel.org/debian" + +export LANG USE_COMPONENTS +umask 022 + +########################################################################### + +## phases: +## finddebs dldebs printdebs first_stage second_stage + +RESOLVE_DEPS=true + +WHAT_TO_DO="finddebs dldebs first_stage second_stage" +am_doing_phase () { + # usage: if am_doing_phase finddebs; then ...; fi + local x; + for x in "$@"; do + if echo " $WHAT_TO_DO " | grep -q " $x "; then return 0; fi + done + return 1 +} + +########################################################################### + +usage_err() +{ + info USAGE1 "usage: [OPTION]... [ [ + + + + + +
+ + + + diff --git a/app/src/main/ic_launcher-web.png b/app/src/main/ic_launcher-web.png new file mode 100644 index 00000000..da71e34f Binary files /dev/null and b/app/src/main/ic_launcher-web.png differ diff --git a/app/src/main/java/ru/meefik/linuxdeploy/AboutActivity.java b/app/src/main/java/ru/meefik/linuxdeploy/AboutActivity.java new file mode 100644 index 00000000..3be458bc --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/AboutActivity.java @@ -0,0 +1,32 @@ +package ru.meefik.linuxdeploy; + +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; +import android.text.method.LinkMovementMethod; +import android.widget.TextView; + +public class AboutActivity extends AppCompatActivity { + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + PrefStore.setLocale(this); + setContentView(R.layout.activity_about); + TextView atv = (TextView) findViewById(R.id.aboutTextView); + atv.setMovementMethod(LinkMovementMethod.getInstance()); + TextView vtv = (TextView) findViewById(R.id.versionView); + vtv.setText(getString(R.string.app_version, PrefStore.getVersion(this))); + } + + @Override + public void setTheme(int resId) { + super.setTheme(PrefStore.getTheme(this)); + } + + @Override + public void onResume() { + super.onResume(); + setTitle(R.string.title_activity_about); + } + +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/AppCompatPreferenceActivity.java b/app/src/main/java/ru/meefik/linuxdeploy/AppCompatPreferenceActivity.java new file mode 100644 index 00000000..092fb081 --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/AppCompatPreferenceActivity.java @@ -0,0 +1,139 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ru.meefik.linuxdeploy; + +import android.content.res.Configuration; +import android.os.Bundle; +import android.preference.PreferenceActivity; +import android.support.annotation.LayoutRes; +import android.support.annotation.Nullable; +import android.support.v4.app.NavUtils; +import android.support.v7.app.ActionBar; +import android.support.v7.app.AppCompatDelegate; +import android.support.v7.widget.Toolbar; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; + +/** + * A {@link PreferenceActivity} which implements and proxies the necessary calls + * to be used with AppCompat. + *

+ * This technique can be used with an {@link android.app.Activity} class, not just + * {@link PreferenceActivity}. + */ +public abstract class AppCompatPreferenceActivity extends PreferenceActivity { + private AppCompatDelegate mDelegate; + + @Override + protected void onCreate(Bundle savedInstanceState) { + getDelegate().installViewFactory(); + getDelegate().onCreate(savedInstanceState); + super.onCreate(savedInstanceState); + } + + @Override + protected void onPostCreate(Bundle savedInstanceState) { + super.onPostCreate(savedInstanceState); + getDelegate().onPostCreate(savedInstanceState); + } + + public ActionBar getSupportActionBar() { + return getDelegate().getSupportActionBar(); + } + + public void setSupportActionBar(@Nullable Toolbar toolbar) { + getDelegate().setSupportActionBar(toolbar); + } + + @Override + public MenuInflater getMenuInflater() { + return getDelegate().getMenuInflater(); + } + + @Override + public void setContentView(@LayoutRes int layoutResID) { + getDelegate().setContentView(layoutResID); + } + + @Override + public void setContentView(View view) { + getDelegate().setContentView(view); + } + + @Override + public void setContentView(View view, ViewGroup.LayoutParams params) { + getDelegate().setContentView(view, params); + } + + @Override + public void addContentView(View view, ViewGroup.LayoutParams params) { + getDelegate().addContentView(view, params); + } + + @Override + protected void onPostResume() { + super.onPostResume(); + getDelegate().onPostResume(); + } + + @Override + protected void onTitleChanged(CharSequence title, int color) { + super.onTitleChanged(title, color); + getDelegate().setTitle(title); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); + getDelegate().onConfigurationChanged(newConfig); + } + + @Override + protected void onStop() { + super.onStop(); + getDelegate().onStop(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + getDelegate().onDestroy(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + NavUtils.navigateUpFromSameTask(this); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + public void invalidateOptionsMenu() { + getDelegate().invalidateOptionsMenu(); + } + + private AppCompatDelegate getDelegate() { + if (mDelegate == null) { + mDelegate = AppCompatDelegate.create(this, null); + } + return mDelegate; + } +} \ No newline at end of file diff --git a/app/src/main/java/ru/meefik/linuxdeploy/BootReceiver.java b/app/src/main/java/ru/meefik/linuxdeploy/BootReceiver.java new file mode 100644 index 00000000..ff96e09b --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/BootReceiver.java @@ -0,0 +1,21 @@ +package ru.meefik.linuxdeploy; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +public class BootReceiver extends BroadcastReceiver { + + @Override + public void onReceive(final Context context, Intent intent) { + switch (intent.getAction()) { + case Intent.ACTION_BOOT_COMPLETED: + EnvUtils.execService(context, "start", "start -m"); + break; + case Intent.ACTION_SHUTDOWN: + EnvUtils.execService(context, "stop", "stop -u"); + break; + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/ru/meefik/linuxdeploy/EnvUtils.java b/app/src/main/java/ru/meefik/linuxdeploy/EnvUtils.java new file mode 100644 index 00000000..7e776478 --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/EnvUtils.java @@ -0,0 +1,631 @@ +package ru.meefik.linuxdeploy; + +import android.content.Context; +import android.content.Intent; +import android.content.res.AssetManager; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.Closeable; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; + +public class EnvUtils { + + /** + * Closeable helper + * + * @param c closable object + */ + private static void close(Closeable c) { + if (c != null) { + try { + c.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + /** + * Extract file to env directory + * + * @param c context + * @param target target directory + * @param rootAsset root asset name + * @param path path to asset file + * @return true if success + */ + private static boolean extractFile(Context c, String target, String rootAsset, String path) { + AssetManager assetManager = c.getAssets(); + InputStream in = null; + OutputStream out = null; + try { + in = assetManager.open(rootAsset + path); + File fname = new File(target + path); + fname.delete(); + out = new FileOutputStream(fname); + byte[] buffer = new byte[1024]; + int read; + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + out.flush(); + } catch (IOException e) { + e.printStackTrace(); + return false; + } finally { + close(in); + close(out); + } + return true; + } + + /** + * Extract path to env directory + * + * @param c context + * @param target target directory + * @param rootAsset root asset name + * @param path path to asset directory + * @return true if success + */ + private static boolean extractDir(Context c, String target, String rootAsset, String path) { + AssetManager assetManager = c.getAssets(); + try { + String[] assets = assetManager.list(rootAsset + path); + if (assets.length == 0) { + if (!extractFile(c, target, rootAsset, path)) return false; + } else { + String fullPath = target + path; + File dir = new File(fullPath); + if (!dir.exists()) dir.mkdir(); + for (String asset : assets) { + if (!extractDir(c, target, rootAsset, path + "/" + asset)) + return false; + } + } + } catch (IOException e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * Recursive remove all from directory + * + * @param path path to directory + */ + private static void cleanDirectory(File path) { + if (path == null) return; + if (path.exists()) { + for (File f : path.listFiles()) { + if (f.isDirectory()) cleanDirectory(f); + f.delete(); + } + path.delete(); + } + } + + /** + * Recursive set permissions to directory + * + * @param path path to directory + */ + private static void setPermissions(File path) { + if (path == null) return; + if (path.exists()) { + path.setReadable(true, false); + path.setExecutable(true, false); + for (File f : path.listFiles()) { + if (f.isDirectory()) setPermissions(f); + f.setReadable(true, false); + f.setExecutable(true, false); + } + } + } + + /** + * Check root permissions + * + * @return true if success + */ + public static boolean isRooted() { + boolean result = false; + OutputStream stdin = null; + InputStream stdout = null; + try { + Process process = Runtime.getRuntime().exec("su"); + stdin = process.getOutputStream(); + stdout = process.getInputStream(); + + DataOutputStream os = null; + try { + os = new DataOutputStream(stdin); + os.writeBytes("ls /data\n"); + os.writeBytes("exit\n"); + os.flush(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + close(os); + } + + int n = 0; + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(stdout)); + while (reader.readLine() != null) { + n++; + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + close(reader); + } + + if (n > 0) { + result = true; + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + close(stdout); + close(stdin); + } + return result; + } + + /** + * Update version file + * + * @param c context + * @return true if success + */ + private static boolean setVersion(Context c) { + boolean result = false; + String f = PrefStore.getDataDir(c) + "/version"; + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter(f)); + bw.write(PrefStore.getVersion(c)); + result = true; + } catch (IOException e) { + e.printStackTrace(); + } finally { + close(bw); + } + return result; + } + + /** + * Check latest env version + * + * @param c context + * @return true if success + */ + public static boolean isLatestVersion(Context c) { + File f = new File(PrefStore.getDataDir(c) + "/version"); + if (!f.exists()) return false; + boolean result = false; + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(f)); + String line = br.readLine(); + if (PrefStore.getVersion(c).equals(line)) result = true; + } catch (IOException e) { + e.printStackTrace(); + } finally { + close(br); + } + return result; + } + + /** + * Remove version file + * + * @param c context + * @return true if success + */ + public static boolean resetVersion(Context c) { + File f = new File(PrefStore.getDataDir(c) + "/version"); + return f.delete(); + } + + /** + * Make linuxdeploy script + * + * @param c context + * @return true if success + */ + public static boolean makeScript(Context c) { + boolean result = false; + String scriptFile = PrefStore.getBinDir(c) + "/linuxdeploy"; + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter(scriptFile)); + bw.write("#!" + PrefStore.getShell(c) + "\n"); + bw.write("PATH=" + PrefStore.getPath(c) + ":$PATH\n"); + bw.write("ENV_DIR=\"" + PrefStore.getEnvDir(c) + "\"\n"); + bw.write("TEMP_DIR=\"" + PrefStore.getTmpDir(c) + "\"\n"); + bw.write(". \"${ENV_DIR}/cli.sh\"\n"); + result = true; + } catch (IOException e) { + e.printStackTrace(); + } finally { + close(bw); + } + return result; + } + + /** + * Execute commands from system shell + * + * @param c context + * @param params list of commands + * @return true if success + */ + public static boolean exec(final Context c, final String shell, final List params) { + if (params == null || params.size() == 0) { + Logger.log(c, "No scripts for processing.\n"); + return false; + } + if ("su".equals(shell)) { + if (!isRooted()) { + Logger.log(c, "Requires superuser privileges (root).\n"); + return false; + } + } + boolean result = false; + OutputStream stdin = null; + InputStream stdout = null; + InputStream stderr = null; + try { + Process process = Runtime.getRuntime().exec(shell); + + stdin = process.getOutputStream(); + stdout = process.getInputStream(); + stderr = process.getErrorStream(); + + params.add(0, "PATH=" + PrefStore.getPath(c) + ":$PATH"); + params.add("exit $?"); + if (PrefStore.isTraceMode(c)) params.add(0, "set -x"); + + DataOutputStream os = null; + try { + os = new DataOutputStream(stdin); + for (String cmd : params) { + os.writeBytes(cmd + "\n"); + } + os.flush(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + close(os); + } + + // show stdout log + final InputStream out = stdout; + (new Thread() { + @Override + public void run() { + Logger.log(c, out); + } + }).start(); + + // show stderr log + final InputStream err = stderr; + if (PrefStore.isDebugMode(c)) { + (new Thread() { + @Override + public void run() { + Logger.log(c, err); + } + }).start(); + } + + if (process.waitFor() == 0) result = true; + } catch (Exception e) { + result = false; + e.printStackTrace(); + } finally { + close(stdin); + close(stdout); + close(stderr); + } + return result; + } + + /** + * Update operating environment + * + * @param c context + * @return true if success + */ + public static boolean updateEnv(Context c) { + Logger.log(c, "Updating environment ... "); + + // stop telnetd + execService(c, "telnetd", "stop"); + //stop httpd + execService(c, "httpd", "stop"); + + // extract bin assets + if (!extractDir(c, PrefStore.getBinDir(c), "bin/all", "")) { + Logger.log(c, "fail\n"); + return false; + } + if (!extractDir(c, PrefStore.getBinDir(c), "bin/" + PrefStore.getArch(), "")) { + Logger.log(c, "fail\n"); + return false; + } + + // extract env assets + if (!extractDir(c, PrefStore.getEnvDir(c), "env", "")) { + Logger.log(c, "fail\n"); + return false; + } + + // extract web assets + if (!extractDir(c, PrefStore.getWebDir(c), "web", "")) { + Logger.log(c, "fail\n"); + return false; + } + + // make linuxdeploy script + if (!makeScript(c)) { + Logger.log(c, "fail\n"); + return false; + } + + // make tmp directory + File tmpDir = new File(PrefStore.getTmpDir(c)); + tmpDir.mkdirs(); + + // make config directory + File configDir = new File(PrefStore.getConfigDir(c)); + configDir.mkdirs(); + + // create .nomedia + File noMedia = new File(PrefStore.getEnvDir(c) + "/.nomedia"); + try { + noMedia.createNewFile(); + } catch (IOException ignored) { + } + + // set permissions + File binDir = new File(PrefStore.getBinDir(c)); + setPermissions(binDir); + File cgiDir = new File(PrefStore.getWebDir(c) + "/cgi-bin"); + setPermissions(cgiDir); + + // install applets + List params = new ArrayList<>(); + params.add("busybox --install -s " + PrefStore.getBinDir(c)); + exec(c, "sh", params); + + // update cli.conf + if (!PrefStore.getSettingsConfFile(c).exists()) PrefStore.dumpSettings(c); + // update profile.conf + if (!PrefStore.getPropertiesConfFile(c).exists()) PrefStore.dumpProperties(c); + + // update version + if (!setVersion(c)) { + Logger.log(c, "fail\n"); + return false; + } + + // start telnetd + execService(c, "telnetd", "start"); + //start httpd + execService(c, "httpd", "start"); + + Logger.log(c, "done\n"); + return true; + } + + /** + * Make symlink on linuxdeploy script in /system/bin + * + * @param c context + * @return true if success + */ + public static boolean makeSymlink(Context c) { + Logger.log(c, "Making CLI symlink ... "); + List params = new ArrayList<>(); + params.add("rm -f /system/bin/linuxdeploy"); + params.add("ln -s " + + PrefStore.getBinDir(c) + + "/linuxdeploy /system/bin/linuxdeploy || " + + "{ mount -o rw,remount /system; rm -f /system/bin/linuxdeploy; ln -s " + + PrefStore.getBinDir(c) + + "/linuxdeploy /system/bin/linuxdeploy; mount -o ro,remount /system; }"); + if (EnvUtils.exec(c, "su", params)) { + Logger.log(c, "done\n"); + return true; + } else { + Logger.log(c, "fail\n"); + return false; + } + } + + /** + * Remove operating environment + * + * @param c context + * @return true if success + */ + public static boolean removeEnv(Context c) { + Logger.log(c, "Removing environment ... "); + + // remove version file + resetVersion(c); + + // stop telnetd + execService(c, "telnetd", "stop"); + + //stop httpd + execService(c, "httpd", "stop"); + + // remove symlink + File ldSymlink = new File("/system/bin/linuxdeploy"); + if (ldSymlink.exists()) { + // exec shell commands + List params = new ArrayList<>(); + params.add("if [ -e /system/bin/linuxdeploy ]; then " + + "rm -f /system/bin/linuxdeploy || " + + "{ mount -o rw,remount /system; rm -f /system/bin/linuxdeploy; mount -o ro,remount /system; };" + + "fi"); + exec(c, "su", params); + } + + // clean web directory + File webDir = new File(PrefStore.getWebDir(c)); + cleanDirectory(webDir); + + // clean env directory + File envDir = new File(PrefStore.getEnvDir(c)); + cleanDirectory(envDir); + + // clean tmp directory + File tmpDir = new File(PrefStore.getTmpDir(c)); + cleanDirectory(tmpDir); + + // clean bin directory + File binDir = new File(PrefStore.getBinDir(c)); + cleanDirectory(binDir); + + Logger.log(c, "done\n"); + return true; + } + + /** + * Execute linuxdeploy script + * + * @param c context + * @param cmd command + * @param args arguments + * @return true if success + */ + public static boolean linuxdeploy(Context c, String cmd, String args) { + List params = new ArrayList<>(); + String opts = ""; + if (PrefStore.isDebugMode(c)) opts += "-d "; + if (PrefStore.isTraceMode(c)) opts += "-t "; + if (args == null) args = ""; + else args = " " + args; + params.add("printf '>>> " + cmd + "\n'"); + params.add(PrefStore.getBinDir(c) + "/linuxdeploy " + opts + cmd + args); + params.add("printf '<<< " + cmd + "\n'"); + String shell = PrefStore.isRootRequired(c) ? "su" : "sh"; + return exec(c, shell, params); + } + + /** + * Execute command via service + * + * @param c context + * @param args command and arguments + */ + public static void execService(Context c, String cmd, String args) { + Intent service = new Intent(c, ExecService.class); + service.putExtra("cmd", cmd); + service.putExtra("args", args); + c.startService(service); + } + + /** + * Start/stop telnetd daemon + * + * @param c context + * @param cmd command: start, stop or restart + * @return true if success + */ + public static boolean telnetd(Context c, String cmd) { + List params = new ArrayList<>(); + if (cmd == null) cmd = PrefStore.isTelnet(c) ? "start" : "stop"; + switch (cmd) { + case "restart": + case "stop": + params.add("pkill -9 telnetd"); + if (cmd.equals("stop")) break; + case "start": + if (!PrefStore.isTelnet(c)) break; + String args = ""; + args += " -l " + PrefStore.getShell(c); + args += " -p " + PrefStore.getTelnetPort(c); + args += " -f " + PrefStore.getWebDir(c) + "/issue"; + if (PrefStore.isTelnetLocalhost(c)) args += " -b 127.0.0.1"; + params.add("pgrep telnetd >/dev/null && exit"); + params.add("export TERM=\"xterm\""); + params.add("export HOME=\"" + PrefStore.getEnvDir(c) + "\""); + params.add("cd \"$HOME\""); + params.add("telnetd" + args); + } + return params.size() > 0 && exec(c, "sh", params); + } + + + /** + * Start/stop httpd daemon + * + * @param c context + * @param cmd command: start, stop or restart + * @return true if success + */ + public static boolean httpd(Context c, String cmd) { + List params = new ArrayList<>(); + if (cmd == null) cmd = PrefStore.isHttp(c) ? "start" : "stop"; + switch (cmd) { + case "restart": + case "stop": + params.add("pkill -9 httpd"); + if (cmd.equals("stop")) break; + case "start": + if (!PrefStore.isHttp(c)) break; + File conf = PrefStore.getHttpConfFile(c); + EnvUtils.makeHttpdConf(c, conf); + params.add("pgrep httpd >/dev/null && exit"); + params.add("export WS_SHELL=\"telnet 127.0.0.1 " + PrefStore.getTelnetPort(c) + "\""); + params.add("export ENV_DIR=\"" + PrefStore.getEnvDir(c) + "\""); + params.add("export HOME=\"" + PrefStore.getEnvDir(c) + "\""); + params.add("cd " + PrefStore.getWebDir(c)); + params.add("httpd " + " -p " + PrefStore.getHttpPort(c) + " -c " + conf); + } + return params.size() > 0 && exec(c, "sh", params); + } + + /** + * Make httpd.conf file + * + * @param c context + * @return true if success + */ + public static boolean makeHttpdConf(Context c, File conf) { + boolean result = false; + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter(conf)); + for(String part: PrefStore.getHttpConf(c).split(" ")) { + bw.write(part + "\n"); + } + result = true; + } catch (IOException e) { + e.printStackTrace(); + } finally { + close(bw); + } + return result; + } + +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/ExecService.java b/app/src/main/java/ru/meefik/linuxdeploy/ExecService.java new file mode 100644 index 00000000..f8d016bc --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/ExecService.java @@ -0,0 +1,61 @@ +package ru.meefik.linuxdeploy; + +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.os.IBinder; + +public class ExecService extends Service { + + Context mContext; + + @Override + public void onCreate() { + super.onCreate(); + mContext = getApplicationContext(); + PrefStore.showIcon(mContext, null); + } + + @Override + public IBinder onBind(Intent arg0) { + return null; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + if (intent != null) { + final String cmd = intent.getStringExtra("cmd"); + final String args = intent.getStringExtra("args"); + Thread thread = new Thread(new Runnable() { + @Override + public void run() { + switch (cmd) { + case "telnetd": + EnvUtils.telnetd(mContext, args); + break; + case "httpd": + EnvUtils.httpd(mContext, args); + break; + case "update": + if (!EnvUtils.updateEnv(mContext)) break; + if (PrefStore.isCliSymlink(mContext)) { + EnvUtils.makeSymlink(mContext); + } + break; + case "remove": + EnvUtils.removeEnv(mContext); + break; + default: + if (!EnvUtils.isLatestVersion(mContext)) { + EnvUtils.updateEnv(mContext); + } + EnvUtils.linuxdeploy(mContext, cmd, args); + } + } + }); + thread.start(); + } + return super.onStartCommand(intent, flags, startId); + } + +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/FullscreenActivity.java b/app/src/main/java/ru/meefik/linuxdeploy/FullscreenActivity.java new file mode 100644 index 00000000..c6011a67 --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/FullscreenActivity.java @@ -0,0 +1,46 @@ +package ru.meefik.linuxdeploy; + +import android.content.pm.ActivityInfo; +import android.content.res.Configuration; +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.Toolbar; +import android.view.Window; +import android.view.WindowManager; + +public class FullscreenActivity extends AppCompatActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // remove title + supportRequestWindowFeature(Window.FEATURE_NO_TITLE); + getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, + WindowManager.LayoutParams.FLAG_FULLSCREEN); + + setContentView(R.layout.activity_fullscreen); + } + + @Override + public void onResume() { + super.onResume(); + + // Screen lock + if (PrefStore.isScreenLock(this)) + this.getWindow().addFlags( + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + else this.getWindow().clearFlags( + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + + // Set screen orientation (freeze) + int ot = getResources().getConfiguration().orientation; + if (ot == Configuration.ORIENTATION_LANDSCAPE) { + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + } else { + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); + } + + } + +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/Logger.java b/app/src/main/java/ru/meefik/linuxdeploy/Logger.java new file mode 100644 index 00000000..624e722e --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/Logger.java @@ -0,0 +1,170 @@ +package ru.meefik.linuxdeploy; + +import android.content.Context; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.Closeable; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +public class Logger { + + private static volatile List protocol = new ArrayList<>(); + private static char lastChar = '\n'; + private static String lastLine = ""; + + /** + * Generate timestamp + * + * @return timestamp + */ + private static String getTimeStamp() { + return "[" + new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH).format(new Date()) + "] "; + } + + /** + * Append the message to protocol and show + * + * @param c context + * @param msg message + */ + private static synchronized void appendMessage(Context c, final String msg) { + if (msg.length() == 0) return; + String out = msg; + boolean timestamp = PrefStore.isTimestamp(c); + int maxLines = PrefStore.getMaxLines(c); + int protocolSize = protocol.size(); + if (protocolSize > 0 && lastChar != '\n') { + protocol.remove(protocolSize - 1); + out = lastLine + out; + } + lastChar = out.charAt(out.length() - 1); + String[] lines = out.split("\\n"); + for (int i = 0, l = lines.length; i < l; i++) { + lastLine = lines[i]; + if (timestamp) protocol.add(getTimeStamp() + lastLine); + else protocol.add(lastLine); + if (protocolSize + i >= maxLines) { + protocol.remove(0); + } + } + // show protocol + show(); + // write log + if (PrefStore.isLogger(c)) write(c, msg); + } + + /** + * Clear protocol + * + * @param c context + * @return true if success + */ + public static boolean clear(Context c) { + protocol.clear(); + File logFile = new File(PrefStore.getLogFile(c)); + return logFile.delete(); + } + + /** + * Size of protocol + * + * @return size + */ + public static int size() { + return protocol.size(); + } + + /** + * Show log on main activity + */ + public static void show() { + MainActivity.showLog(get()); + } + + /** + * Get protocol + * + * @return protocol as text + */ + public static String get() { + return android.text.TextUtils.join("\n", protocol); + } + + /** + * Append message to protocol + * + * @param c context + * @param msg message + */ + public static void log(Context c, String msg) { + appendMessage(c, msg); + } + + /** + * Closeable helper + * + * @param c closable object + */ + private static void close(Closeable c) { + if (c != null) { + try { + c.close(); + } catch (IOException e) { + // e.printStackTrace(); + } + } + } + + /** + * Write to log file + * + * @param c context + * @param msg message + */ + public static void write(Context c, String msg) { + String logFile = PrefStore.getLogFile(c); + BufferedWriter writer = null; + try { + writer = new BufferedWriter(new FileWriter(logFile, true)); + writer.write(msg); + } catch (IOException e) { + // e.printStackTrace(); + } finally { + close(writer); + } + } + + /** + * Append stream messages to protocol + * + * @param c context + * @param stream stream + */ + public static void log(Context c, InputStream stream) { + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(stream)); + int n; + char[] buffer = new char[1024]; + while ((n = reader.read(buffer)) != -1) { + String msg = String.valueOf(buffer, 0, n); + appendMessage(c, msg); + } + } catch (IOException e) { + // e.printStackTrace(); + } finally { + close(reader); + } + } + +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/MainActivity.java b/app/src/main/java/ru/meefik/linuxdeploy/MainActivity.java new file mode 100644 index 00000000..1abeec7b --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/MainActivity.java @@ -0,0 +1,455 @@ +package ru.meefik.linuxdeploy; + +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.res.Configuration; +import android.net.wifi.WifiManager; +import android.net.wifi.WifiManager.WifiLock; +import android.os.Bundle; +import android.os.Handler; +import android.os.PowerManager; +import android.support.design.widget.NavigationView; +import android.support.v4.view.GravityCompat; +import android.support.v4.widget.DrawerLayout; +import android.support.v7.app.ActionBar; +import android.support.v7.app.ActionBarDrawerToggle; +import android.support.v7.app.AlertDialog; +import android.support.v7.app.AppCompatActivity; +import android.text.method.LinkMovementMethod; +import android.util.Log; +import android.util.TypedValue; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.WindowManager; +import android.widget.EditText; +import android.widget.ScrollView; +import android.widget.TextView; +import android.widget.Toast; + +public class MainActivity extends AppCompatActivity implements + NavigationView.OnNavigationItemSelectedListener { + + private static TextView output; + private static ScrollView scroll; + private static WifiLock wifiLock; + private static PowerManager.WakeLock wakeLock; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + PrefStore.setLocale(this); + setContentView(R.layout.activity_main); + + ActionBar actionBar = getSupportActionBar(); + actionBar.setDisplayHomeAsUpEnabled(true); + + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( + this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close); + drawer.setDrawerListener(toggle); + toggle.syncState(); + + NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); + navigationView.setNavigationItemSelectedListener(this); + + output = (TextView) findViewById(R.id.outputView); + scroll = (ScrollView) findViewById(R.id.scrollView); + + output.setMovementMethod(LinkMovementMethod.getInstance()); + + // WiFi lock init + WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); + wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, getPackageName()); + + // Wake lock + PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); + wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getPackageName()); + + if (EnvUtils.isLatestVersion(this)) { + // start telnetd + EnvUtils.execService(getApplicationContext(), "telnetd", "start"); + // start httpd + EnvUtils.execService(getApplicationContext(), "httpd", "start"); + } else { + // Update ENV + EnvUtils.execService(getApplicationContext(), "update", ""); + } + } + + @Override + public void setTheme(int resId) { + super.setTheme(PrefStore.getTheme(this)); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + PrefStore.setLocale(this); + int orientation = getResources().getConfiguration().orientation; + if (orientation == Configuration.ORIENTATION_LANDSCAPE) { + getMenuInflater().inflate(R.menu.activity_main_landscape, menu); + } else { + getMenuInflater().inflate(R.menu.activity_main_portrait, menu); + } + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_start: + containerStart(null); + break; + case R.id.menu_stop: + containerStop(null); + break; + case R.id.menu_properties: + containerProperties(null); + break; + case R.id.menu_install: + containerDeploy(); + break; + case R.id.menu_configure: + containerConfigure(); + break; + case R.id.menu_export: + containerExport(); + break; + case R.id.menu_status: + containerStatus(); + break; + case R.id.menu_clear: + clearLog(); + break; + case android.R.id.home: + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + if (drawer.isDrawerOpen(GravityCompat.START)) { + drawer.closeDrawer(GravityCompat.START); + } else { + drawer.openDrawer(GravityCompat.START); + } + break; + default: + return super.onOptionsItemSelected(item); + } + return false; + } + + @Override + public void onBackPressed() { + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + if (drawer.isDrawerOpen(GravityCompat.START)) { + drawer.closeDrawer(GravityCompat.START); + } else { + super.onBackPressed(); + } + } + + @SuppressWarnings("StatementWithEmptyBody") + @Override + public boolean onNavigationItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.nav_profiles: + Intent intent_profiles = new Intent(this, ProfilesActivity.class); + startActivity(intent_profiles); + break; + case R.id.nav_repository: + openRepository(); + break; + case R.id.nav_terminal: + openTerminal(); + break; + case R.id.nav_settings: + Intent intent_settings = new Intent(this, SettingsActivity.class); + startActivity(intent_settings); + break; + case R.id.nav_about: + Intent intent_about = new Intent(this, AboutActivity.class); + startActivity(intent_about); + break; + case R.id.nav_exit: + PrefStore.hideIcon(getApplicationContext()); + if (wifiLock.isHeld()) wifiLock.release(); + if (wakeLock.isHeld()) wakeLock.release(); + EnvUtils.execService(getApplicationContext(), "telnetd", "stop"); + EnvUtils.execService(getApplicationContext(), "httpd", "stop"); + finish(); + break; + } + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + drawer.closeDrawer(GravityCompat.START); + return true; + } + + @Override + public void onResume() { + super.onResume(); + + String profileName = PrefStore.getProfileName(getApplicationContext()); + String ipAddress = PrefStore.getLocalIpAddress(); + setTitle(profileName + " [ " + ipAddress + " ]"); + + // show icon + PrefStore.showIcon(getApplicationContext(), getIntent()); + + // Restore font size + output.setTextSize(TypedValue.COMPLEX_UNIT_SP, PrefStore.getFontSize(getApplicationContext())); + + // Restore log + if (Logger.size() == 0) output.setText(R.string.help_text); + else Logger.show(); + + // Screen lock + if (PrefStore.isScreenLock(this)) + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + else + getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + + // WiFi lock + if (PrefStore.isWifiLock(this)) { + if (!wifiLock.isHeld()) wifiLock.acquire(); + } + else { + if (wifiLock.isHeld()) wifiLock.release(); + } + + // Wake lock + if (PrefStore.isWakeLock(this)) { + if (!wakeLock.isHeld()) wakeLock.acquire(); + } + else { + if (wakeLock.isHeld()) wakeLock.release(); + } + } + + /** + * Show message in TextView, used from Logger + * + * @param log message + */ + public static void showLog(final String log) { + if (output == null || scroll == null) return; + // show log in TextView + output.post(new Runnable() { + @Override + public void run() { + output.setText(log); + // scroll TextView to bottom + scroll.post(new Runnable() { + @Override + public void run() { + scroll.fullScroll(View.FOCUS_DOWN); + scroll.clearFocus(); + } + }); + } + }); + } + + /** + * Clear logs + */ + private void clearLog() { + Logger.clear(getApplicationContext()); + output.setText(R.string.help_text); + } + + /** + * Start container action + * + * @param view + */ + public void containerStart(View view) { + new AlertDialog.Builder(this).setTitle(R.string.confirm_start_title) + .setMessage(R.string.confirm_start_message) + .setIcon(android.R.drawable.ic_dialog_alert) + .setCancelable(false) + .setPositiveButton(android.R.string.yes, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + // actions + Handler h = new Handler(); + if (PrefStore.isXserver(getApplicationContext()) + && PrefStore.isXsdl(getApplicationContext())) { + PackageManager pm = getPackageManager(); + Intent intent = pm.getLaunchIntentForPackage("x.org.server"); + if (intent != null) startActivity(intent); + h.postDelayed(new Runnable() { + public void run() { + EnvUtils.execService(getApplicationContext(), "start", "-m"); + } + }, PrefStore.getXsdlDelay(getApplicationContext())); + } else if (PrefStore.isFramebuffer(getApplicationContext())) { + EnvUtils.execService(getApplicationContext(), "start", "-m"); + h.postDelayed(new Runnable() { + public void run() { + Intent intent = new Intent(getApplicationContext(), + FullscreenActivity.class); + startActivity(intent); + } + }, 1500); + } else { + EnvUtils.execService(getApplicationContext(), "start", "-m"); + } + } + }).setNegativeButton(android.R.string.no, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, + int id) { + dialog.cancel(); + } + }).show(); + } + + /** + * Stop container action + * + * @param view + */ + public void containerStop(View view) { + new AlertDialog.Builder(this).setTitle(R.string.confirm_stop_title) + .setMessage(R.string.confirm_stop_message) + .setIcon(android.R.drawable.ic_dialog_alert) + .setCancelable(false) + .setPositiveButton(android.R.string.yes, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + EnvUtils.execService(getApplicationContext(), "stop", "-u"); + } + }).setNegativeButton(android.R.string.no, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }).show(); + } + + /** + * Container properties action + * + * @param view + */ + public void containerProperties(View view) { + Intent intent = new Intent(this, PropertiesActivity.class); + intent.putExtra("restore", true); + startActivity(intent); + } + + /** + * Container deploy action + */ + private void containerDeploy() { + new AlertDialog.Builder(this) + .setTitle(R.string.title_install_dialog) + .setMessage(R.string.message_install_dialog) + .setCancelable(false) + .setPositiveButton(android.R.string.yes, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + EnvUtils.execService(getApplicationContext(), "deploy", null); + } + }) + .setNegativeButton(android.R.string.no, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }).show(); + } + + /** + * Container configure action + */ + private void containerConfigure() { + new AlertDialog.Builder(this) + .setTitle(R.string.title_configure_dialog) + .setMessage(R.string.message_configure_dialog) + .setCancelable(false) + .setPositiveButton(android.R.string.yes, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + EnvUtils.execService(getApplicationContext(), "deploy", "-n bootstrap"); + } + }) + .setNegativeButton(android.R.string.no, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }).show(); + } + + /** + * Container export action + */ + private void containerExport() { + final EditText input = new EditText(this); + final String rootfsArchive = getString(R.string.rootfs_archive); + input.setText(rootfsArchive); + new AlertDialog.Builder(this) + .setTitle(R.string.title_export_dialog) + .setCancelable(false) + .setView(input, 16, 32, 16, 0) + .setPositiveButton(android.R.string.yes, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + EnvUtils.execService(getApplicationContext(), "export", input.getText().toString()); + } + }) + .setNegativeButton(android.R.string.no, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }).show(); + } + + /** + * Container status action + */ + private void containerStatus() { + EnvUtils.execService(getApplicationContext(), "status", null); + } + + /** + * Open repository action + */ + private void openRepository() { +// PackageManager manager = getPackageManager(); +// if (manager.checkSignatures(getPackageName(), "ru.meefik.linuxdeploy.key") +// == PackageManager.SIGNATURE_MATCH) { +// //full version +// } + Intent intent = new Intent(this, RepositoryActivity.class); + startActivity(intent); + } + + /** + * Open terminal action + */ + private void openTerminal() { + try { + Intent intent_terminal = new Intent("jackpal.androidterm.RUN_SCRIPT"); + intent_terminal.addCategory(Intent.CATEGORY_DEFAULT); + intent_terminal.putExtra("jackpal.androidterm.iInitialCommand", + PrefStore.getTerminalCmd(getApplicationContext())); + startActivity(intent_terminal); + } catch(Exception e) { + Toast.makeText(getApplicationContext(), + R.string.toast_terminal_error, Toast.LENGTH_SHORT).show(); + } + } + +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/MountsActivity.java b/app/src/main/java/ru/meefik/linuxdeploy/MountsActivity.java new file mode 100644 index 00000000..0de7d4ff --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/MountsActivity.java @@ -0,0 +1,200 @@ +package ru.meefik.linuxdeploy; + +import android.content.Context; +import android.content.DialogInterface; +import android.os.Bundle; +import android.support.v7.app.AlertDialog; +import android.support.v7.app.AppCompatActivity; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.EditText; +import android.widget.ListView; +import android.widget.TextView; + +import java.util.ArrayList; +import java.util.List; + +public class MountsActivity extends AppCompatActivity { + + private List listItems = new ArrayList<>(); + private ArrayAdapter adapter; + + private void addDialog() { + final EditText input = new EditText(this); + new AlertDialog.Builder(this) + .setTitle(R.string.new_mount_title) + .setView(input, 16, 32, 16, 0) + .setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, + int whichButton) { + String text = input.getText().toString() + .replaceAll(" ", "_"); + if (text.length() > 0) { + listItems.add(text); + adapter.notifyDataSetChanged(); + } + } + }).setNegativeButton(android.R.string.cancel, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.cancel(); + } + }).show(); + } + + private void editDialog(final int position) { + final EditText input = new EditText(this); + if (position >= 0 && position < listItems.size()) { + input.setText(listItems.get(position)); + input.setSelection(input.getText().length()); + new AlertDialog.Builder(this) + .setTitle(R.string.edit_mount_title) + .setView(input, 16, 32, 16, 0) + .setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, + int whichButton) { + String text = input.getText() + .toString() + .replaceAll(" ", "_"); + if (text.length() > 0) { + listItems.set(position, text); + adapter.notifyDataSetChanged(); + } + } + }).setNegativeButton(android.R.string.cancel, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.cancel(); + } + }).show(); + } + } + + private void deleteDialog(final int position) { + if (position >= 0 && position < listItems.size()) { + new AlertDialog.Builder(this) + .setTitle(R.string.confirm_mount_discard_title) + .setMessage(R.string.confirm_mount_discard_message) + .setIcon(android.R.drawable.ic_dialog_alert) + .setCancelable(false) + .setPositiveButton(android.R.string.yes, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, + int whichButton) { + listItems.remove(position); + adapter.notifyDataSetChanged(); + } + }).setNegativeButton(android.R.string.no, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.cancel(); + } + }).show(); + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + PrefStore.setLocale(this); + setContentView(R.layout.activity_mounts); + + // ListView Adapter + ListView listView = (ListView) findViewById(R.id.mountsView); + adapter = new ArrayAdapter(this, R.layout.mounts_row, listItems) { + @Override + public View getView(final int position, View view, final ViewGroup parent) { + if (view == null) { + LayoutInflater inflater = (LayoutInflater) getApplicationContext(). + getSystemService(Context.LAYOUT_INFLATER_SERVICE); + view = inflater.inflate(R.layout.mounts_row, null); + } + String item = getItem(position); + + ((TextView) view.findViewById(R.id.mount_point)).setText(item); + + view.findViewById(R.id.mount_point).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ListView) parent).performItemClick(v, position, 0); // Let the event be handled in onItemClick() + } + }); + + view.findViewById(R.id.delete_mount).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ListView) parent).performItemClick(v, position, 0); // Let the event be handled in onItemClick() + } + }); + + return view; + } + }; + listView.setAdapter(adapter); + + // Click listener + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + public void onItemClick(AdapterView parent, View view, int position, long id) { + long viewId = view.getId(); + if (viewId == R.id.delete_mount) deleteDialog(position); + else editDialog(position); + } + }); + } + + @Override + public void setTheme(int resId) { + super.setTheme(PrefStore.getTheme(this)); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + PrefStore.setLocale(this); + getMenuInflater().inflate(R.menu.activity_mounts, menu); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_add: + addDialog(); + break; + } + return false; + } + + @Override + public void onResume() { + super.onResume(); + + String titleMsg = getString(R.string.title_activity_mounts) + ": " + + PrefStore.getProfileName(getApplicationContext()); + setTitle(titleMsg); + + listItems.addAll(PrefStore.getMountsList(getApplicationContext())); + } + + @Override + public void onPause() { + super.onPause(); + + PrefStore.setMountsList(getApplicationContext(), listItems); + } +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/NetworkReceiver.java b/app/src/main/java/ru/meefik/linuxdeploy/NetworkReceiver.java new file mode 100644 index 00000000..b4093f40 --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/NetworkReceiver.java @@ -0,0 +1,26 @@ +package ru.meefik.linuxdeploy; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; + +public class NetworkReceiver extends BroadcastReceiver { + + @Override + public void onReceive(final Context context, Intent intent) { + if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { + ConnectivityManager cm = + (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); + + NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); + boolean isConnected = false; + if (activeNetwork != null) isConnected = activeNetwork.isConnected(); + if (isConnected) { + EnvUtils.execService(context, "start", "core/net"); + } + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/ru/meefik/linuxdeploy/ParamUtils.java b/app/src/main/java/ru/meefik/linuxdeploy/ParamUtils.java new file mode 100644 index 00000000..3ced6831 --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/ParamUtils.java @@ -0,0 +1,183 @@ +package ru.meefik.linuxdeploy; + +import android.content.Context; +import android.content.SharedPreferences; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.Closeable; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +public class ParamUtils { + + private String name; + private List params; + + public ParamUtils(String name, String[] params) { + this.name = name; + this.params = Arrays.asList(params); + } + + /** + * Closeable helper + * + * @param c closable object + */ + private static void close(Closeable c) { + if (c != null) { + try { + c.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public static Map readConf(File confFile) { + TreeMap map = new TreeMap<>(); + BufferedReader br = null; + String line; + try { + br = new BufferedReader(new FileReader(confFile)); + while ((line = br.readLine()) != null) { + if (!line.startsWith("#") && !line.isEmpty()) { + String[] pair = line.split("="); + String key = pair[0]; + String value = pair[1]; + map.put(key, value.replaceAll("\"","")); + } + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + close(br); + } + return map; + } + + public static boolean writeConf(Map map, File confFile) { + Boolean result = false; + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter(confFile)); + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + bw.write(key + "=\"" + value+"\""); + bw.newLine(); + } + result = true; + } catch (Exception e) { + e.printStackTrace(); + } finally { + close(bw); + } + return result; + } + + public String fixOutputParam(Context c, String key, String value) { + return value; + } + + public String get(Context c, String key) { + SharedPreferences pref = c.getSharedPreferences(this.name, Context.MODE_PRIVATE); + int resourceId = PrefStore.getResourceId(c, key, "string"); + Map source = pref.getAll(); + String defaultValue = ""; + if (resourceId > 0) defaultValue = c.getString(resourceId); + Object value = source.get(key); + if (value == null) value = defaultValue; + return fixOutputParam(c, key, value.toString()); + } + + public Map get(Context c) { + SharedPreferences pref = c.getSharedPreferences(this.name, Context.MODE_PRIVATE); + Map source = pref.getAll(); + Map target = new TreeMap<>(); + for (String key : this.params) { + int resourceId = PrefStore.getResourceId(c, key, "string"); + String defaultValue = ""; + if (resourceId > 0) defaultValue = c.getString(resourceId); + Object value = source.get(key); + if (value == null) value = defaultValue; + target.put(key.toUpperCase(), fixOutputParam(c, key, value.toString())); + } + for (Map.Entry entry : source.entrySet()) { + String key = entry.getKey(); + if (!key.matches("^[A-Z0-9_]+$")) continue; + if (!target.containsKey(key)) target.put(key, entry.getValue().toString()); + } + return target; + } + + public String fixInputParam(Context c, String key, String value) { + return value; + } + + public void set(Context c, String key, String value) { + SharedPreferences pref = c.getSharedPreferences(this.name, Context.MODE_PRIVATE); + SharedPreferences.Editor prefEditor = pref.edit(); + if (value.equals("true") || value.equals("false")) { + prefEditor.putBoolean(key, fixInputParam(c, key, value).equals("true")); + } else { + prefEditor.putString(key, fixInputParam(c, key, value)); + } + prefEditor.apply(); + } + + public void set(Context c, Map source) { + SharedPreferences pref = c.getSharedPreferences(this.name, Context.MODE_PRIVATE); + SharedPreferences.Editor prefEditor = pref.edit(); + for (Map.Entry entry : source.entrySet()) { + String key = entry.getKey(); + if (!key.matches("^[A-Z0-9_]+$")) continue; + String value = entry.getValue(); + String lowerKey = key.toLowerCase(); + if (params.contains(lowerKey)) { + if (value.equals("true") || value.equals("false")) { + prefEditor.putBoolean(lowerKey, fixInputParam(c, lowerKey, value).equals("true")); + } else { + prefEditor.putString(lowerKey, fixInputParam(c, lowerKey, value)); + } + } else { + prefEditor.putString(key, value); + } + } + prefEditor.apply(); + } + + public boolean dump(Context c, File f) { + return writeConf(get(c), f); + } + + public boolean restore(Context c, File f) { + clear(c, false); + if (f.exists()) { + set(c, readConf(f)); + return true; + } + return false; + } + + public void clear(Context c, boolean all) { + SharedPreferences pref = c.getSharedPreferences(this.name, Context.MODE_PRIVATE); + SharedPreferences.Editor prefEditor = pref.edit(); + if (all) prefEditor.clear(); + else { + for (Map.Entry entry : pref.getAll().entrySet()) { + String key = entry.getKey(); + if (!key.matches("^[A-Z0-9_]+$")) continue; + prefEditor.remove(key); + } + } + prefEditor.apply(); + } + +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/PrefStore.java b/app/src/main/java/ru/meefik/linuxdeploy/PrefStore.java new file mode 100644 index 00000000..f4d773b9 --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/PrefStore.java @@ -0,0 +1,823 @@ +package ru.meefik.linuxdeploy; + +import android.annotation.SuppressLint; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.content.res.Configuration; +import android.graphics.Point; +import android.os.Build; +import android.support.v4.app.NotificationCompat; +import android.support.v4.app.TaskStackBuilder; +import android.text.TextUtils; +import android.view.Display; +import android.view.WindowManager; + +import java.io.File; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; +import java.util.Locale; + +public class PrefStore { + + public final static SettingsStore SETTINGS = new SettingsStore(); + public final static PropertiesStore PROPERTIES = new PropertiesStore(); + final static int NOTIFY_ID = 1; + + /** + * Get application version + * + * @param c context + * @return version, format versionName-versionCode + */ + public static String getVersion(Context c) { + String version = ""; + try { + PackageInfo pi = c.getPackageManager().getPackageInfo(c.getPackageName(), 0); + version = pi.versionName + "-" + pi.versionCode; + } catch (PackageManager.NameNotFoundException e) { + e.printStackTrace(); + } + return version; + } + + /** + * Get data directory + * + * @param c context + * @return path, e.g. /data/data/package + */ + public static String getDataDir(Context c) { + return c.getApplicationInfo().dataDir; + } + + /** + * Get environment directory + * + * @param c context + * @return path, e.g. /data/data/package/files/env + */ + public static String getEnvDir(Context c) { + String envDir = SETTINGS.get(c, "env_dir"); + if (envDir.isEmpty()) envDir = getDataDir(c) + "/env"; + return envDir; + } + + /** + * Get config directory + * + * @param c context + * @return path, e.g. ${ENV_DIR}/config + */ + public static String getConfigDir(Context c) { + return getEnvDir(c) + "/config"; + } + + /** + * Get bin directory + * + * @param c context + * @return path, e.g. /data/data/package/bin + */ + public static String getBinDir(Context c) { + return getDataDir(c) + "/bin"; + } + + /** + * Get tmp directory + * + * @param c context + * @return path, e.g. /data/data/package/tmp + */ + public static String getTmpDir(Context c) { + return getDataDir(c) + "/tmp"; + } + + /** + * Get web directory + * + * @param c context + * @return path, e.g. /data/data/package/web + */ + public static String getWebDir(Context c) { + return getDataDir(c) + "/web"; + } + + /** + * Get httpd.conf file + * + * @param c context + * @return path of httpd.conf + */ + public static File getHttpConfFile(Context c) { + return new File(getWebDir(c) + "/httpd.conf"); + } + + /** + * Dump settings to configuration file + * + * @param c context + * @return true if success + */ + public static boolean dumpSettings(Context c) { + return SETTINGS.dump(c, getSettingsConfFile(c)); + } + + /** + * Restore settings from configuration file + * + * @param c context + * @return true if success + */ + public static boolean restoreSettings(Context c) { + return SETTINGS.restore(c, getSettingsConfFile(c)); + } + + /** + * Dump profile to configuration file + * + * @param c context + * @return true if success + */ + public static boolean dumpProperties(Context c) { + return PROPERTIES.dump(c, getPropertiesConfFile(c)); + } + + /** + * Restore profile from configuration file + * + * @param c context + * @return true if success + */ + public static boolean restoreProperties(Context c) { + PROPERTIES.clear(c, true); + return PROPERTIES.restore(c, getPropertiesConfFile(c)); + } + + /** + * Get shared name for settings + * + * @return name + */ + public static String getSettingsSharedName() { + return SETTINGS.name; + } + + /** + * Get shared name for properties + * + * @return name + */ + public static String getPropertiesSharedName() { + return PROPERTIES.name; + } + + /** + * Check root is required for current profile + * + * @return true if required + */ + public static boolean isRootRequired(Context c) { + return PROPERTIES.get(c, "method").equals("chroot"); + } + + /** + * Get language code + * + * @param c context + * @return language code, e.g. "en" + */ + public static String getLanguage(Context c) { + String language = SETTINGS.get(c, "language"); + if (language.length() == 0) { + String countryCode = Locale.getDefault().getLanguage(); + switch (countryCode) { + case "ru": + language = countryCode; + break; + default: + language = "en"; + } + SETTINGS.set(c, "language", language); + } + return language; + } + + /** + * Get application theme resource id + * + * @param c context + * @return resource id + */ + public static int getTheme(Context c) { + String theme = SETTINGS.get(c, "theme"); + int themeId = R.style.DarkTheme; + switch (theme) { + case "dark": + themeId = R.style.DarkTheme; + break; + case "light": + themeId = R.style.LightTheme; + break; + } + return themeId; + } + + /** + * Get font size + * + * @param c context + * @return font size + */ + public static int getFontSize(Context c) { + Integer fontSizeInt; + String fontSize = SETTINGS.get(c, "fontsize"); + try { + fontSizeInt = Integer.parseInt(fontSize); + } catch (Exception e) { + fontSize = c.getString(R.string.fontsize); + fontSizeInt = Integer.parseInt(fontSize); + SETTINGS.set(c, "fontsize", fontSize); + } + return fontSizeInt; + } + + /** + * Get maximum limit to scroll + * + * @param c context + * @return number of lines + */ + public static int getMaxLines(Context c) { + Integer maxLinesInt; + String maxLines = SETTINGS.get(c, "maxlines"); + try { + maxLinesInt = Integer.parseInt(maxLines); + } catch (Exception e) { + maxLines = c.getString(R.string.maxlines); + maxLinesInt = Integer.parseInt(maxLines); + SETTINGS.set(c, "maxlines", maxLines); + } + return maxLinesInt; + } + + /** + * Timestamp is enabled + * + * @param c context + * @return true if enabled + */ + public static Boolean isTimestamp(Context c) { + return SETTINGS.get(c, "timestamp").equals("true"); + } + + /** + * Debug mode is enabled + * + * @param c context + * @return true if enabled + */ + public static Boolean isDebugMode(Context c) { + return SETTINGS.get(c, "debug_mode").equals("true"); + } + + /** + * Trace mode is enabled + * + * @param c context + * @return true if enabled + */ + public static Boolean isTraceMode(Context c) { + return SETTINGS.get(c, "trace_mode").equals("true"); + } + + /** + * Logging is enabled + * + * @param c context + * @return true if enabled + */ + public static Boolean isLogger(Context c) { + return SETTINGS.get(c, "logger").equals("true"); + } + + /** + * Get path of log file + * + * @param c context + * @return path + */ + public static String getLogFile(Context c) { + String logfile = SETTINGS.get(c, "logfile"); + if (!logfile.contains("/")) logfile = getEnvDir(c) + "/" + logfile; + return logfile; + } + + /** + * Screen lock is enabled + * + * @param c context + * @return true if enabled + */ + public static Boolean isScreenLock(Context c) { + return SETTINGS.get(c, "screenlock").equals("true"); + } + + /** + * Wifi lock is enabled + * + * @param c context + * @return true if enabled + */ + public static Boolean isWifiLock(Context c) { + return SETTINGS.get(c, "wifilock").equals("true"); + } + + /** + * Wake lock is enabled + * + * @param c context + * @return true if enabled + */ + public static Boolean isWakeLock(Context c) { + return SETTINGS.get(c, "wakelock").equals("true"); + } + + /** + * Application autostart is enabled + * + * @param c context + * @return true if enabled + */ + public static Boolean isAutostart(Context c) { + return SETTINGS.get(c, "autostart").equals("true"); + } + + /** + * Track changes of the network status is enabled + * + * @param c context + * @return true if enabled + */ + public static Boolean isTrackNetwork(Context c) { + return SETTINGS.get(c, "nettrack").equals("true"); + } + + /** + * Show icon is enabled + * + * @param c context + * @return true if enabled + */ + public static Boolean isShowIcon(Context c) { + return SETTINGS.get(c, "appicon").equals("true"); + } + + /** + * Get terminal command + * + * @param c context + * @return command + */ + public static String getTerminalCmd(Context c) { + return SETTINGS.get(c, "terminalcmd"); + } + + /** + * Get PATH variable + * + * @param c context + * @return path, e.g. /data/data/package/files/bin + */ + public static String getPath(Context c) { + String binDir = getDataDir(c) + "/bin"; + String path = SETTINGS.get(c, "path"); + if (path.isEmpty()) path = binDir; + else path = path + ":" + binDir; + return path; + } + + /** + * Which path to SH + * + * @param c context + * @return path, e.g. /system/bin/sh + */ + public static String getShell(Context c) { + String[] path = getPath(c).split(":"); + String shell = "/system/bin/sh"; + for (String p : path) { + shell = p + "/sh"; + File f = new File(shell); + if (f.exists()) break; + } + return shell; + } + + /** + * Get repository URL + * + * @param c context + * @return url + */ + public static String getRepositoryUrl(Context c) { + return SETTINGS.get(c, "repository_url"); + } + + /** + * Set repository URL + * + * @param c context + */ + public static void setRepositoryUrl(Context c, String url) { + SETTINGS.set(c, "repository_url", url); + } + + /** + * CLI symlink is enabled + * + * @param c context + * @return true if enabled + */ + public static Boolean isCliSymlink(Context c) { + return SETTINGS.get(c, "is_cli").equals("true"); + } + + /** + * Telnet is enabled + * + * @param c context + * @return true if enabled + */ + public static Boolean isTelnet(Context c) { + return SETTINGS.get(c, "is_telnet").equals("true"); + } + + /** + * Get telnetd port + * + * @param c context + * @return port + */ + public static String getTelnetPort(Context c) { + return SETTINGS.get(c, "telnet_port"); + } + + /** + * Is telnetd localhost + * + * @param c context + * @return true if localhost + */ + public static boolean isTelnetLocalhost(Context c) { + return SETTINGS.get(c, "telnet_localhost").equals("true"); + } + + /** + * HTTP is enabled + * + * @param c context + * @return true if enabled + */ + public static Boolean isHttp(Context c) { + return SETTINGS.get(c, "is_http").equals("true"); + } + + /** + * Get http port + * + * @param c context + * @return port + */ + public static String getHttpPort(Context c) { + return SETTINGS.get(c, "http_port"); + } + + /** + * Get http authentication + * + * @param c context + * @return authentication string, e.g. /:user:password (for crypt password use httpd -m password) + */ + public static String getHttpConf(Context c) { + String auth = SETTINGS.get(c, "http_conf"); + if (auth.isEmpty()) auth = "/:android:" + generatePassword(); + return auth; + } + + /** + * X server is enabled + * + * @param c context + * @return true if enabled + */ + public static boolean isXserver(Context c) { + return PROPERTIES.get(c, "is_gui").equals("true") && + PROPERTIES.get(c, "graphics").equals("x11"); + } + + /** + * Framebuffer is enabled + * + * @param c context + * @return true if enabled + */ + public static boolean isFramebuffer(Context c) { + return PROPERTIES.get(c, "is_gui").equals("true") && + PROPERTIES.get(c, "graphics").equals("fb"); + } + + /** + * XServer XSDL is enabled + * + * @param c context + * @return true if enabled + */ + public static boolean isXsdl(Context c) { + return PROPERTIES.get(c, "x11_sdl").equals("true"); + } + + /** + * Get XServer XSDL opening delay + * + * @param c context + * @return delay in ms + */ + public static int getXsdlDelay(Context c) { + Integer deplayInt; + String delay = PROPERTIES.get(c, "x11_sdl_delay"); + try { + deplayInt = Integer.parseInt(delay); + } catch (Exception e) { + delay = c.getString(R.string.x11_sdl_delay); + deplayInt = Integer.parseInt(delay); + PROPERTIES.set(c, "x11_sdl_delay", delay); + } + return deplayInt * 1000; + } + + /** + * Get global configuration file path + * + * @param c context + * @return path of cli.conf + */ + public static File getSettingsConfFile(Context c) { + return new File(getEnvDir(c) + "/cli.conf"); + } + + /** + * Get profile configuration path + * + * @param c context + * @return path of profile + */ + public static File getPropertiesConfFile(Context c) { + return new File(getConfigDir(c) + "/" + getProfileName(c) + ".conf"); + } + + /** + * Get current profile + * + * @param c context + * @return profile + */ + public static String getProfileName(Context c) { + return SETTINGS.get(c, "profile"); + } + + /** + * Set current profile + * + * @param c context + */ + public static void changeProfile(Context c, String profile) { + SETTINGS.set(c, "profile", profile); + dumpSettings(c); + File confFile = getPropertiesConfFile(c); + if (!confFile.exists()) { + PROPERTIES.clear(c, true); + PROPERTIES.dump(c, confFile); + } + } + + /** + * Set application locale + * + * @param c context + */ + public static void setLocale(Context c) { + String language = getLanguage(c); + Locale locale = new Locale(language); + Locale.setDefault(locale); + Configuration config = new Configuration(); + config.locale = locale; + c.getResources().updateConfiguration(config, c.getResources().getDisplayMetrics()); + } + + + /** + * Load list of mount points + * + * @param c context + * @return list of mount points + */ + public static List getMountsList(Context c) { + String str = PROPERTIES.get(c, "mounts"); + List list = new ArrayList<>(); + if (!str.isEmpty()) Collections.addAll(list, str.split(" ")); + return list; + } + + /** + * Save list of mount points + * + * @param c context + * @param list list of mount points + */ + public static void setMountsList(Context c, List list) { + PROPERTIES.set(c, "mounts", TextUtils.join(" ", list)); + } + + /** + * Generate password + * + * @return plain password + */ + public static String generatePassword() { + return Long.toHexString(Double.doubleToLongBits(Math.random())).substring(8); + } + + /** + * Get hardware architecture + * + * @param arch unformated architecture + * @return intel, arm or mips + */ + public static String getArch(String arch) { + String march = "unknown"; + if (arch.length() > 0) { + char a = arch.toLowerCase().charAt(0); + switch (a) { + case 'a': + if (arch.equals("amd64")) + march = "intel"; + else march = "arm"; + break; + case 'm': + march = "mips"; + break; + case 'i': + case 'x': + march = "intel"; + break; + } + } + return march; + } + + /** + * Get current hardware architecture + * + * @return intel, arm or mips + */ + public static String getArch() { + return getArch(System.getProperty("os.arch")); + } + + /** + * Get width of device screen + * + * @param c context + * @return screen width + */ + @SuppressLint("NewApi") + public static Integer getScreenWidth(Context c) { + int width = 0; + WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); + Display display = wm.getDefaultDisplay(); + if (Build.VERSION.SDK_INT > 12) { + Point size = new Point(); + display.getSize(size); + width = size.x; + } else { + width = display.getWidth(); // deprecated + } + return width; + } + + /** + * Get height of device screen + * + * @param c context + * @return screen height + */ + @SuppressLint("NewApi") + public static Integer getScreenHeight(Context c) { + int height = 0; + WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); + Display display = wm.getDefaultDisplay(); + if (Build.VERSION.SDK_INT > 12) { + Point size = new Point(); + display.getSize(size); + height = size.y; + } else { + height = display.getHeight(); // deprecated + } + return height; + } + + /** + * Get local IP address + * + * @return ip address + */ + public static String getLocalIpAddress() { + String ip = "127.0.0.1"; + try { + for (Enumeration en = NetworkInterface + .getNetworkInterfaces(); en.hasMoreElements(); ) { + NetworkInterface intf = en.nextElement(); + for (Enumeration enumIpAddr = intf + .getInetAddresses(); enumIpAddr.hasMoreElements(); ) { + InetAddress inetAddress = enumIpAddr.nextElement(); + if (!inetAddress.isLoopbackAddress() + && !inetAddress.isLinkLocalAddress()) { + ip = inetAddress.getHostAddress(); + } + } + } + } catch (SocketException e) { + e.printStackTrace(); + } + return ip; + } + + /** + * Get Android resource id + * + * @param c context + * @param resourceName variable name + * @param resourceType resource type + * @return resource id + */ + public static int getResourceId(Context c, String resourceName, String resourceType) { + try { + return c.getResources().getIdentifier(resourceName, resourceType, c.getPackageName()); + } catch (Exception e) { + return -1; + } + } + + /** + * Show icon on notification bar + * + * @param context context + * @param intent intent + */ + public static void showIcon(Context context, Intent intent) { + NotificationManager mNotificationManager = (NotificationManager) context + .getSystemService(Context.NOTIFICATION_SERVICE); + if (isShowIcon(context)) { + setLocale(context); + NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) + .setSmallIcon(R.mipmap.ic_launcher) + .setContentTitle(context.getString(R.string.app_name)) + .setContentText(context.getString(R.string.notification_current_profile) + + ": " + getProfileName(context)); + Intent resultIntent = intent; + if (resultIntent == null) resultIntent = new Intent(context, MainActivity.class); + TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); + stackBuilder.addParentStack(MainActivity.class); + stackBuilder.addNextIntent(resultIntent); + PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( + 0, PendingIntent.FLAG_UPDATE_CURRENT); + mBuilder.setContentIntent(resultPendingIntent); + mBuilder.setOngoing(true); + mBuilder.setWhen(0); + mNotificationManager.notify(NOTIFY_ID, mBuilder.build()); + } else { + mNotificationManager.cancel(NOTIFY_ID); + } + } + + /** + * Hide icon from notification bar + * + * @param context context + */ + public static void hideIcon(Context context) { + NotificationManager mNotificationManager = (NotificationManager) context + .getSystemService(Context.NOTIFICATION_SERVICE); + mNotificationManager.cancel(NOTIFY_ID); + } + +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/ProfilesActivity.java b/app/src/main/java/ru/meefik/linuxdeploy/ProfilesActivity.java new file mode 100644 index 00000000..0be4dde5 --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/ProfilesActivity.java @@ -0,0 +1,266 @@ +package ru.meefik.linuxdeploy; + +import android.content.Context; +import android.content.DialogInterface; +import android.os.Bundle; +import android.support.v7.app.AlertDialog; +import android.support.v7.app.AppCompatActivity; +import android.view.GestureDetector; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnTouchListener; +import android.widget.ArrayAdapter; +import android.widget.EditText; +import android.widget.ListView; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class ProfilesActivity extends AppCompatActivity implements OnTouchListener { + + private ListView listView; + private List listItems = new ArrayList<>(); + private ArrayAdapter adapter; + private GestureDetector gd; + + /** + * Get position by key + * + * @param key + * @return position + */ + private int getPosition(String key) { + int pos = 0; + for (String item : listItems) { + if (item.equals(key)) return pos; + pos++; + } + return -1; + } + + /** + * Rename conf file associated with the profile + * + * @param c context + * @param oldName old profile name + * @param newName new profile name + * @return true if success + */ + public static boolean renameConf(Context c, String oldName, String newName) { + File oldFile = new File(PrefStore.getEnvDir(c) + "/config/" + oldName + ".conf"); + File newFile = new File(PrefStore.getEnvDir(c) + "/config/" + newName + ".conf"); + return oldFile.renameTo(newFile); + } + + /** + * Remove conf file associated with the profile + * + * @param c context + * @param name profile name + * @return true if success + */ + public static boolean removeConf(Context c, String name) { + File confFile = new File(PrefStore.getEnvDir(c) + "/config/" + name + ".conf"); + return confFile.exists() && confFile.delete(); + } + + /** + * Get list of profiles + * + * @param c context + * @return list of profiles + */ + public static List getProfiles(Context c) { + List profiles = new ArrayList<>(); + File confDir = new File(PrefStore.getEnvDir(c) + "/config"); + File[] listOfFiles = confDir.listFiles(); + if (listOfFiles != null) { + for (File listOfFile : listOfFiles) { + if (listOfFile.isFile()) { + String filename = listOfFile.getName(); + int index = filename.lastIndexOf('.'); + if (index != -1) filename = filename.substring(0, index); + profiles.add(filename); + } + } + } + return profiles; + } + + private void addDialog() { + final EditText input = new EditText(this); + new AlertDialog.Builder(this) + .setTitle(R.string.new_profile_title) + .setView(input, 16, 32, 16, 0) + .setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int whichButton) { + String text = input.getText().toString(); + if (text.length() > 0) { + listItems.add(text.replaceAll("[^A-Za-z0-9_\\-]", "_")); + adapter.notifyDataSetChanged(); + } + } + }) + .setNegativeButton(android.R.string.cancel, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int whichButton) { + dialog.cancel(); + } + }).show(); + } + + private void editDialog() { + final EditText input = new EditText(this); + final int pos = listView.getCheckedItemPosition(); + if (pos >= 0 && pos < listItems.size()) { + final String profileOld = listItems.get(pos); + input.setText(profileOld); + input.setSelection(input.getText().length()); + new AlertDialog.Builder(this) + .setTitle(R.string.edit_profile_title) + .setView(input, 16, 32, 16, 0) + .setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int whichButton) { + String text = input.getText().toString(); + if (text.length() > 0) { + String profileNew = text.replaceAll("[^A-Za-z0-9_\\-]", "_"); + if (!profileOld.equals(profileNew)) { + renameConf(getApplicationContext(), profileOld, profileNew); + listItems.set(pos, profileNew); + adapter.notifyDataSetChanged(); + } + } + } + }) + .setNegativeButton(android.R.string.cancel, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int whichButton) { + dialog.cancel(); + } + }).show(); + } + } + + private void deleteDialog() { + final int pos = listView.getCheckedItemPosition(); + if (pos >= 0 && pos < listItems.size()) { + new AlertDialog.Builder(this) + .setTitle(R.string.confirm_profile_discard_title) + .setMessage(R.string.confirm_profile_discard_message) + .setIcon(android.R.drawable.ic_dialog_alert) + .setCancelable(false) + .setPositiveButton(android.R.string.yes, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int whichButton) { + String key = listItems.get(pos); + listItems.remove(pos); + int last = listItems.size() - 1; + if (last < 0) listItems.add(getString(R.string.profile)); + if (last >= 0 && pos > last) + listView.setItemChecked(last, true); + adapter.notifyDataSetChanged(); + removeConf(getApplicationContext(), key); + } + }) + .setNegativeButton(android.R.string.no, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int whichButton) { + dialog.cancel(); + } + }).show(); + } + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + PrefStore.setLocale(this); + setContentView(R.layout.activity_profiles); + + // ListView Adapter + listView = (ListView) findViewById(R.id.profilesView); + adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice, listItems); + listView.setAdapter(adapter); + + // Initialize the Gesture Detector + listView.setOnTouchListener(this); + gd = new GestureDetector(this, + new GestureDetector.SimpleOnGestureListener() { + @Override + public boolean onDoubleTap(MotionEvent e) { + finish(); + return false; + } + }); + } + + @Override + public void setTheme(int resId) { + super.setTheme(PrefStore.getTheme(this)); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + PrefStore.setLocale(this); + getMenuInflater().inflate(R.menu.activity_profiles, menu); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_add: + addDialog(); + break; + case R.id.menu_edit: + editDialog(); + break; + case R.id.menu_delete: + deleteDialog(); + break; + } + return false; + } + + @Override + public void onPause() { + super.onPause(); + int pos = listView.getCheckedItemPosition(); + if (pos >= 0 && pos < listItems.size()) { + String profile = listItems.get(pos); + PrefStore.changeProfile(getApplicationContext(), profile); + } + } + + @Override + public void onResume() { + super.onResume(); + setTitle(R.string.title_activity_profiles); + listItems.clear(); + listItems.addAll(getProfiles(getApplicationContext())); + Collections.sort(listItems); + String profile = PrefStore.getProfileName(getApplicationContext()); + if (listItems.size() == 0) listItems.add(profile); + adapter.notifyDataSetChanged(); + listView.setItemChecked(getPosition(profile), true); + } + + @Override + public boolean onTouch(View v, MotionEvent event) { + gd.onTouchEvent(event); + return false; + } + +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/PropertiesActivity.java b/app/src/main/java/ru/meefik/linuxdeploy/PropertiesActivity.java new file mode 100644 index 00000000..8e78a0ce --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/PropertiesActivity.java @@ -0,0 +1,329 @@ +package ru.meefik.linuxdeploy; + +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.SharedPreferences.OnSharedPreferenceChangeListener; +import android.os.Bundle; +import android.preference.EditTextPreference; +import android.preference.ListPreference; +import android.preference.Preference; +import android.preference.PreferenceGroup; +import android.preference.PreferenceManager; +import android.preference.PreferenceScreen; +import android.util.Log; +import android.view.MenuItem; + +public class PropertiesActivity extends AppCompatPreferenceActivity implements + Preference.OnPreferenceClickListener, OnSharedPreferenceChangeListener { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + PrefStore.setLocale(this); + + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + PreferenceManager prefMgr = getPreferenceManager(); + prefMgr.setSharedPreferencesName(PrefStore.getPropertiesSharedName()); + + // Restore from conf file if open from main activity + if (getIntent().getBooleanExtra("restore", false)) { + PrefStore.restoreProperties(getApplicationContext()); + } + + Bundle b = getIntent().getExtras(); + int pref = 0; + if (b != null) + pref = b.getInt("pref"); + switch (pref) { + case 1: + addPreferencesFromResource(R.xml.properties_ssh); + break; + case 2: + addPreferencesFromResource(R.xml.properties_vnc); + break; + case 3: + addPreferencesFromResource(R.xml.properties_x11); + break; + case 4: + addPreferencesFromResource(R.xml.properties_fb); + break; + case 5: + addPreferencesFromResource(R.xml.properties_run_parts); + break; + case 6: + addPreferencesFromResource(R.xml.properties_sysv); + break; + default: + addPreferencesFromResource(R.xml.properties); + } + + initSummaries(getPreferenceScreen()); + } + + @Override + public void setTheme(int resId) { + super.setTheme(PrefStore.getTheme(this)); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + finish(); + break; + } + return false; + } + + @Override + public void onResume() { + super.onResume(); + + String titleMsg = getString(R.string.title_activity_properties) + + ": " + PrefStore.getProfileName(getApplicationContext()); + setTitle(titleMsg); + + getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); + } + + @Override + public void onPause() { + super.onPause(); + + getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); + + // update configuration file + PrefStore.dumpProperties(getApplicationContext()); + } + + @Override + public boolean onPreferenceClick(Preference preference) { + if (preference.getKey().equals("ssh_properties")) { + Intent intent = new Intent(getApplicationContext(), PropertiesActivity.class); + Bundle b = new Bundle(); + b.putInt("pref", 1); + intent.putExtras(b); + startActivity(intent); + } + if (preference.getKey().equals("gui_properties")) { + ListPreference graphics = (ListPreference) findPreference("graphics"); + Intent intent = new Intent(getApplicationContext(), PropertiesActivity.class); + Bundle b = new Bundle(); + if (graphics.getValue().equals("vnc")) { + b.putInt("pref", 2); + } + if (graphics.getValue().equals("x11")) { + b.putInt("pref", 3); + } + if (graphics.getValue().equals("fb")) { + b.putInt("pref", 4); + } + intent.putExtras(b); + startActivity(intent); + } + if (preference.getKey().equals("init_properties")) { + ListPreference init = (ListPreference) findPreference("init"); + Intent intent = new Intent(getApplicationContext(), PropertiesActivity.class); + Bundle b = new Bundle(); + if (init.getValue().equals("run-parts")) { + b.putInt("pref", 5); + } + if (init.getValue().equals("sysv")) { + b.putInt("pref", 6); + } + intent.putExtras(b); + startActivity(intent); + } + if (preference.getKey().equals("mounts_editor")) { + Intent intent = new Intent(getApplicationContext(), MountsActivity.class); + startActivity(intent); + } + return true; + } + + @Override + public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { + Preference pref = findPreference(key); + setSummary(pref, true); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + + if (requestCode == 1) { + + if(resultCode == RESULT_OK){ + Log.d("LD", "OK"); + } + if (resultCode == RESULT_CANCELED) { + //Do nothing? + } + } + } + + private void initSummaries(PreferenceGroup pg) { + for (int i = 0; i < pg.getPreferenceCount(); ++i) { + Preference p = pg.getPreference(i); + if (p instanceof PreferenceGroup) + initSummaries((PreferenceGroup) p); + else + setSummary(p, false); + if (p instanceof PreferenceScreen) + p.setOnPreferenceClickListener(this); + } + } + + private void setSummary(Preference pref, boolean init) { + if (pref instanceof EditTextPreference) { + EditTextPreference editPref = (EditTextPreference) pref; + pref.setSummary(editPref.getText()); + + if (editPref.getKey().equals("dns") + && editPref.getText().isEmpty()) { + pref.setSummary(getString(R.string.summary_dns_preference)); + } + if (editPref.getKey().equals("disk_size") + && editPref.getText().equals("0")) { + pref.setSummary(getString(R.string.summary_disk_size_preference)); + } + if (editPref.getKey().equals("user_password") && + editPref.getText().isEmpty()) { + editPref.setText(PrefStore.generatePassword()); + pref.setSummary(editPref.getText()); + } + } + + if (pref instanceof ListPreference) { + ListPreference listPref = (ListPreference) pref; + pref.setSummary(listPref.getEntry()); + + if (listPref.getKey().equals("distrib")) { + ListPreference suite = (ListPreference) findPreference("suite"); + ListPreference architecture = (ListPreference) findPreference("arch"); + EditTextPreference sourcepath = (EditTextPreference) findPreference("source_path"); + + String distributionStr = listPref.getValue(); + + // suite + int suiteValuesId = PrefStore.getResourceId(this, + distributionStr + "_suite_values", "array"); + if (suiteValuesId > 0) { + suite.setEntries(suiteValuesId); + suite.setEntryValues(suiteValuesId); + } + if (init) { + int suiteId = PrefStore.getResourceId(this, distributionStr + + "_suite", "string"); + if (suiteId > 0) { + String suiteStr = getString(suiteId); + if (suiteStr.length() > 0) + suite.setValue(suiteStr); + } + } + suite.setSummary(suite.getEntry()); + suite.setEnabled(true); + + // architecture + int architectureValuesId = PrefStore.getResourceId(this, + distributionStr + "_arch_values", "array"); + if (suiteValuesId > 0) { + architecture.setEntries(architectureValuesId); + architecture.setEntryValues(architectureValuesId); + } + if (init || architecture.getValue().length() == 0) { + int architectureId = PrefStore.getResourceId(this, + PrefStore.getArch() + "_" + distributionStr + + "_arch", "string"); + if (architectureId > 0) { + String architectureStr = getString(architectureId); + if (architectureStr.length() > 0) + architecture.setValue(architectureStr); + } + } + architecture.setSummary(architecture.getEntry()); + architecture.setEnabled(true); + + // source path + if (init || sourcepath.getText().length() == 0) { + int sourcepathId = PrefStore + .getResourceId(this, PrefStore.getArch() + "_" + + distributionStr + "_source_path", "string"); + if (sourcepathId > 0) { + sourcepath.setText(getString(sourcepathId)); + } + } + sourcepath.setSummary(sourcepath.getText()); + sourcepath.setEnabled(true); + + // RootFS + if (distributionStr.equals("rootfs")) { + // suite + suite.setEnabled(false); + // architecture + architecture.setEnabled(false); + // source path + if (init) { + String archiveFile = getString(R.string.rootfs_archive); + sourcepath.setText(archiveFile); + } + sourcepath.setSummary(sourcepath.getText()); + sourcepath.setEnabled(true); + } + } + if (listPref.getKey().equals("arch") && init) { + ListPreference distribution = (ListPreference) findPreference("distrib"); + EditTextPreference sourcepath = (EditTextPreference) findPreference("source_path"); + + String architectureStr = PrefStore.getArch(listPref.getValue()); + String distributionStr = distribution.getValue(); + + int sourcePathId = PrefStore.getResourceId(this, architectureStr + + "_" + distributionStr + "_source_path", "string"); + if (sourcePathId > 0) { + sourcepath.setText(getString(sourcePathId)); + } + + sourcepath.setSummary(sourcepath.getText()); + } + if (listPref.getKey().equals("target_type")) { + EditTextPreference targetpath = (EditTextPreference) findPreference("target_path"); + EditTextPreference disksize = (EditTextPreference) findPreference("disk_size"); + ListPreference fstype = (ListPreference) findPreference("fs_type"); + + switch (listPref.getValue()) { + case "file": + if (init) { + targetpath.setText(getString(R.string.target_path_file)); + } + disksize.setEnabled(true); + fstype.setEnabled(true); + break; + case "directory": + if (init) { + targetpath.setText(getString(R.string.target_path_directory)); + } + disksize.setEnabled(false); + fstype.setEnabled(false); + break; + case "partition": + if (init) { + targetpath.setText(getString(R.string.target_path_partition)); + } + disksize.setEnabled(false); + fstype.setEnabled(true); + break; + case "ram": + if (init) { + targetpath.setText(getString(R.string.target_path_ram)); + } + disksize.setEnabled(true); + fstype.setEnabled(false); + break; + } + } + } + + } + +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/PropertiesStore.java b/app/src/main/java/ru/meefik/linuxdeploy/PropertiesStore.java new file mode 100644 index 00000000..10f751d9 --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/PropertiesStore.java @@ -0,0 +1,87 @@ +package ru.meefik.linuxdeploy; + +import android.content.Context; +import android.text.TextUtils; + +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +public class PropertiesStore extends ParamUtils { + + public static final String name = "properties_conf"; + private static final String[] params = {"method", "distrib", "arch", "suite", "source_path", + "target_type", "target_path", "disk_size", "fs_type", "user_name", "user_password", + "privileged_users", "dns", "locale", "init", "init_path", "init_level", "init_user", + "init_async", "ssh_port", "ssh_args", "graphics", "vnc_display", "vnc_depth", "vnc_dpi", + "vnc_width", "vnc_height", "vnc_args", "x11_display", "x11_host", "x11_sdl", + "x11_sdl_delay", "fb_display", "fb_dev", "fb_input", "fb_args", "fb_refresh", + "fb_freeze", "desktop", "mounts", "include"}; + + public PropertiesStore() { + super(name, params); + } + + @Override + public String fixOutputParam(Context c, String key, String value) { + switch (key) { + case "user_password": + if (value.isEmpty()) value = PrefStore.generatePassword(); + break; + case "vnc_width": + if (value.isEmpty()) + value = String.valueOf(Math.max(PrefStore.getScreenWidth(c), PrefStore.getScreenHeight(c))); + break; + case "vnc_height": + if (value.isEmpty()) + value = String.valueOf(Math.min(PrefStore.getScreenWidth(c), PrefStore.getScreenHeight(c))); + break; + case "mounts": + if (!get(c, "is_mounts").equals("true")) value = ""; + break; + case "include": + Set includes = new TreeSet<>(); + includes.add("bootstrap"); + if (get(c, "is_init").equals("true")) { + includes.add("init"); + } else { + includes.remove("init"); + } + if (get(c, "is_ssh").equals("true")) { + includes.add("extra/ssh"); + } else { + includes.remove("extra/ssh"); + } + if (get(c, "is_gui").equals("true")) { + includes.add("graphics"); + includes.add("desktop"); + } else { + includes.remove("graphics"); + includes.remove("desktop"); + } + value = TextUtils.join(" ", includes); + break; + } + return value; + } + + @Override + public String fixInputParam(Context c, String key, String value) { + if (value != null) { + switch (key) { + case "mounts": + if (!value.isEmpty()) set(c, "is_mounts", "true"); + break; + case "include": + List includes = Arrays.asList(value.split(" ")); + if (includes.contains("init")) set(c, "is_init", "true"); + if (includes.contains("extra/ssh")) set(c, "is_ssh", "true"); + if (includes.contains("graphics")) set(c, "is_gui", "true"); + break; + } + } + return value; + } + +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/RepositoryActivity.java b/app/src/main/java/ru/meefik/linuxdeploy/RepositoryActivity.java new file mode 100644 index 00000000..58388b03 --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/RepositoryActivity.java @@ -0,0 +1,300 @@ +package ru.meefik.linuxdeploy; + +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.os.AsyncTask; +import android.os.Bundle; +import android.support.v7.app.AlertDialog; +import android.support.v7.app.AppCompatActivity; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.EditText; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; + +import java.io.BufferedReader; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.GZIPInputStream; + +public class RepositoryActivity extends AppCompatActivity { + + class RetrieveIndexTask extends AsyncTask { + + private ProgressDialog dialog; + private Context context; + + RetrieveIndexTask(Context context) { + this.context = context; + this.dialog = new ProgressDialog(context); + } + + @Override + protected void onPreExecute() { + dialog.setMessage(getString(R.string.loading_message)); + dialog.show(); + profiles.clear(); + } + + @Override + protected Boolean doInBackground(String... params) { + // params comes from the execute() call: params[0] is the url. + try { + downloadUrl(params[0]); + } catch (Exception e) { + return false; + } + return true; + } + + @Override + protected void onPostExecute(Boolean success) { + if (dialog.isShowing()) { + dialog.dismiss(); + } + adapter.notifyDataSetChanged(); + if (!success) { + Toast.makeText(context, R.string.toast_loading_error, Toast.LENGTH_SHORT).show(); + } + } + + private void downloadUrl(String url) throws IOException { + BufferedReader reader = null; + try { + URL u = new URL(new URL(url), "index.gz"); + reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(u.openStream()))); + String line; + Map map = new HashMap<>(); + while ((line = reader.readLine()) != null) { + if (line.isEmpty()) { + if (!map.isEmpty()) profiles.add(map); + map = new HashMap<>(); + continue; + } + if (!line.startsWith("#")) { + String[] pair = line.split("="); + String key = pair[0]; + String value = pair[1]; + map.put(key, value); + } + } + } finally { + if (reader != null) reader.close(); + } + } + } + + class ImportProfileTask extends AsyncTask { + + private ProgressDialog dialog; + private Context context; + private String profile; + + ImportProfileTask(Context context) { + this.context = context; + this.dialog = new ProgressDialog(context); + } + + @Override + protected void onPreExecute() { + dialog.setMessage(getString(R.string.loading_message)); + dialog.show(); + } + + @Override + protected Boolean doInBackground(String... params) { + profile = params[1]; + try { + downloadUrlAndImport(params[0], params[1]); + } catch (Exception e) { + return false; + } + return true; + } + + @Override + protected void onPostExecute(Boolean success) { + if (dialog.isShowing()) { + dialog.dismiss(); + } + if (success) { + PrefStore.changeProfile(getApplicationContext(), profile); + finish(); + } else { + Toast.makeText(context, R.string.toast_loading_error, Toast.LENGTH_SHORT).show(); + } + } + + private void downloadUrlAndImport(String url, String profile) throws IOException { + String conf = PrefStore.getEnvDir(context) + "/config/" + profile + ".conf"; + InputStream in = null; + OutputStream out = null; + try { + URL u = new URL(new URL(url), "config/" + profile + ".conf"); + in = u.openStream(); + out = new FileOutputStream(conf); + byte[] buffer = new byte[1024]; + int read; + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (in != null) in.close(); + if (out != null) out.close(); + } + } + } + + private List> profiles = new ArrayList<>(); + private ArrayAdapter adapter; + + private void importDialog(final Map profile) { + final String name = profile.get("PROFILE"); + final String message = getString(R.string.repository_import_message, + profile.get("DESC"), + profile.get("SIZE")); + new AlertDialog.Builder(this) + .setTitle(name) + .setMessage(message) + .setCancelable(false) + .setPositiveButton(R.string.repository_import_button, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int whichButton) { + importProfile(name); + } + }).setNegativeButton(android.R.string.no, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.cancel(); + } + }).show(); + } + + private void changeUrlDialog() { + final EditText input = new EditText(this); + input.setText(PrefStore.getRepositoryUrl(getApplicationContext())); + input.setSelection(input.getText().length()); + new AlertDialog.Builder(this) + .setTitle(R.string.repository_change_url_title) + .setView(input, 16, 32, 16, 0) + .setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, + int whichButton) { + String text = input.getText().toString(); + if (text.length() > 0) { + PrefStore.setRepositoryUrl(getApplicationContext(), text); + retrieveIndex(); + } + } + }).setNegativeButton(android.R.string.cancel, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.cancel(); + } + }).show(); + } + + private void retrieveIndex() { + String url = PrefStore.getRepositoryUrl(getApplicationContext()); + new RetrieveIndexTask(this).execute(url); + } + + private void importProfile(String name) { + String url = PrefStore.getRepositoryUrl(getApplicationContext()); + new ImportProfileTask(this).execute(url, name); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + PrefStore.setLocale(this); + setContentView(R.layout.activity_repository); + + // ListView Adapter + ListView listView = (ListView) findViewById(R.id.repositoryView); + adapter = new ArrayAdapter>(this, + android.R.layout.simple_list_item_2, android.R.id.text1, profiles) { + @Override + public View getView(int position, View convertView, ViewGroup parent) { + View view = super.getView(position, convertView, parent); + TextView text1 = (TextView) view.findViewById(android.R.id.text1); + TextView text2 = (TextView) view.findViewById(android.R.id.text2); + text1.setText(profiles.get(position).get("PROFILE")); + String desc = profiles.get(position).get("DESC"); + if (desc != null && !desc.isEmpty()) text2.setText(desc); + else text2.setText(getString(R.string.repository_default_description)); + return view; + } + }; + listView.setAdapter(adapter); + + // Click listener + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + public void onItemClick(AdapterView parent, View view, int position, long id) { + Map profile = (Map) parent.getItemAtPosition(position); + importDialog(profile); + } + }); + } + + @Override + public void setTheme(int resId) { + super.setTheme(PrefStore.getTheme(this)); + } + + @Override + public void onResume() { + super.onResume(); + setTitle(R.string.title_activity_repository); + retrieveIndex(); + } + + @Override + public void onPause() { + super.onPause(); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + PrefStore.setLocale(this); + getMenuInflater().inflate(R.menu.activity_repository, menu); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_refresh: + retrieveIndex(); + break; + case R.id.menu_change_url: + changeUrlDialog(); + break; + } + return false; + } + +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/SettingsActivity.java b/app/src/main/java/ru/meefik/linuxdeploy/SettingsActivity.java new file mode 100644 index 00000000..4580f242 --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/SettingsActivity.java @@ -0,0 +1,197 @@ +package ru.meefik.linuxdeploy; + +import android.content.ComponentName; +import android.content.DialogInterface; +import android.content.SharedPreferences; +import android.content.SharedPreferences.OnSharedPreferenceChangeListener; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.preference.EditTextPreference; +import android.preference.ListPreference; +import android.preference.Preference; +import android.preference.PreferenceGroup; +import android.preference.PreferenceManager; +import android.preference.PreferenceScreen; +import android.support.v7.app.AlertDialog; + +public class SettingsActivity extends AppCompatPreferenceActivity implements + OnSharedPreferenceChangeListener, Preference.OnPreferenceClickListener { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + PrefStore.setLocale(this); + + PreferenceManager prefMgr = getPreferenceManager(); + prefMgr.setSharedPreferencesName(PrefStore.getSettingsSharedName()); + + // Restore from conf file + PrefStore.restoreSettings(getApplicationContext()); + + addPreferencesFromResource(R.xml.settings); + + initSummaries(getPreferenceScreen()); + } + + @Override + public void setTheme(int resId) { + super.setTheme(PrefStore.getTheme(this)); + } + + @Override + public void onResume() { + super.onResume(); + + setTitle(R.string.title_activity_settings); + getPreferenceScreen().getSharedPreferences() + .registerOnSharedPreferenceChangeListener(this); + } + + @Override + public void onPause() { + super.onPause(); + + getPreferenceScreen().getSharedPreferences() + .unregisterOnSharedPreferenceChangeListener(this); + + // set autostart settings + int autostartFlag = (PrefStore.isAutostart(getApplicationContext()) ? + PackageManager.COMPONENT_ENABLED_STATE_ENABLED + : PackageManager.COMPONENT_ENABLED_STATE_DISABLED); + ComponentName bootComponent = new ComponentName(getApplicationContext(), BootReceiver.class); + getPackageManager().setComponentEnabledSetting(bootComponent, autostartFlag, + PackageManager.DONT_KILL_APP); + + // set handler for network change action + int nettrackFlag = (PrefStore.isTrackNetwork(getApplicationContext()) ? + PackageManager.COMPONENT_ENABLED_STATE_ENABLED + : PackageManager.COMPONENT_ENABLED_STATE_DISABLED); + ComponentName networkComponent = new ComponentName(getApplicationContext(), NetworkReceiver.class); + getPackageManager().setComponentEnabledSetting(networkComponent, nettrackFlag, + PackageManager.DONT_KILL_APP); + + // update configuration file + PrefStore.dumpSettings(getApplicationContext()); + } + + @Override + public boolean onPreferenceClick(Preference preference) { + if (preference.getKey().equals("installenv")) { + updateEnvDialog(); + } + if (preference.getKey().equals("removeenv")) { + removeEnvDialog(); + } + return true; + } + + @Override + public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { + Preference pref = findPreference(key); + setSummary(pref, true); + switch (key) { + case "is_telnet": + // start/stop telnetd + EnvUtils.execService(getApplicationContext(), "telnetd", null); + break; + case "telnet_port": + // restart httpd + EnvUtils.execService(getApplicationContext(), "httpd", "restart"); + case "telnet_localhost": + // restart telnetd + EnvUtils.execService(getApplicationContext(), "telnetd", "restart"); + break; + case "is_http": + // start/stop httpd + EnvUtils.execService(getApplicationContext(), "httpd", null); + break; + case "http_port": + case "http_conf": + // restart httpd + EnvUtils.execService(getApplicationContext(), "httpd", "restart"); + break; + } + } + + private void initSummaries(PreferenceGroup pg) { + for (int i = 0; i < pg.getPreferenceCount(); ++i) { + Preference p = pg.getPreference(i); + if (p instanceof PreferenceGroup) + initSummaries((PreferenceGroup) p); + else + setSummary(p, false); + if (p instanceof PreferenceScreen) + p.setOnPreferenceClickListener(this); + } + } + + private void setSummary(Preference pref, boolean init) { + if (pref instanceof EditTextPreference) { + EditTextPreference editPref = (EditTextPreference) pref; + pref.setSummary(editPref.getText()); + + if (editPref.getKey().equals("env_dir") && !init) { + editPref.setText(PrefStore.getEnvDir(this)); + pref.setSummary(editPref.getText()); + } + + if (editPref.getKey().equals("http_conf") && + editPref.getText().isEmpty()) { + editPref.setText(PrefStore.getHttpConf(this)); + pref.setSummary(editPref.getText()); + } + } + + if (pref instanceof ListPreference) { + ListPreference listPref = (ListPreference) pref; + pref.setSummary(listPref.getEntry()); + } + } + + private void updateEnvDialog() { + new AlertDialog.Builder(this) + .setTitle(R.string.title_installenv_preference) + .setMessage(R.string.message_installenv_confirm_dialog) + .setIcon(android.R.drawable.ic_dialog_alert) + .setCancelable(false) + .setPositiveButton(android.R.string.yes, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + EnvUtils.execService(getApplicationContext(), "update", null); + finish(); + } + }) + .setNegativeButton(android.R.string.no, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }).show(); + } + + private void removeEnvDialog() { + new AlertDialog.Builder(this) + .setTitle(R.string.title_removeenv_preference) + .setMessage(R.string.message_removeenv_confirm_dialog) + .setIcon(android.R.drawable.ic_dialog_alert) + .setCancelable(false) + .setPositiveButton(android.R.string.yes, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + EnvUtils.execService(getApplicationContext(), "remove", null); + finish(); + } + }) + .setNegativeButton(android.R.string.no, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }).show(); + } + +} diff --git a/app/src/main/java/ru/meefik/linuxdeploy/SettingsStore.java b/app/src/main/java/ru/meefik/linuxdeploy/SettingsStore.java new file mode 100644 index 00000000..60dffe2b --- /dev/null +++ b/app/src/main/java/ru/meefik/linuxdeploy/SettingsStore.java @@ -0,0 +1,24 @@ +package ru.meefik.linuxdeploy; + +import android.content.Context; + +public class SettingsStore extends ParamUtils { + + public static final String name = "settings_conf"; + private static final String[] params = {"chroot_dir", "profile"}; + + public SettingsStore() { + super(name, params); + } + + @Override + public String fixOutputParam(Context c, String key, String value) { + return value; + } + + @Override + public String fixInputParam(Context c, String key, String value) { + return value; + } + +} diff --git a/app/src/main/res/drawable-hdpi/ic_action_properties_dark.png b/app/src/main/res/drawable-hdpi/ic_action_properties_dark.png new file mode 100644 index 00000000..3d429a76 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_action_properties_dark.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_action_properties_light.png b/app/src/main/res/drawable-hdpi/ic_action_properties_light.png new file mode 100644 index 00000000..eb44bed8 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_action_properties_light.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_action_start_dark.png b/app/src/main/res/drawable-hdpi/ic_action_start_dark.png new file mode 100644 index 00000000..8a9bc8a4 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_action_start_dark.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_action_start_light.png b/app/src/main/res/drawable-hdpi/ic_action_start_light.png new file mode 100644 index 00000000..6384a4ee Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_action_start_light.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_action_stop_dark.png b/app/src/main/res/drawable-hdpi/ic_action_stop_dark.png new file mode 100644 index 00000000..edc39540 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_action_stop_dark.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_action_stop_light.png b/app/src/main/res/drawable-hdpi/ic_action_stop_light.png new file mode 100644 index 00000000..2810b444 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_action_stop_light.png differ diff --git a/app/src/main/res/drawable-ldpi/ic_action_properties_dark.png b/app/src/main/res/drawable-ldpi/ic_action_properties_dark.png new file mode 100644 index 00000000..11a71e2e Binary files /dev/null and b/app/src/main/res/drawable-ldpi/ic_action_properties_dark.png differ diff --git a/app/src/main/res/drawable-ldpi/ic_action_properties_light.png b/app/src/main/res/drawable-ldpi/ic_action_properties_light.png new file mode 100644 index 00000000..e0ff07a3 Binary files /dev/null and b/app/src/main/res/drawable-ldpi/ic_action_properties_light.png differ diff --git a/app/src/main/res/drawable-ldpi/ic_action_start_dark.png b/app/src/main/res/drawable-ldpi/ic_action_start_dark.png new file mode 100644 index 00000000..3686f069 Binary files /dev/null and b/app/src/main/res/drawable-ldpi/ic_action_start_dark.png differ diff --git a/app/src/main/res/drawable-ldpi/ic_action_start_light.png b/app/src/main/res/drawable-ldpi/ic_action_start_light.png new file mode 100644 index 00000000..e487f58c Binary files /dev/null and b/app/src/main/res/drawable-ldpi/ic_action_start_light.png differ diff --git a/app/src/main/res/drawable-ldpi/ic_action_stop_dark.png b/app/src/main/res/drawable-ldpi/ic_action_stop_dark.png new file mode 100644 index 00000000..c183a8a1 Binary files /dev/null and b/app/src/main/res/drawable-ldpi/ic_action_stop_dark.png differ diff --git a/app/src/main/res/drawable-ldpi/ic_action_stop_light.png b/app/src/main/res/drawable-ldpi/ic_action_stop_light.png new file mode 100644 index 00000000..76a5d264 Binary files /dev/null and b/app/src/main/res/drawable-ldpi/ic_action_stop_light.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_action_properties_dark.png b/app/src/main/res/drawable-mdpi/ic_action_properties_dark.png new file mode 100644 index 00000000..e4cc75bd Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_action_properties_dark.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_action_properties_light.png b/app/src/main/res/drawable-mdpi/ic_action_properties_light.png new file mode 100644 index 00000000..f61442f8 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_action_properties_light.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_action_start_dark.png b/app/src/main/res/drawable-mdpi/ic_action_start_dark.png new file mode 100644 index 00000000..7dc52636 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_action_start_dark.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_action_start_light.png b/app/src/main/res/drawable-mdpi/ic_action_start_light.png new file mode 100644 index 00000000..4552ae6d Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_action_start_light.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_action_stop_dark.png b/app/src/main/res/drawable-mdpi/ic_action_stop_dark.png new file mode 100644 index 00000000..538b5f8f Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_action_stop_dark.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_action_stop_light.png b/app/src/main/res/drawable-mdpi/ic_action_stop_light.png new file mode 100644 index 00000000..0b8028c9 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_action_stop_light.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_action_properties_dark.png b/app/src/main/res/drawable-xhdpi/ic_action_properties_dark.png new file mode 100644 index 00000000..915c9dc8 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_action_properties_dark.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_action_properties_light.png b/app/src/main/res/drawable-xhdpi/ic_action_properties_light.png new file mode 100644 index 00000000..33a78471 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_action_properties_light.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_action_start_dark.png b/app/src/main/res/drawable-xhdpi/ic_action_start_dark.png new file mode 100644 index 00000000..6c586f15 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_action_start_dark.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_action_start_light.png b/app/src/main/res/drawable-xhdpi/ic_action_start_light.png new file mode 100644 index 00000000..652ac68d Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_action_start_light.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_action_stop_dark.png b/app/src/main/res/drawable-xhdpi/ic_action_stop_dark.png new file mode 100644 index 00000000..b472a429 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_action_stop_dark.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_action_stop_light.png b/app/src/main/res/drawable-xhdpi/ic_action_stop_light.png new file mode 100644 index 00000000..157ea160 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_action_stop_light.png differ diff --git a/app/src/main/res/layout-land/activity_about.xml b/app/src/main/res/layout-land/activity_about.xml new file mode 100644 index 00000000..fb061226 --- /dev/null +++ b/app/src/main/res/layout-land/activity_about.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-land/content_main.xml b/app/src/main/res/layout-land/content_main.xml new file mode 100644 index 00000000..e16f2f44 --- /dev/null +++ b/app/src/main/res/layout-land/content_main.xml @@ -0,0 +1,28 @@ + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_about.xml b/app/src/main/res/layout/activity_about.xml new file mode 100644 index 00000000..3ceb0f4f --- /dev/null +++ b/app/src/main/res/layout/activity_about.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_fullscreen.xml b/app/src/main/res/layout/activity_fullscreen.xml new file mode 100644 index 00000000..12f22d2f --- /dev/null +++ b/app/src/main/res/layout/activity_fullscreen.xml @@ -0,0 +1,8 @@ + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 00000000..abc49d10 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,22 @@ + + + + + + + + diff --git a/app/src/main/res/layout/activity_mounts.xml b/app/src/main/res/layout/activity_mounts.xml new file mode 100644 index 00000000..a4c5cf07 --- /dev/null +++ b/app/src/main/res/layout/activity_mounts.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/app/src/main/res/layout/activity_profiles.xml b/app/src/main/res/layout/activity_profiles.xml new file mode 100644 index 00000000..7dffa1d9 --- /dev/null +++ b/app/src/main/res/layout/activity_profiles.xml @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_repository.xml b/app/src/main/res/layout/activity_repository.xml new file mode 100644 index 00000000..6c969f13 --- /dev/null +++ b/app/src/main/res/layout/activity_repository.xml @@ -0,0 +1,17 @@ + + + + + + diff --git a/app/src/main/res/layout/content_main.xml b/app/src/main/res/layout/content_main.xml new file mode 100644 index 00000000..8a1add54 --- /dev/null +++ b/app/src/main/res/layout/content_main.xml @@ -0,0 +1,87 @@ + + + + + + + + + + + + +