Showing posts with label linux. Show all posts
Showing posts with label linux. Show all posts

Thursday, September 6, 2012

Make new ThinkPad's charge thresholds work in Debian/Ubuntu

Instead of Intro

ThinkPad`s have been always famous for the amazing hardware compatibility with Linux. But seems this time has gone and owners of new ThinkPad`s like ThinkPad X230, T430 and of some other may have started experiencing some uncomfortable changes. The one of the such changes is inability to use tp_smapi module to set battery thresholds.

Battery charge threshold might be important for you if you want extend the battery's health. They are used to keep batteries partially charged.

I am as an owner of brand new ThinkPad x230 run into the impossibility to load tp_smapi module for my primary Debian (Testing) GNU/Linux as well as to set above mentioned thresholds. Here will be a safe workaround to fix the regression. It must work as well for Ubuntu Linux.

For the previous versions of ThinkPad`s it was simply enough to put desired integers to /sys/devices/platform/smapi/BAT{0,1}/{start,stop}_charge_thresh files to make these thresholds work. Currently there are no such special files anymore; since tp_acpi loading is failed. At least for the newest ThinkPad`s. Fortunately there is an alternative way: to set these values directly through the kernel's ACPI subsystem not ThinkPad brand controller's interface.

There is a module called acpi_call which was originally designed for easy switching video adapters in dual graphics environments. It provides a convenient interface for sending any command to ACPI subsystem; literally "call ACPI for some request". But which command to send to request a change of charge thresholds? Actually it does not matter because you should not do it by yourself. There is a special tool called tpacpi-bat (the part of tpbattstat-applet) which will do it for you.

Solution: all steps together

The only things we need to make ThinkPad`s charge thresholds work in Debian/Ubuntu are:
  1. Install acpi_call module;
  2. Install tpacpi_bat script;
  3. Configure thresholds setting on system boot-up;

acpi_call for Debian/Ubuntu

acpi_call is not included to standard Debian/Ubuntu repositories. The only way is to build it by yourself. Since I am a bit lazy about keeping in mind that with each kernel update I should rebuild acpi_call module I decided to write a simple script which will register and install it as a DKMS module.

The script could be retrieved from my git repository. The only requirement for running it is a root permission. If some packages required to build are missing you will be notified. Run it with 'run' argument and the script will do the following for you:
  • Retrieve acpi_call sources from the main git repository;
  • Register it as a DKMS module;
  • Install acpi_module to your Debian/Ubuntu system.

tpacpi_bat

tpacpi_bat is also not included to standard Debian/Ubuntu repositories. It could be grabbed from the author's git repository. The script depends on Perl only and could be put anywhere on the system, e.g. to /usr/local/bin.

Thresholds on boot-up

To make charge thresholds set on system boot-up:
  • acpi_call entry must be added to /etc/modules
  • The following commands must be added to /etc/rc.local:
/usr/local/tpacpi-bat -v startChargeThreshold 0 N
/usr/local/tpacpi-bat -v stopChargeThreshold 0 K

where N and K are integers in percent of full battery capacity.


Enjoy! Thanks to this ThinkPad's batteries might be a bit healthy :).

Sunday, July 22, 2012

Splitting OpenBox configuration to several files

Several weeks ago I decided to enhance performance of my Linux-powered ThinkPad x120e laptop. The one of the steps was switching from XFCE's window manager to a more lightweight and configurable one. I decided to give a try to OpenBox and since then I still like it.

Being a Software Developer I cannot stand pieces of software code which are large than ~15 lines. The one of the reasons is such code is hard to maintain. The same rule is applied for configuration files as well. OpenBox's configuration file represents itself a quite large XML file called rc.xml. And I really do not like this approach. I decided to find a way to split it out to several small pieces with the corresponding responsibility zones.

At first glance because of XML we could use a mechanism called External Entity. After this attempt was failed I discovered in the source code of OpenBox that processing of such entities is disabled and I get started to send a patch to enable it. But right away I found that XInclude mechanism is supported. After googling it was discovered that this feature was added in 2010. Now my OpenBox rc.xml is split to several files and looks like this:

<?xml version="1.0" encoding="UTF-8"?> <openbox_config xmlns="http://openbox.org/3.4/rc" xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="resistance.xml"/>
  <xi:include href="focus.xml"/>
  <xi:include href="placement.xml"/>
  <xi:include href="theme.xml"/>
  <xi:include href="desktops.xml"/>
  <xi:include href="resize.xml"/>
  <xi:include href="margins.xml"/>
  <xi:include href="dock.xml"/>
  <xi:include href="keyboard.xml"/>
  <xi:include href="mouse.xml"/>
  <xi:include href="menu.xml"/>
  <xi:include href="applications.xml"/>
</openbox_config>

Note: because of syntax highlighter bug extra HTML tags may appear in this snippet. Please ignore them.

Where each include represents a corresponding configuration section. For example, resistance.xml:

<resistance>
    <strength>10</strength>
    <screen_edge_strength>20</screen_edge_strength>
</resistance>

As for me this is a very underrated feature which is not covered even in the official documentation. It makes the configuration components of OpenBox more granular and modular.

Note: Please be aware that OpenBox GUI configuration tools such as obconf may handle (and currently they do!) such files with XInclude`s.

