Aug 25, 2013

Linux Mint Multiseat with keyboards & mice(Xephyr)

I must state this important fact first:

Xephyr on Ubuntu/Linux Mint does not come compiled with evdev support.

This is important because Linux uses evdev to configure most input devices like keyboards and mice. You will see lots of documentation on configuring inputs with evdev, but none of those methods will work unless you compile Xephyr from scratch and enable evdev yourself.

I downloaded and installed the following executable to make my life easier. I repeat, this method will not work unless you have a modified version of Xephyr with evdev support!

Correct drivers - make sure they are installed!

I used an older Nvidia card so the following commands got me up and running:
sudo apt-get -y xserver-xorg-video-nouveau
#
# Upgrade our system
sudo apt-get -y install ubuntu-drivers-common
sudo apt-get -y install nvidia-current nvidia-settings

If you are unsure what graphics card you have then run the following (the second line is my output; yours will probably be different):
$ lspci | grep VGA
01:00.0 VGA compatible controller: NVIDIA Corporation GT218 [GeForce 210] (rev a2)

Input devices

Determine which devices are which by running the following command (unplug devices to help to narrow down your options). The paths you see are going to help in writing up our configuration file.

$ ls -l /dev/input/by-path/
total 0
lrwxrwxrwx 1 root root 9 May 27 18:39 pci-0000:00:1d.0-usb-0:1:1.0-event-kbd -> ../event3
lrwxrwxrwx 1 root root 9 May 27 18:39 pci-0000:00:1d.0-usb-0:2:1.0-event-mouse -> ../event4
lrwxrwxrwx 1 root root 9 May 27 18:39 pci-0000:00:1d.0-usb-0:2:1.0-mouse -> ../mouse0
lrwxrwxrwx 1 root root 9 May 27 18:39 platform-i8042-serio-0-event-kbd -> ../event2
lrwxrwxrwx 1 root root 9 May 27 18:39 platform-i8042-serio-1-event-mouse -> ../event5
lrwxrwxrwx 1 root root 9 May 27 18:39 platform-i8042-serio-1-mouse -> ../mouse1

Custom Xephyr script

The custom script (save it to /usr/sbin/Xephyr.sh) will act like the glue in our multi-seat environment. It will attach input devices to our monitors and some other stuff.

#!/bin/bash
# 20060905 - josean - added get_event() function to obtain eventNN from a physical address
# Original version:
# http://en.wikibooks.org/wiki/Multiterminal_with_Xephyr
# http://www.c3sl.ufpr.br/multiterminal/howtos/Xephyr.sh
trap "" usr1
XEPHYR=/usr/local/sbin/Xephyr
get_event()
{
    evento=`grep -A5 $1 /proc/bus/input/devices | grep 'H: Handlers=' | grep --only-matching -e 'event[0-9]*'`
}
args=()
while [ ! -z "$1" ]; do
    if [[ "$1" == "-xauthority" ]]; then
        shift
        if [ ! -z "$1" ]; then
            export XAUTHORITY="$1"
        fi
    elif [[ "$1" == "-display" ]]; then
        shift
        if [ ! -z "$1" ]; then
            export DISPLAY="$1"
        fi
    elif [[ "$1" == "-kbdphys" ]]; then
        shift
        if [ ! -z "$1" ]; then
            get_event $1
            args=("${args[@]}" "-keybd")
            args=("${args[@]}" "evdev,,device=/dev/input/$evento,xkbrules=evdev,xkbmodel=evdev,xkblayout=us")
        fi
    elif [[ "$1" == "-mousephys" ]]; then
        shift
        if [ ! -z "$1" ]; then
            get_event $1
            args=("${args[@]}" "-mouse")
            args=("${args[@]}" "evdev,5,device=/dev/input/$evento")
        fi
    else
        if ! expr match $1 'vt[0-9][0-9]*' >/dev/null; then
            args=("${args[@]}" "$1")
        fi
    fi
    shift
done
echo $XEPHYR "${args[@]}"
exec $XEPHYR "${args[@]}"

