Tuesday, May 24, 2011

Iphone web server with php

I have an old iphone 3G that I upgraded to a 4G. Now I use it as my lowpower server. To do this you first need to jailbreak it and of course you need to have a home wifi setup. Serving private web pages is one of its uses. Here is the basic setup

Here is how to install lighttpd and php
  1. Jail break the iPhone using whatever setup you like
  2. Find the iPhones IP address in the wifi config area
    1. set your network IP to static.. and choose an IP at the end or out of your DHCP allocation range. (so that the DHCP doesnt keep moving your server around, nothing is worst for NAT setup..)
  3. Change the default passwords
    1. SSH into the iPhone using the username "root" and password "alpine"
    2. "root"s original password is "alpine"
    3. "mobile"s original password is also "alpine"
    4. double check for other accounts in /etc/passwd
      passwd 
      #enter old/new passwords for root
      su mobile
      passwd 
      #enter old/new passwords for mobile
      
  4. Remove password based ssh (makes it harder to hack in)
    1. copy/generate a ssh key from the entry machine.
    2. install the ssh key into the iPhone
    3. ssh into the phone (as mobile) and execute
      mkdir -p ~/.ssh
      chmod 0700 ~/.ssh
      touch ~/.ssh/authorized_keys
      chmod 600 ~/.ssh/authorized_keys
      cat >> ~/.ssh/authorized_keys
      #now paste in ssh key and hit crtl-D
      cat ~/.ssh/authorized_keys
      ls -al ~/.ssh/authorized_keys
      #confirm u see: -rw------- 1 mobile mobile ... /var/mobile/.ssh/authorized_keys
      
    4. Confirm login by ssh'ing in a diffrenet window
    5. BACKUP SSH KEY BEFORE CONTINUING. Its your way in from here on...
    6. Remove the password login.
      su
      #enter root password
      nano  /etc/ssh/sshd_config
      
    7. Now edit/add the following lines
      PasswordAuthentication no
      AllowTcpForwarding no
      X11Forwarding no
      AllowUsers mobile
      
    8. Restart iPhone (maybe /usr/sbin/sshd is sufficent to restart the sshd)
    9. Check the setting by ssh'ing with the key/username. You will be prompted for login as: but it should reject before it asks a password.
  5. Installing web server software
    1. run apt-get and install packages
      su
      #enter root password
      apt-get install php
      apt-get install lighttpd
      
    2. if you are missing apt get you will need to open Cydia and install the "AptBackup" package
  6. setup web software
    1. create the directory/files erc needed
      mkdir -p /htdocs/site/
      mkdir -p /htdocs/log/
      chmod 777 /htdocs/log/
      mkdir /etc/lighttpd/
      
    2. Configure the site.
      nano /etc/lighttpd/lighttpd.conf
      
    3. Copy this into the file:
      include "mod_fastcgi.conf"
      server.document-root = "/htdocs/site/"
      #server.port = 8080
      
      server.username = "_sshd"
      server.groupname = "_sshd"
      
      server.bind = "localhost"
      server.tag ="lighttpd"
      server.errorlog = "/htdocs/log/error.log"
      accesslog.filename = "/htdocs/log/access.log"
      
      server.modules = (
      "mod_access",
      "mod_accesslog",
      "mod_fastcgi",
      "mod_rewrite",
      "mod_auth",
      "mod_fastcgi"
      )
      index-file.names = ( "index.html", "index.php" )
      
    4. Configure the php module.
      nano /etc/lighttpd/mod_fastcgi.conf
      
    5. Copy this into the file:
      fastcgi.server = ( ".php" =>
       ( "localhost" => 
        ( "bin-path" => "/usr/bin/php-cgi", "socket" => "/tmp/php.socket")))
      

    6. Setup a trial page
      nano /htdocs/index.php
      
    7. Copy this into the file:
      <?
          echo "Welcome:", $_SERVER['REMOTE_ADDR'];
      
          echo "< br >< br >Heres some uptime data:< br >";
          passthru("uptime");
          echo "< br >< br >Heres whats running:< br >";
          passthru("ps | sed 's/$/< br >/'");
      ?>
      

    8. Boot the server manually and check it all
      lighttpd -f /etc/lighttpd/lighttpd.conf
      

    9. Open a browser and enter http://your_iphones_static_ip and you should see the trial page
  7. Right now lighttpd has to be manually started, it wont do it automatically.
    1. Set it to autoboot via a launchd control file at /Library/LaunchDaemons/com.lighttpd.plist the launchd process will start it and keep it running if it should crash or be killed.

    2. touch /Library/LaunchDaemons/com.lighttpd.plist
      chmod go-wrx /Library/LaunchDaemons/com.lighttpd.plist
      nano /Library/LaunchDaemons/com.lighttpd.plist
      

    3. Paste in the contents
      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
      "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
      <plist version="1.0">
      <dict>
          <key>Label</key>
          <string>com.lighttpd</string>
          <key>ProgramArguments</key>
          <array>
              <string>/usr/sbin/lighttpd</string>
              <string>-f</string>
              <string>/etc/lighttpd/lighttpd.conf</string>
          </array>
          <key>RunAtLoad</key>
          <true/>
          <key>KeepAlive</key>
          <true/>
          <key>UserName</key>
          <string>root</string>
          <key>WorkingDirectory</key>
          <string>/htdocs</string>
      </dict>
      </plist>
      

    4. load it with(and check)
      launchctl load -w /Library/LaunchDaemons/com.lighttpd.plist
      ps aux | grep light  
      

    5. You can shut it down again with:
      sudo launchctl unload -w /Library/LaunchDaemons/com.lighttpd.plist
      