Wednesday, May 30, 2012

How to replace screensaver in XFCE

Intro: XFCE's default screensaver

By default XFCE is shipped with a quite ascetic xscreensaver. Some people ma find it not attractive. So I do also. For example, if you install an alternative screen locking application called i3lock there are about no chances that it will be used by XFCE. Even there are no other alternatives installed. Because XFCE knows nothing about it. But user definitely knows and wants to replace the default screensaver with a preferred one.

The entry point for XFCE to screen lockers is a script called xflock{4}. All XFCE applications which need to start a screensaver or to lock the screen run it. (Note: Since version 4.10 it is shipped as a part of xfce4-session package.) E.g., XFCE's power manager will call xflock{4} when an action "Lock Screen" is specified for several ACPI events like "LID closed"; or when system goes suspend. The script itself launches only a default screensaver.

Possible alternatives

The ugly thing about this script is that it contains hardcoded list of screensavers. So if yours favorite screensaver is not listed there it won't be launched. The priority of these locking applications is:
  1. xscreensaver
  2. GNOME Screensaver
  3. xlock
  4. slock
And nothing else!

Solution

The straight way is to add an alternative screensaver is to hack xflock{4}'s contents. Replace:

for lock_cmd in \
  "xlock -mode blank" \
  "slock"
  do

with:

for lock_cmd in \
  "my-favorite-screensaver" \ # e.g. i3lock
  "xlock -mode blank" \
  "slock"
  do

But on the system's next update these changes more likely will be overrided with the default ones and yours screensaver will stop launching.
The best way of course is to extend xflock{4} and send the patch to upstream; but not this time :).
Another way is to pretend like we have a one of the above-mentioned screensavers which XFCE is familiar with:
  1. Create a script which launches your screensaver. For example, with the following contents:
    #!/bin/sh
    if ! pidof i3lock > /dev/null 2>&1; then # launch once only
      /usr/bin/i3lock --dpms -c 000000
    fi
    
  2. Make a symbolic link /usr/bin/slock to the newly created script;
After these steps there will be a new system's default screen locker.

Note: Do not forget to uninstall xscreensaver, gnome-screensaver, xlock from the system if there are any to prevent using of them because of their's higher priority.

Note: Please keep in mind about created symlink if once you decide to install an application with the same name.

Tuesday, May 1, 2012

Some TrueCrypt sugar for Linux

Intro

Currently we have a fast growing trend called "Clouds". In the Clouds we can store about everything and be sure that we are able to get it back anywhere and anytime. The only thing is Clouds do not belong to us. That's why we should think critical when we upload a very-very private data there. This way of thinking leads us to use various file encryption tools like encfs, TrueCrypt and other.