Xorg.conf settings

Edit /etc/X11/xorg.conf with something similar to the following. Please change the values to your whatever matches your system!!

############## SETTINGS#############
Section "ServerFlags"   Option  "DontZap"  "true"   Option  "DontVTSwitch" "true"   Option   "DontZoom" "true"   Option   "AllowMouseOpenFail"   "true"   Option   "AllowEmptyInput"   "true"   Option   "AutoAddDevices"   "false"   Option   "AutoEnableDevices"   "false"   Option  "Xinerama" "false"   Option   "NoPM" "true"   Option   "DPM" "false"   Option   "BlankTime" "0"   Option   "StandbyTime" "0"   Option   "SuspendTime" "0"   Option   "OffTime" "0"EndSection
############## INPUTS#############
Section "InputDevice"   Identifier   "Keyboard1"   Driver      "evdev"   Option      "Device" "/dev/input/event2"   Option      "Floating" "true"   Option      "XkbRules" "evdev"   Option       "XkbModel" "evdev"   Option      "XkbLayout" "us"EndSection
Section "InputDevice"   Identifier   "Mouse1"   Driver      "evdev"   Option      "Device" "/dev/input/event5"   Option      "Floating" "true"   Option      "GrabDevice" "on"   Option      "Protocol" "auto"   Option      "Emulate3Buttons" "no"   Option      "ZAxisMapping" "4 5"EndSection
Section "InputDevice"   Identifier   "Keyboard0"   Driver      "evdev"   Option      "Device" "/dev/input/event3"   Option      "Floating" "true"   Option      "XkbRules" "evdev"   Option      "XkbModel" "evdev"   Option      "XkbLayout" "us"EndSection
Section "InputDevice"   Identifier   "Mouse0"   Driver      "evdev"   Option      "Device" "/dev/input/event4"   Option      "Floating" "true"   Option      "GrabDevice" "on"   Option      "Protocol" "auto"   Option      "Emulate3Buttons" "no"   Option      "ZAxisMapping" "4 5"EndSection
########### SEAT 1##########
Section "Device"   Identifier   "Device1"   Driver      "nvidia"   Vendorname   "NVIDIA Corporation"   BoardName   "GeForce 210"   Option      "DPMS" "false"   Option      "UseDisplayDevice" "CRT"   Option      "ProbeAllGpus" "false"   Option      "NoLogo" "true"   Option      "RenderAccel" "true"   Screen      1EndSection
Section "Monitor"   Identifier   "Monitor1"   VendorName   "Toshiba"   ModelName   "Toshiba Matsushita Display Technology Co., Ltd LCD-MONITOR"   Option      "DPMS" "false"EndSection
Section "Screen"   Identifier   "Screen1"   Device      "Device1"   Monitor      "Monitor1"   DefaultDepth   24   Subsection "Display"      Depth   24      Modes   "nvidia-auto-select"   EndSubsection   Option      "DPMS" "false"   Option      "UseDisplayDevice" "CRT"   Option      "ProbeAllGpus" "false"EndSection
############# SEAT 0############
Section "Device"   Identifier   "Device0"   Driver      "nvidia"   VendorName   "NVIDIA Corporation"   BoardName   "GeForce 210"   Option      "DPMS" "false"   Option      "UseDisplayDevice" "DFP"   Option      "ProbeAllGpus" "false"   Option      "NoLogo" "true"   Option      "RenderAccel" "true"   Screen      0EndSection
Section "Monitor"   Identifier   "Monitor0"   VendorName   "Toshiba"   ModelName   "Toshiba Matsushita Display Technology Co., Ltd LCD-MONITOR"   Option      "DPMS" "false"EndSection
Section "Screen"   Identifier   "Screen0"   Device      "Device0"   Monitor      "Monitor0"   DefaultDepth   24   SubSection "Display"      Depth 24      Modes "nvidia-auto-select"   EndSubsection   Option      "DPMS" "false"   Option      "UseDisplayDevice" "DFP"   Option      "ProbeAllGpus" "false"EndSection
############## SERVERS#############
Section "ServerLayout"   Identifier   "multix"   Screen   0 "Screen0" 0 0   Screen   1 "Screen1" 0 0EndSection