I note that you need to keep the iPhone plugged into its charger to keep it connected to the wifi and alive. Otherwise it goes into a low power mode and shut off the wifi link, there by disconnecting your server.

I also iphones php package is rather limited in some aspects. For example create_socket doesn't work.

I also note that the user who is running the server seems bad.

Refer
http://www.esrun.co.uk/blog/lighttpd-php-on-the-iphone/
http://www.cyberciti.biz/tips/lighttpd-restrict-or-deny-access-by-ip-address.html
http://stackoverflow.com/questions/1181751/send-iphone-http-request-to-apache-php-webserver
http://arcoleo.org/dsawiki/Wiki.jsp?page=Autostart%20MySQL%20on%20Mac

quick wake on lan script with netcat

An WOL packet is simply the 6 bytes of FF followed by the 6 byte MAC address repeated 16 times.

So to script it first generate the wake packet.. Im assuming the mac is AA:BB:CC:DD:EE:FF and Im storing the packet so I can use it on a machine without xxd..hence the file dump.
ETHER="aa:bb:cc:dd:ee:ff"
ETHER2=`echo $ETHER | sed "s/://g"`
ETHER3="${ETHER2}${ETHER2}${ETHER2}${ETHER2}"
ETHER4="FFFFFFFFFFFF${ETHER3}${ETHER3}${ETHER3}${ETHER3}"
echo ${ETHER4} | xxd -r -p > wake.packet

Then send out the wake packet with Netcat. You can send it directly to the server or to your routers broadcast address it should goto either port 7 or 9. For the example i choose 192.168.1.200 and port 7.
netcat -c -v -u -n -x -p 80 192.168.1.200 7 < wake.packet
The contents of the packet should looks like this:
$ xxd wake.packet
0000000: ffff ffff ffff aabb ccdd eeff aabb ccdd  ................
0000010: eeff aabb ccdd eeff aabb ccdd eeff aabb  ................
0000020: ccdd eeff aabb ccdd eeff aabb ccdd eeff  ................
0000030: aabb ccdd eeff aabb ccdd eeff aabb ccdd  ................
0000040: eeff aabb ccdd eeff aabb ccdd eeff aabb  ................
0000050: ccdd eeff aabb ccdd eeff aabb ccdd eeff  ................
0000060: aabb ccdd eeff                           ......

Post iPhone UI design

UI design is always one of the most annoying and unportable tasks a programmer faces. (Aside from the problems with "professional" designs that have more photoshop effects that common sense). Todays devices are changing drastically the iPhone was the linchpin on this. It has fundamentally redefined the human machine interface. Mouse point and click interfaces now need to handle the the finger pinch and flick. Static window layouts wont live much longer in a world of rotatable and portable hardware.

The problem boils down to the fact that every joe and his dog has his own UI implementation. And after reviewing several of these in a post iPhone/Android world I have come the conclusion that they just are not going to survive beyond a few years from now. Now more that ever the clean separation between Model/Controller/View needs to be handled or your code is going to get outdated and become a maintenance time sucker.

I think Androids Fragment idea is the way to go on this. Release the constraints on the placement/layout and reconsider your UI from the perspective of a set of fragments or UI chunks that are correlated and interacting. Think dynamic and fluid layouts. This way it allows the segments to be shuffled around to meet the needs or your next port and code reuse.

While doing all this its best to stay as farway as you can from the Frameworks Implementation specific classes. Especially the pointless rewrite/rebuild of the string and networking class that seems to be in every framework. Wrap them if you must use them but don't let it them anywhere near your core implementation.

Refer:
http://developer.android.com/videos/index.html#v=WGIU2JX1U5Y

Sunday, May 22, 2011

forcing i386 installs on 64bit

Sometimes you just cant find a 64 bit version of stuff.. force that 32 bit deb to install with.

sudo dpkg --force-architecture -i downloaded_package.deb

rtti to traits for auto uuiding classes

There are times when you want automatically UID or index a class. The rtti is string based and I am assuming that simple Hashing of of that string is not sufficient. So here is a quick hack up of trait class to achieve the result.

#include <iostream>
#include <stdint.h>
#include <map>
#include <typeinfo>

class RttiCasterBase
{
private:
  class RttiRegFactory
  {
  private:
    typedef std::map<std::string, uint32_t> RttiIDMap;
    
    //0 is the bad marker..
    uint32_t g_uid;
    RttiIDMap rttiIDMap;
    
    RttiRegFactory() :
      g_uid(1)
    {}
    