I like TrueCrypt. It is installed on my every Linux workstation. But sometimes I am not the only user of such workstations. There could be several concurrent users who are able to browse computer's filesystem. Do you remember the default behavior of TrueCrypt when it is asked (I mean double-click inside File Manager) to mount an encrypted volume? Right! By default it mounts a specified container somewhere to /mnt (/media) directory which could be browsed by other online users. That means they are able to see my private data stored in the mounted TrueCrypt container! Nein, I do not want this! I want to make double-click on a TrueCrypt container and be the only viewer of it's contents.

That's why I have written a kind of mounter of TrueCrypt containers which connects decrypted volume to user's home folder.

In Action

Suppose that our encrypted volumes have ".private" extension in the filename. To make them always be opened with the mounter we should make a corresponding file association:
Make TrueCrypt container association with the truecrypt-mount application
TrueCrypt mounter (simple wrapper over TrueCrypt) is located in /usr/bin:
Specify an absolute path to truecrypt-mount application
Then TrueCrypt asks for the password:
Enter container's password to unlock the data
User-Locally (!) mounted container is immediately shown in a new window of File Manager. Please notice the path where the container is mounted to.
Immediate browsing of mounted TrueCrypt volume
If there is an attempt to mount already connected TrueCrypt's volume with truecrypt-mount application there will be a corresponding error message:
Already mounted TrueCrypt volume error message


In details

truecrypt-mount as I have already mentioned above is a simple wrapper over TrueCrypt itself. The wrapper is just a POSIX shell script which redirects volume mount requests from the user to TrueCrypt application with the "correct" arguments.

truecrypt-mount is configured through /etc/default/truecrypt file. The following options are supported:

TRUECRYPT_BINARY -- path where TrueCrypt itself is installed. By default points to /usr/bin/truecrypt.

USER_MOUNT_ROOT -- path where will be created user-specific mounts.

EXPLORE_MOUNTED_VOLUME -- boolean value which specifies should be a newly mounted TrueCrypt volume shown in the File Browser or not.

ERROR_REPORTING_CHANNEL -- specifies how errors while mounting are shown.

Download

The wrapper is available for download from the git repository http://git.thekondor.net
truecrypt-mount is a part of truecrypt-extra package since there is not the only thing how the experience with TrueCrypt could be improved (see below).

The application as well as the package is distributed in the terms on GNU GPL v3.0+ license.

As a benefit

Exploring volume in XFCE

Have you ever tried to launch TrueCrypt from a command line with '--explore' option being in XFCE? If you have, you must have also probably received an error that "Nautilus" is not found. Accordingly to the source codes of TrueCrypt it knows nothing about Thunar! Then you possibly tried to work around the problem by creating a fake Nautilus "application".

Thanks to EXPLORE_MOUNTED_VOLUME option for truecrypt-mount there is no need in such workarounds anymore; we get it just for free! By calling /usr/bin/xdg-open there will be opened default File Manager.

Sleep means Sleep

That's all about being kinda paranoid :). What if a laptop while hibernated is stolen? What if there are several mounted TrueCrypt volumes? That means that a Bad Guy having a hibernation image is able to retrieve sensitive data from those volumes because they were not disconnected! To prevent this kind of hole user should always unmount its TrueCrypt volumes when laptop is sent to sleep/hibernate mode.

truecrypt-extra package provides PM-Utils script 20_unmount-truecrypt-containers which unmounts ALL connected TrueCrypt volumes in the user's system when it goes sleep/hibernate. This behavior could be disabled by UNMOUNT_ON_SLEEP option.

Not a summary

I still have several ideas about improving TrueCrypt experience in Linux which might be implemented in the terms on truecrypt-extra package. So stay tuned and send your feedback regarding the package if any.

Saturday, December 3, 2011

Reduce Linux laptop's backlight on boot up

I like Linux. Especially for being able to create graceful workarounds for the things we get accustomed in a real life.

Being a Linux-powered laptop owner I have always been annoyed by sharp backlight change when Linux boots up. I do not like when a backlight is set to the maximum one and there are no ways to affect these settings on. So I did a very funny trick.

System's backlight (aka "display's brightness") in Linux could be changed through the special /sys/class/backlight/acpi_video0/brightness file. When an integer is written Linux immediately changes laptop's backlight level. E.g. the following command:
# echo 10 > /sys/class/backlight/acpi_video0/brightness