MDM configuration

The MDM is what executes everything (if it has been configured properly). Edit /etc/mdm/mdm.conf and change the Server Section to the following:

## Also note, that if you redefine a [server-foo] section, then MDM will# use the definition in this file, not the MDM System Defaults configuration# file.  It is currently not possible to disable a [server-foo] section# defined in the MDM System Defaults configuration file.#
[server-Xephyr0]name=Xephyr0command=/usr/bin/X -ac -br -layout multix -audit 4 -dpmshandled=falseflexible=false
[server-Xephyr1]name=Xephyr1command=/usr/sbin/Xephyr.sh -display :0.0 -xauthority /var/lib/mdm/:0.Xauth -fullscreen -kbdphys usb-0000:00:1d.0-1/input0 -mousephys usb-0000:00:1d.0-2/input0 -verbosity 100 -audit 4 -screen 0 -dpms -retrohandled=trueflexible=false
[server-Xephyr2]name=Xephyr2command=/usr/sbin/Xephyr.sh -display :0.1 -xauthority /var/lib/mdm/:0.Xauth -fullscreen -kbdphys isa0060/serio0/input0 -mousephys isa0060/serio1/input0 -verbosity 100 -audit 4 -screen 1 -dpms -retrohandled=trueflexible=false

Resources

Aug 23, 2013

Coursera Notes: Stanford 'Start-up Engineering' (Lectures 5-8)

These are just some of my notes from Coursera's 'Start-up Engineering' course, taught by Balaji Srinivasan from Stanford.

This is a continuation of my existing series of notes.

Market Research, Wire-framing and Design

  • Idea \ne Mock-up
    Mock-up \ne Prototype
    Prototype \ne Program
    Program \ne Product
    Product \ne Business
    Business \ne Profit
  • Execution! It is not the idea, but the execution that matters. Sales rather than technology is what builds a business.
  • Market! Market will draw a product from a team, whether or not it is quality or the team is good.
  • An idea exists within a maze. A simple sentence is not enough to describe an idea; an idea is defined by the regulations, markets, and competition.
  • Execution mindset. This is essentially writing a to-do list and regularly checking off items. Rinse and repeat.
  • Market Research:
    1. News coverage and research papers. Google Books, SEC filings and Wikipedia.
    2. Back-of-envelope estimate of market size. Look for relevant statistics.
    3. Validate. Google keyword planner and Facebook advertiser tools help determine if there is actually a market need.
    4. Do a basic launch page with basic SEO. Use wireframes.
    5. Ad-word to discover the market. The launch page will then gauge market interest.
  • MVP or Minimum Viable Product.
  • Remember, a start-up aims to be very ambitious and scale rapidly.
  • Two features of successful start-ups:
    1. Exhibit economies of scale. Cost of production per unit decreases as more units are built (but revenue stays the same). We can then determine a break-even point and therefore the minimal capital required.
    2. Attack/Pursue large markets. Different pricing will attract different markets, but low price points require automation and industrial efficiency to make profits (because customer service is expensive). It may be better to charge higher initially to counter risks. Market sizing calculations should be done early and often.
  • Once a market and broad perspective has been set, versions and features need to be prioritized. Remember, it is execution and sales that matter!
  • Rough guide to prioritizing versions and features:
    • How much are they willing to pay for certain features or versions?
    • Which features are required in each version? What features make sense to bundle together?
    • Estimate the time and cost to build each feature. Is it feasible to implement the feature now, or wait for more funding?
    • Find the most popular features.
    • Calculate the market size for each feature.
  • Wireframing tools: omnigraffle, lucid chart, jet strap and popapp.
  • Copy-writing:
    • Home-page message must allow a customer to immediately figure out what the product is. This is a priority if this is going to be a major source of potential customers.
    • Work backwards from the press release (write the release then build the product). This allows you to figure out which features are making the news and which are not.
    • Find your competitors and explain why they are terrible options. Use this insight when explaining the benefits of your product.
    • Simple, factual and concise statements.
    • Call to action. Allow the customer to do something once they visit your website.
  • Vector graphics are better to work with.
  • In design remember Alignment, Repetition, Contrast and Proximity.
  • Start with a font heavy design (it is easier to do and images can always come later)

