Epic 4G USB tethering with Ubuntu Oneiric 11.10

It’s been a long time since I had to patch kernel code, to get a popular device to work with Linux.

I was having an issue tethering a Samsung Epic 4G to an Ubuntu 11.10 netbook over the USB cable.
When I plug things to Ubuntu, they just work most of the time. So this was a pleasant surprise.

I plugged an Epic 4G to the USB port and I can see the SCSI driver kicking in, with the command ‘dmesg’:

[13192.597053] scsi 5:0:0:0: Direct-Access     SAMSUNG  SPH-D700 Card         PQ: 0 ANSI: 2

When I enabled USB tethering on Android Gingerbread:

Settings -> Wireless and Network -> Tethering -> USB Tethering

I got these errors in Ubuntu about “bad CDC descriptors” when the USB network drivers try to load:

[13229.820147] usb 1-2: USB disconnect, device number 5
[13230.128108] usb 1-2: new high speed USB device number 6 using ehci_hcd
[13230.592280] usbcore: registered new interface driver cdc_ether
[13230.597004] usb 1-2: bad CDC descriptors
[13230.597081] usbcore: registered new interface driver rndis_host
[13230.607344] usb 1-2: bad CDC descriptors
[13230.607527] usbcore: registered new interface driver rndis_wlan

The Samsung Epic 4G uses RNDIS communication control, in order to provide Ethernet Networking over USB. (Microsoft Proprietary).
I hear this used to work well on Linux, until some devices got their Gingerbread update.

Now look at this bright example of Open Source community:
Some guy named Markus Kolb, submitted a bug report, provided debug and console captures; then wrote a patch as a workaround that fixes the issue.

I followed instructions from this Ubuntu Wiki, that explain how to compile a single module. After that, Ubuntu recognizes and connects me to the Internet with a tethered Epic 4G and Ubuntu using the USB cable.

# Fetch and uncompress the kernel source
sudo apt-get install linux-source patch
cd /usr/src
tar xfvj linux-source-3.0.0.tar.bz2 
# Apply the patch from the bug and compile the modules
cd linux-source-3.0.0/drivers/net/usb
patch cdc_ether.c $HOME/Downloads/Ubuntu_bug_796006.patch
make -C /usr/src/linux-headers-`uname -r` M=`pwd` modules    
# sudo make -C /usr/src/linux-headers-`uname -r` M=`pwd` modules_install
sudo depmod -a
# sudo update-initramfs -u

I could have done modules_install and update-initramfs, so the module is used at boot. However, it seemed faster to just copy the compiled module I need (cdc_ether.ko), and overwrite the old one:

cp cdc_ether.ko /lib/modules/`uname -r`/kernel/net/usb/cdc_ether.ko

I could have used the WiFi hotspot functionality instead, but this was more fun.

Posted in Ubuntu Linux | Tagged , | Leave a comment

Delete old log files

Logrotate is an utility in Ubuntu that allows package maintainers and admins to regulate how logfiles are stored, compressed and rolled for backups.

When creating lean virtual machine images, I found that I didn’t want to keep any logs.
I also didn’t want to go an reconfigure logrotate.

You can use the find command to get rid of all the backups, if you really don’t care about log backups.

/usr/bin/find /var/log/  \
    -type f \( -name "*\.log\.[0-9]*" -prune -o  \
        -name "*\.gz" -prune -o  \
        -name "*.[0-9]" -prune \)  \ 
    -exec rm -rf {} \;

If you must keep some log files based on their modifcation time, use the -mtime option.

find . -mtime 0   ( modified between now and 1 day ago )
find . -mtime 1   ( modified between 24 and 48 hours ago )
find . -mtime -1  ( modified less than 1 day ago )
find . -mtime +1  ( modified more than 48 hours ago )

Posted in Bash | Tagged | Leave a comment

Blog your status to a file using Bash

I wanted to take notes about what I’m currently doing at work, but I didn’t want to upload this info to Twitter or Facebook.
I also wasn’t in the mood to put MySQL and Tomcat to work hard on my laptop.
I just wanted something off-line and local for security.

I wrote this bash script to log my comments to a file.

#!/bin/bash
# Just display entries when you don't pass parameters
if [ $# -gt 0 ]
then
    DATE=$(date +"%m/%d/%Y %r")
    #use $@ to print out all arguments at once
    echo [$DATE] $@ >> $HOME/work.log
fi
# display last 4 entries
tail -n 4 $HOME/work.log

Save this as $HOME/bin/log

Use it like this:

~$ log Today I worked on XX project

and it will display:

[01/11/2010 03:41:59 PM] Way older post
[01/11/2010 03:43:01 PM] Older post
[01/12/2010 08:24:34 AM] Old post
[01/12/2010 02:31:47 PM] Today I worked on XX Project

Call it without arguments to simply display the last 4 entries without logging anything new.

Posted in Bash | Tagged , , | 2 Comments

Run a System Process from Scala

Here’s an example on how to run a System process from Scala.

+ ProcessBuilder simplifies the creation of the Process object
+ A Scala Actor reads the console output buffer concurrently
+ reactWithin allows us to timeout if the process hangs
+ receiveWithin in the main thread, guards us in case the Actor gets stuck

In this case we show the output of ls -1

One thing to notice is the continue val to exit the loop. At the time of writing, Scala 2.7 doesn’t support the break statement to exit loops. Support for break is expected in Scala 2.8

object Main {
    import java.io._
    import scala.actors._
    import scala.actors.Actor._
 
    private val caller = self
    private val WAIT_TIME = 2000
 
    private val reader = actor {
        println("created actor: " + Thread.currentThread)
        var continue = true
        loopWhile(continue){
            reactWithin(WAIT_TIME) {
                case TIMEOUT =>
                    caller ! "react timeout"
                case proc:Process =>
                    println("entering first actor " + Thread.currentThread)
                    val streamReader = new java.io.InputStreamReader(proc.getInputStream)
                    val bufferedReader = new java.io.BufferedReader(streamReader)
                    val stringBuilder = new java.lang.StringBuilder()
                    var line:String = null
                    while({line = bufferedReader.readLine; line != null}){
                        stringBuilder.append(line)
                        stringBuilder.append("\n")
                    }
                    bufferedReader.close
                    caller ! stringBuilder.toString
            }
        }
    }
 
    def run(command:String){
        println("gonna runa a command: " + Thread.currentThread)
        val args = command.split(" ")
        val processBuilder = new ProcessBuilder(args: _* )
        processBuilder.redirectErrorStream(true)
        val proc = processBuilder.start()
 
        //Send the proc to the actor, to extract the console output.
        reader ! proc
 
        //Receive the console output from the actor.
        receiveWithin(WAIT_TIME) {
                case TIMEOUT => println("receiving Timeout")
                case result:String => println(result)
        }
    }
 
    def main(args: Array[String]) :Unit = {
        println("Hello, world!")
        run("ls -1")
        System.exit(0)
    }
}

Posted in Scala | Tagged | 2 Comments

Test private methods in C# .Net

I was writing Unit Tests for a module that has many private methods.

With these tricks, my UnitTest assembly is allowed to access all methods and properties as if they were declared Internal, rather than private, without changing the production code modifiers to internal.

When creating the Unit Tests, Visual Studio 2008 suggested I added the following line to AssemblyInfo.cs on the Target assembly under test.

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("UnitTests")]

However, I got the following error during build time:

Friend assembly 'UnitTests' reference is invalid.
 Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations

To fix this, make sure your UnitTest assembly is signed. (As detailed in this MSDN Article)

Use SecUtil to find your public key’s token in Hex.

secutil.exe -hex -s UnitTests.dll

SecUtil comes with the Microsoft SDK.

I didn’t want to use the command line, because it requires knowing and typing the full path to the DLL file, so I added SecUtil to my External Tools in visual studio, to keep it handy.

image

SecUtil as External Tool in Visual Studio 2008

Add the PublicKey value without 0x prefix, like this:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("UnitTests,PublicKey=002.....1093")]

Now build and observe the Errors and Warnings are gone.

Posted in C# | Tagged , , | Leave a comment

Format and Indent XML in Ubuntu Linux

While playing with Castor, I used one of their tools to generate an XML file.
The problem is that the XML file was one line. It was pretty hard to read with the text wrapping.

Here’s how to turn ugly.xml into pretty.xml in Ubuntu Linux

Install tidy:

sudo apt-get install tidy

Parse the ugly xml with tidy:

cat ugly.xml  | tidy -utf8 -xml -w 255 -i -c -q -asxml > pretty.xml

The result is a nicely formatted and Indented XML file, where the allowed width was 255 characters.

Here’s the man page with the details on the options.

Posted in XML | Tagged , , | 2 Comments

Find the full Path of a Resource File in the Classpath

Hardcoding the filesystem location of a file in your tests, can become a maintenance problem.

If the resource file changes location, you’ll have to update and re-compile your code to match the new path.

One way to solve this problem is to add the file to the Classpath and get it as a Resource.

import java.util.Properties;
 
Properties _prop = new Properties();
 
@Before        
public void setUp() throws Exception {
    // Loading properties from your Classpath
    InputStream in = this.getClass().getResourceAsStream("/AcceptanceTest.properties");
    _prop.load(in);
    in.close();
    // Print contents to the Console
    System.out.println("Properties: " + _prop.toString());                
}

If what you really need is the actual filesystem path, you can resolve it invoking the method .getPath() from the java.net.URL class.

For example, let’s say you are testing an application that was designed to use a system property that references a file in the local system. Put the file in the classpath, store it anywhere in the filesystem and then update the property during the test initialization. This allows you to switch between platforms without having to reconfigure the code with the new location.

import java.net.URL;
 
@Before        
public void setUp() throws Exception {
    URL location =  this.getClass().getResource("/certStore");
    String FullPath = location.getPath();
    System.out.println(FullPath);
    System.setProperty("javax.net.ssl.keyStore", FullPath); 
}

Posted in Java | Tagged , | Leave a comment