will set display's brightness to 10 points.

The first steps of Linux boot up are made with initramfs scripts which are executed one by one. When system-required-specific modules are loaded laptop's backlight level dramatically raises up. So we can think about this point in time as a moment when the user is able to tell Linux not to do so; or at least set it explicitly to a preferred value. That moment in time in the terms of initrams-tools could be called "premount".
#!/bin/sh

### file: /etc/initramfs-tools/scripts/local-premount/backlight_level
### this file must have an executable bit.
###
### Author: Andrew Sichevoi
### Please feel free to send your bug reports to http://blog.thekondor.net

PREREQ=""
prereqs()
{
  echo "${PREREQ}"
}

case "${1}" in
  prereqs)
           exit 0;
           ;;
esac

. /scripts/functions

DEFAULT_BACKLIGHT_LEVEL=10
BACKLIGHT_LEVEL=
for arg in $(cat /proc/cmdline); do
  case ${arg} in
    backlight_level=*)
                       BACKLIGHT_LEVEL=${arg#backlight_level=}
                       ;;
  esac
done

if [ -z ${BACKLIGHT_LEVEL} ]; then
   log_warning_msg "Using default backlight level: '${DEFAULT_BACKLIGHT_LEVEL}'"
   BACKLIGHT_LEVEL=${DEFAULT_BACKLIGHT_LEVEL}
fi

echo ${BACKLIGHT_LEVEL} > /sys/class/backlight/acpi_video0/brightness

So here we go:
  1. Add the below-mentioned backlight_level script to /etc/initramfs-tools/scripts/local-premount directory, make it executable;
  2. Update initramfs using update-initramfs command (Linux distribution specific; at least that works for Debian and Ubuntu) to include the script to the initrd image;
  3. Set passing backlight_level=X (where X is a preferred backlight level) boot option in your's grub.cfg.
and reboot to see the changes in action.

The script just looks up backlight_level kernel boot option and writes (if any, or default one otherwise) this value to the brightness file for immediate laptop's brightness update.

Simple? I think yes. Does it work? Definitely. Perfect? Not at all: I believe that system's boot's up settings should not differ from main DE's ones: they should be configured through the single entry point not several ones. Anyway this scripts makes feel us that we able to control Linux as well as we have a new task to think about :). So stay tuned!

Friday, October 28, 2011

PAM authentication for Transmission btorrent client

The one of the most valuable things in the World Wide Web beside the public available knowledge are files. Files which you can grab; and it does not matter they are Free or not. Files could be downloaded using various ways: when you grab them for yourself only or when not just grab but also provide others with the abilities to get them easily too. Due to the second point I like to use torrents. The one of my favorite BitTorrent clients is Transmission -- great OpenSource crossplatform software.

The one of the valuable features of Transmission is an ability to run as daemon not being depending on any kind of GUI toolkits. That's why it is common to use Transmission daemon on servers and various NASes. The daemon can be conveniently managed using any GUI client as well as a Web-interface or even command-line tool. The access to the daemon is controlled through credentials -- the pair of username and password which are stored in settings.json configuration file.

It is definitely cool to be able to protect my running Transmission daemon from my neighbour who works for RIAA :). But I do not like the idea that to manage the daemon safely I should to generate and keep in mind another access password. I asked myself why just not to use the credentials I already have? I mean credentials I already use to log to my Linux system in.

In Linux user's authentication to a system usually is performed using PAM infrastructure -- Pluggable Access Module. The infrastructure provides a single mechanism for managing and embedding of software applications to the authentication workflow.

So I decided to integrate PAM authentication for Transmission torrent daemon. And it was done for 1 day. The patch is available on my git repository. It is applicable for trunk@13057.

Enable PAM authentication for Transmission

  • Add a user which privileges the daemon is run on to the group which is able to read /etc/shadow file (if authentication in your system is performed in standard Linux way). Usually such group is called 'shadow'.
  • Add to your Transmission's settings.json "rpc-native-authentication-enabled" parameter set to "true".
  • Restart the daemon and try to re-connect using your system credentials.