Mobile

  • Assumption behind the mobile phenomenon is that everything is going to be on the internet. The internet is going from a novelty to a utility.
  • Build for HTML5 and then move to native apps. HTML5 ensure your application works on all devices (and Android will soon utilise HTML5 and Javascript instead of native applications).
  • Internet of Things is the idea that every device will have it's own IP address. This offers a huge potential market.
  • Quantified self is the measuring of human beings and our actions. This is the collection of metrics that may revolutionize diagnosis and medicine.
  • One way to build mobile-aware applications is user-agent sniffing. This approach has the problems that a client can fake their own user-agent, and that the user-agent is inherently unreliable.
  • CSS media queries and Responsive web design allows the application of conditional styles depending on screen size. This is much more reliable, but does not have ubiquitous support (yet).
  • Some constraints with mobile include:
    • Unreliable networks (the fallacies of distributed computing)
    • Debugging requires logging (and bug reporting)
    • Minimization of user input (difficult problem to solve; how to collect everything you need without overwhelming the user)
    • Minimize the time to result (if you take too long the user will go elsewhere)

HTML / CSS / Javascript

  • HTML is the skeleton of a web application. It provides the structure of a page and the semantics. It is a set of finite elements with attributes.
  • CSS is the look and layout of a web application. It edits the element and attributes for styling and formatting.
  • Javascript is the dynamics and behavior of a web application. It allows you to provide client-side validation, pulling in content, playing games and much more.
  • Some useful tools include jsfiddle.net and Chrome Developer Tools.

Deployment, DNS and Custom Domains

  • Your code production environments should be along the lines of Development -> Staging -> Production
  • Separating environments bring the following benefits:
    • Testing of features before they reach the customer
    • Roll back of code in case of major bugs
    • Restore code or data in case of catastrophic crashes of the server
    • Incorporate contributions from multiple engineers
    • Perform AB testing of features
  • DNS (Domain Name System) converts IP address into human readable hostnames. The system first looks locally in a program, then the OS, then the ISP and then finally a trusted internet DNS server.

Inkscape and glue: Creating CSS sprites

I use a combination of Inkscape (to create raw SVG files and then export them to PNG images) and glue (to stich them all up and create the CSS file) to help me create CSS sprite icons for various websites. I also used iconmonstr as a starting point for some icons.

This is the BASH script I use to convert raw SVG files into PNG files and then into the sprite and CSS combination:
#!/bin/bash
mkdir -p ./img/48x48/ ./img/32x32/ ./img/16x16/
for i in ./svg/*.svg; do
    inkscape -z -w 48 -h 48 -e ./img/48x48/`basename $i .svg`.png $i
    inkscape -z -w 32 -h 32 -e ./img/32x32/`basename $i .svg`.png $i
    inkscape -z -w 16 -h 16 -e ./img/16x16/`basename $i .svg`.png $i
done
glue ./img/ --img=./img/ --css=./css/ --html --project

Aug 16, 2013

Coursera Notes: Stanford 'Start-up Engineering' (Lectures 1-4)

These are just some of my notes from Coursera's 'Start-up Engineering' course, taught by Balaji Srinivasan from Stanford.

Lecture 1:


  • A start-up is typically a company designed to grow rapidly and scale to global markets. The idea is to take ownership of the market before competitors move in.
  • The modern Start-up company is generally focused around the internet and other emerging technologies, but history is filled with start-up stories. The automobile, aviation, oil, and pharmaceutical industries all began with similar start-up journeys. Some of the biggest businesses we know had very humble beginnings.
  • The modern start-up industry began in 1989-1992. This was due to a combination of factors such as the widespread adoption of the internet, the fall of the USSR and the repeal of the NSF AUP in the USA.
  • The USSR (and other communist regimes) heavily regulated the use of technology, and you could be jailed for any unauthorized use. The fall of the USSR allowed the adoption of technology by the mainstream population, vastly increasing the amount of people interacting on-line. It also forced India to introduce policies that deregulated technology use and made China focus on market reforms. These factors helped to create the global free market.
  • The National Science Federation (NSF) in the USA had banned e-commerce because of fears of malware, spam and pornography. Eventually the US congress repealed the Accepted Use Policy (AUP), and this allowed people to start trading goods and services on-line.
  • The features of a modern start-up company include:
    1. Operational Scalability: This refers to the ability to conduct transactions from anywhere in the world without requiring a physical presence. This means you can rapidly expand into global markets without increasing operational overhead.
    2. Market size: The internet means a company now has access to a customer from anywhere in the world. This exponentially increases your market size (as long as border and geographical restrictions are solved).
    3. Generality: Software is a flexible and malleable tool with almost limitless potential. Software skills are also portable.
    4. Low capital barriers: Hardware costs are relative cheap, so sophisticated equipment can be bought with little capital overhead. Developers can also create their own software tools to suit the job at hand.
    5. Low regulation barriers: It is currently very hard to regulate the internet, but this should not be taken for granted. The firewall in China and the USA's NSA spying program are examples of attempts by governments to control, regulate and restrict the internet.
    6. Open source: The internet is built on open source technologies such as DNS, HTTP, HTML, IP, DHCP and other protocols and specifications. The free exchange of ideas and common technologies means the rapid emergence of new and useful tools for the entrepreneur.
    7. The long trail: The global scale of the potential market means that a start-up can target extremely specific customers and market niches like never before.
    8. Failure tolerance: Penalty for failure is lower than other industries (such as automobiles and aviation).
    9. Able to build a hybrid business: Can supply an API to interact with third-parties or the physical world. Automation through device drivers and actuators.
  • The current trend for start-ups is towards mobility and decentralization (or at least reducing the penalty for location and nationality).
  • Start-up engineering is focused on shipping a workable product. Iterative development is key; ship an initial product with reduced functionality to bring in some early funding to fuel further improvements in the next version.
  • Primary task of a start-up engineer is the integration of diverse technologies. They need to keep up with the latest developments, evaluate the usefulness of technology and quickly snap together the pieces.
  • Engineers need versatility, especially with Design, Marketing and Sales.
  • Mobile HTML5 and JS/JSON is the future of web applications. They allow for responsive mobile design (with a desktop UI as an aftereffect), which allows the use of the application on as many devices as possible.

Lecture 3 & 4:


  • Virtual Machines allows us to take a single physical computer and make it seem like multiple independent computers. Virtualisation significantly reduces the infrastructure overhead.
  • Linux has server-side license loophole. This allows a developer to modify open source code without distributing those changes to the public. This means you can modify code to create a service without releasing those code changes, as long as you are not distributing the changes for profit.
  • The Cloud Computer is a computer whose precise physical location is immaterial to the application. There are three approaches:
    1. IAAS: (Infrastructure As A Service) Direct access to hardware
    2. PAAS: (Platform As A Service) API access to the hardware.
    3. SAAS: (Software As A Service) API and GUI to the application, but no control over the hardware.
  • $PATH is the order of directories that Linux will use to search for a command. The first matching command found is assumed to be the desired command.
  • 'which' is a useful command to determine which command Linux will find first. This can help when you have multiple versions of a command installed
  • bash is a command-line shell implementation
  • A shell script begins with a sha-bang (#!) followed by the path to the command that the shell will use to interpret/execute the script.
  • ssh allows you to securely connect to a remote machine and run commands
  • scp allows you to connect and copy files to a remote machine
  • You can configure SSH so that you don't have to write out the connection details every time. Add the following to the file ~/.ssh/config and invoke with ssh <name>
    • Host <name>
    • HostName <hostname>
    • User <username>
    • Identityfile <the path to the file>
  • STDIN is the input stream, STDOUT is the output stream, and STDERROR is the error stream
  • Some useful linux commands:
    • cd - change directory
    • alias - set a command alias to save typing
    • rm - remove a file
    • mv - move a file
    • mkdir - create a directory
    • pwd - print the current working directory
    • env - list all environment variables
    • ls - list files in current directory
    • ln - create symbolic links
    • rsync - synchronise a local file with a remote file
    • wget - download a file (unlike rsync this is only for publicly available files)
    • curl - Only for single URLs, and can support more protocols than wget
    • ping - test network availability
    • less - used to view large files by paging it. CTRL+N down, CTRL+P up, Q quit
    • cat - File viewer, but does not have pagination features of less
    • head - view first few lines of a file
    • tail - view last few lines of a file
    • cut - Pull out columns from a file
    • paste - paste data into columns
    • nl - print our the line number
    • sort - sort lines in a file
    • uniq - determine unique elements in a file
    • wc - line, word and character count
    • split - split large files
    • man - single page manual files for commands
    • info - for some applications this will provide more detail than what man provides
    • uname - lists system information
    • hostname - name of machine
    • whoami - name of current user
    • ps - list current running processes
    • kill - kill a process
    • top - list processes based on criteria
    • sudo - act as root user for one or more commands
    • su - become root user
    • tar - archival utility
    • gzip - compression utility
    • find - non-indexed file search
    • locate - indexed file search. Requires updatedb command to be operational
    • df - determine disk space
    • du - determine file's disk usage
    • grep is a text and file parser that uses regular expressions. Very powerful.
    • sed is a string substitution command. Used to do a find and replace.
    • awk is a useful scripting language for tab-delimited text.
  • A list of useful bash shortcuts:
    • CTRL+K : Kill everything from cursor up
    • CTRL+C : Abort command
    • CTRL+L : Clear the screen
    • CTRL+D : Exit the command prompt
  • Backticks ` allows you to use results from commands as part of a new command
  • Ampersand & allows you to run a command in the background
  • xargs allows you to build command line arguments, and can spawn parallel processes.
  • tee allows you output to both a file and the display
  • time is useful for bench-marking commands
  • screen is a manager for remote tabs. This allows you to save a context that allows you to resume your work if you lose connection temporarily.

Aug 15, 2013

Windows Batch Script to lockdown firewall and only allow a few websites with dynamic IP addresses (nslookup)

This script was pretty much an extension of my earlier work on locking down windows. The problem is that that script only really worked for locking down static IP addresses. If you had a dynamic IP address you would have to manually change the firewall rules.

This script will delete the old firewall rules, find the new IP address of a host and create a new rule using that IP address.

@ECHO OFF
netsh advfirewall set domainprofile firewallpolicy allowinbound,allowoutbound
netsh advfirewall set privateprofile firewallpolicy allowinbound,allowoutbound
netsh advfirewall set publicprofile firewallpolicy allowinbound,allowoutbound
 
netsh advfirewall firewall delete rule name=all dir=out protocol=tcp remoteport=80,8080,8443,443 profile=any 
for /f "tokens=1*" %%k in ('nslookup example.com.au') do (
if [%%k]==[Address:] set address=%%l
)
netsh advfirewall firewall add rule name="example" dir=out action=allow protocol=tcp remoteport=80,8080,8443,443 remoteip=%address% profile=any
 
for /f "tokens=1*" %%k in ('nslookup learning.com.au') do (
if [%%k]==[Address:] set address=%%l
)
netsh advfirewall firewall add rule name="learning" dir=out action=allow protocol=tcp remoteport=80,8080,8443,443 remoteip=%address% profile=any
 
netsh advfirewall set domainprofile firewallpolicy blockinbound,blockoutbound
netsh advfirewall set privateprofile firewallpolicy blockinbound,blockoutbound
netsh advfirewall set publicprofile firewallpolicy blockinbound,blockoutbound

By saving this script somewhere secure you can create an event run by the inbuilt Windows Task Scheduler to run this script daily. This way you never have to worry about updating your firewalls when IP addresses change!