  public:
    static RttiRegFactory& instance()
    {
      static RttiRegFactory instance_;
      return instance_;
    }
    
    uint32_t getID(std::string rttiName)
    {
      if (rttiIDMap.find(rttiName) != rttiIDMap.end())
 return rttiIDMap[rttiName];
      rttiIDMap[rttiName] = g_uid;
      return g_uid++;
    }
  };
protected:
  static uint32_t  lookup(std::string rttiID)
  {
    return RttiRegFactory::instance().getID(rttiID);
  }
  
public:
  RttiCasterBase() {}
  virtual ~RttiCasterBase() {}
  
  virtual uint32_t      uid() = 0;
  virtual std::size_t   size() = 0;
  virtual std::string   rttiID() = 0;
};

template<typename T>
class RttiCasterImp : public RttiCasterBase
{
public:
  typedef T Type;
  uint32_t uid_;
  
  RttiCasterImp() :
    RttiCasterBase()
  {
    uid_ = RttiCasterBase::lookup(typeid(T).name());
  }
  
  ~RttiCasterImp() {}

  virtual uint32_t uid()
  {
    return uid_;
  }
  
  virtual std::size_t size()
  {
    return sizeof(T);
  }
  
  virtual std::string   rttiID()
  {
    return typeid(T).name();
  }
  
  T* cast(void* buf)
  {
    return reinterpret_cast<T*>(buf);
  }
  
  void print(std::ostream& out)
  {
    out << "uid:  "   << uid()    << std::endl
 << "size: "   << size()   << std::endl
 << "rttiID: " << rttiID() << std::endl
 << std::endl;
  }
};

class A {};
class B { int var; };
class C { char stuff[10]; };

int main(int argc, char const * const *argv)
{
  RttiCasterImp<A> InfoA;
  RttiCasterImp<B> InfoB;
  RttiCasterImp<C> InfoC;
  RttiCasterImp<B> InfoD;
  
  InfoA.print(std::cout);
  InfoB.print(std::cout);
  InfoC.print(std::cout);       
  InfoD.print(std::cout);       
}

Output looks like:
$ a.exe
uid:  1
size: 1
rttiID: 1A

uid:  2
size: 4
rttiID: 1B

uid:  3
size: 10
rttiID: 1C

uid:  2
size: 4
rttiID: 1B

Social circle.

Google has put out a new cross-referencing set of pages. They basically tie your profile page to your know friends and contacts. Check it out for your self.

http://www.google.com/s2/search/social#socialconnections

cleaning up ubuntus file usage

FIRST OF ALL get into the apt-get and clear out the apps you dont want. Then purge, autoclean, autoremove, orphan remove all the remain pieces until nothing is left

Heres the basic clean up (plus some setup)
sudo apt-get -y install gtkorphan logrotate localepurge fslint
sudo apt-get autoremove
sudo apt-get clean all 
sudo apt-get autoclean all
sudo localepurge
dpkg -l | grep '^rc'| cut -d' ' -f3 | xargs dpkg -P

When you take out packages the best way is to --purge or autoremove them
 sudo apt-get --purge remove bluez-utils bluez-gnome 
 sudo apt-get autoremove bluez-utils bluez-gnome 

Then execute gtkorphan and keep killing unneed deps until it cant find any.

The Disk Usage Analyzer to sort out the biggest space wasters. Its found at Applications->Accessories->Disk Usage Analyzer.

There is also the computer janitor. Its at System > Administration > Computer Janitor.

And you can also hunt down the dead log files and other crap in you system with fslint.

You may need to loop around the whole process a few times to get it really clear

Several useless packages that tend to be installed by default are(sorry list is very short I got hacking before I thought about writing it down);
  • gnome-pilot
  • mesu-utils
Refer http://maketecheasier.com/8-ways-to-maintain-a-clean-lean-ubuntu-machine/2008/10/07

PHP: getting the users IP address

$_SERVER['REMOTE_ADDR']; 

c++ chomping white space

A Bit of code to chomp strings in c++

#include <string>
#include <iostream>

int main()
{
  std::string str;
  getline(std::cin, str);

  std::cout << "'" << str << "'" << std::endl;
    
  std::string::size_type pos = str.find_last_not_of("\n \t");
  if(pos != std::string::npos) 
  {
    str = str.substr(0, pos+1);
  }
    
  std::cout << "'" << str << "'" << std::endl;
}

Quick way list your LAN machines

Here is a quick way to grab the Ethernet MACs and IPs of the machines that are up on your LAN

arp -a

Suming a list of numbers of the shell

Manipulating lists on the shell can be done with awk. The most common one I encounter is summing numbers. Here is a quick bit of shell magic to sum up the size of all log files below a certian dictionary. Awk has much more power than this however.

find . -type f | grep "\.log" | xargs ls -al | sed "s/  */ /g" | cut -d " " -f 5 | awk -F: '{total+=$1} END{print total}'

Friday, May 6, 2011

Shell repeat/do/while for a count

Gahh.. simple thing but annoying its for bash shell

 i=245; while [ $i -ne 33 ]; do  echo $i; i=`expr $i - 1`; done