The name of parameter is chosen in that way because of cross-platform intentions. For each system native authentication might differ from PAM. But most UNIX`es it will most probably be PAM.

Currently the feature is enabled for Linux only. I suppose it can work w/o any extrac magic on MacOS as well as on BSD.

Cons
  • ssh-ready credentials are passed over network in the non-encrypted way;
For all my cases the credentials cannot (again: for my cases only) be sniffed. For other possible cases just use ssh-powerless credentials. And finally start using ssh key-based authentication!
  • the daemon is able to read /etc/shadow file. If the daemon is taken over, a brute force attack to the password can performed.
If your PAM is configured in the way no to use pam_unix.so, there should be no problems. In other ways there could be some unless you are using one-time passwords.

Pros
  • easy to maintain access to control Transmission daemon itself as well as allow 3rd-party trusted people to manage processed torrents;
No need to keep in mind another password. No extra reasons to change the password in cases when you shared daemon access for one time; just block guest account.
  • PAM is just a frontentd but there could be any backend;
In the other words you are not forced to used system credentials to manage Transmission daemon. For example your PAM could be configured to perform user's authentication over LDAP or one-time SMS.

Using

The patch to add PAM authentication to Transmission torrent client is distributed in terms of GNU GPL v3.0+ license.
Since to its specific needs currently it is not going to be the part of main Transmission's branch. So if you maintain your own Transmission's fork/build please feel free to share your opinions regarding the feature.

Saturday, February 12, 2011

Customizing GNOME screensaver's lock dialog

Using bleeding edge Linux there are absolutely no guarantees that something doesn't go wrong. Several days ago I updated my Debian GNU/Linux "Testing" [branch] installation in the way I usually do using aptitude upgrade. Some things got broken some didn't. After this update I found that appearance of GNOME screensaver's lock dialog had changed: it became collapsed in it's total width. So, how to return the dialog's previous appearance and geometry back?

Google says nothing regarding this issue. But nothing tells us that it is impossible to solve it out:
  • GNOME Screensaver's lock dialog appearance is not "hardcoded" to the executable binary;
  • The dialog's appearance is built up before showing to the user from Glade's UI file located in /usr/share/gnome-screensaver directory; the default one is called lock-dialog-default.ui.
  • There could be several different .ui files:
    • The text between "lock-dilalog-" and ".ui" in the file's name called "name of the dialog's theme";
    • Switching between available themes of GNOME Screensaver's lock dialog is made using /apps/gnome-screensaver/lock_dialog_theme key in gconf.
Glade UI file is an ordinary XML file which describes declaratively the appearance and layout of some dialogs or widgets shown to the end-user. This one looks like:

<?xml version="1.0"?>
<!--*- mode: xml -*-->
<interface>
      <object class="GtkFrame" id="lock-dialog">
        <property name="visible">True</property>
        <property name="label_xalign">0</property>
        <property name="label_yalign">0.5</property>
        <property name="shadow_type">GTK_SHADOW_OUT</property>
        <child>
          ...
          <object class="GtkAlignment" id="alignment1">
          ...
        </child>
        <child>
          <placeholder/>
        </child>
      </object>
</interface>

So having known these things now it is possible for us to fix the original problem out:
  1. Make a copy of lock-dialog-default.ui to the same dir; name it, say, lock-dialog-extended-default.ui; the next step is made with the newly copied file;
  2. Add a new property called width_request to GtkFrame object with ID lock-dialog; the value must be set to the number of preferred pixels;
  3. Set /apps/gnome-screensaver/lock_dialog_theme value to extended-default since we have created a new dialog's theme.
Gotcha! The dialog looks in the way we like it now.

And some related remarks:
  1. Actually it is not a hack way; it is absolutely official one;
  2. It is possible to use any text editor to extend UI file as well as to use Glade application (usually it is not included to the default system's installation) for such purposes;
  3. There are already "ready-to-use" themes for GNOME screensaver's lock dialog. Just google for "GNOME screensaver lock dialog theme" and you may find something out you really like.

Tuesday, June 8, 2010

Linux, Thinkpad, HDAPS: battery mode

ThinkPad laptops have a lot of amazing features. HDAPS is one of them. HDAPS stands for Hard Disk Active Protection System; it is intended to protect ThinkPad's HDD from damage in case of a notebook drop or other kind of impact while it is running.

But HDAPS doesn't work 'out of the box' on Linux by default. On my Debian too. But there is so indispensable website named ThinkWiki with the tons of information how to make Linux and ThinkPad friends forever. And there is a cool article how to enable HDD APS (http://www.thinkwiki.org/wiki/How_to_protect_the_harddisk_through_APS): just compile few modules and install a special daemon -- nothing difficult. And APS will begin to work. Every time.

But there are cases when there are no need in active HDD protection when laptop is running from AC but required when the battery mode. How to handle this? The answer is to use capabilities of pm-utils package -- it allows to make hooks on special events like 'Laptop is on battery more' or vice-versa. So here a little tip'n'trick.

1. Create an executable hdaps file in /etc/pm/power.d folder with the following contents:
#!/bin/sh

HDAPS_MODULES="thinkpad_ec tp_smapi hdaps"
HDAPSD_INIT_SCRIPT=/etc/init.d/hdapsd
MODPROBE=/sbin/modprobe
RMMOD=/sbin/rmmod

case "$1" in
    ### CASE: Work on battery 
    true)
        echo "Enabling HDAPS"

        for module in $HDAPS_MODULES; do
            $MODPROBE $module
        done

        $HDAPSD_INIT_SCRIPT start
        ;;

    ### CASE: Work on AC-adapter
    false)
        echo "Disabling HDAPS"

        $HDAPSD_INIT_SCRIPT stop

        ### NOTE: modules should be unloaded in the reverse order
        for module in `echo $HDAPS_MODULES | tac -s' '`; do
            $RMMOD $module
        done
        ;;
esac
2. Disable hdaps modules autoloading from /etc/modules
3. Disable hdapsd daemon autorunning on system startup: # update-rc.d -f hdapsd remove

That's all! On Battery the script will load required HDAPS modules and run the daemon. Or will stop the daemon and unload the corresponding modules otherwise.

Tested and works well for my Debian Squeeze and Thinkpad T410.

Wednesday, April 28, 2010

'cp' command with a wget-like progress bar

Can not help re-posting: a tip and trick to make 'cp' command have a wget-like progress bar.

#!/bin/sh
cp_p()
{
   strace -q -ewrite cp -- "${1}" "${2}" 2>&1 \
      | awk '{
        count += $NF
            if (count % 10 == 0) {
               percent = count / total_size * 100
               printf "%3d%% [", percent
               for (i=0;i<=percent;i++)
                  printf "="
               printf ">"
               for (i=percent;i<100;i++)
                  printf " "
               printf "]\r"
            }
         }
         END { print "" }' total_size=$(stat -c '%s' "${1}") count=0
}

% cp_p /mnt/raid/pub/iso/debian/debian-2.2r4potato-i386-netinst.iso /dev/null
76% [===========================================>                    ]

Source: http://chris-lamb.co.uk/2008/01/24/can-you-get-cp-to-give-a-progress-bar-like-wget/

I think that's amazing idea!

Monday, October 5, 2009

Sandbox`ed (AppArmor) Skype 2.1 in Linux

To be able to stay in touch with my contacts and speak for free with people through Skype I agree that my workstation becomes P2P-node. But I do not agree that Skype scans my private files (browser cookies and history). What to do? As far as I am Linux user the solution is simple: to use AppArmor. According to this approach Skype is launched in some kind of sandbox, i.e. in the invironment where not everything is allowed You can read more about sandbox`ing Skype with AppArmor here.

But the problem is that all AppArmor profiles I found for Skype do not work for the latest version 2.1 -- they cause a termination of the application. Because they seem to be just a bit outdated. So I have managed to write (after hours of experiments) a new one, which definitely works well for me (Ubuntu 8.10 + latest Skype 2.1b). Here is a draft version of usr.bin.skype: