Proxy Server

Proxy is a server that sits between a client application, such as a Web browser, and a real server. It intercepts all requests to the real server to see if it can fulfill the requests itself. Proxy itself has two main purposes
1. to improve performance
2. to filter content

There are also several kind of proxy in the internet divided as of their anonymity. There are
1. Transparent Proxy
=> this kind proxy provides no privacy improvements. This proxy will display the following information :

REMOTE_ADDR = Proxy’s IP
HTTP_VIA = Proxy’s IP
HTTP_X_FORWARDED_FOR = Your IP

2. Anonymous Proxy
=> this kind of proxy will hide the client IP address by replacing with either the proxies IP, or a random address. This proxy will display the following information :

REMOTE_ADDR = Proxy’s IP
HTTP_VIA = Proxy’s IP
HTTP_X_FORWARDED_FOR = Proxy’s IP, or random

3. Highly Anonymous Proxy
=> this kind of proxy provides the best security; however, all the caveats of an anonymous proxy are still present. This proxy will display the following information :

REMOTE_ADDR = Proxy’s IP
HTTP_VIA = blank
HTTP_X_FORWARDED_FOR = blank

How to Create Linux Startup Script

We can create a startup script on Linux especially on Debian based using this following script.

#! /bin/sh
# /etc/init.d/YOURSCRIPTNAME
### BEGIN INIT INFO 
# Provides: YOUR INFO
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Simple script to start a program at boot
# Description: Your description.
### END INIT INFO

# If you want a command to always run, put it here 

# Carry out specific functions when asked to by the system

case "$1" in
  start)
    echo "Starting YOURSCRIPTNAME"
    # run application you want to start
    ;;

  stop)
    echo "Stopping YOURSCRIPTNAME"
    # kill application you want to stop
    ;;
  *)
    echo "Usage: /etc/init.d/YOURSCRIPTNAME {start|stop}"
  exit 1
  ;;
esac
exit 0

Make script executable

sudo chmod 755 /etc/init.d/NameOfYourScript

Test starting the program

sudo /etc/init.d/NameOfYourScript start

Test stopping the program

sudo /etc/init.d/NameOfYourScript stop

Register script to be run at start-up

sudo update-rc.d NameOfYourScript defaults

Remove the script from start-up

sudo update-rc.d -f NameOfYourScript remove

Setting WiFi on Raspberry PI

Setup the interface configuration

sudo nano /etc/network/interfaces

Normally the base configuration will look something like this

auto lo
 
iface lo inet loopback
iface eth0 inet dhcp
 
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp

Assuming you have a DHCP server on your LAN (normally your DSL/Cable router) use the following configuration, your SSID and password will be put in the wpa_supplicant.conf later on in this guide

auto lo
 
iface lo inet loopback
iface eth0 inet dhcp
 
allow-hotplug wlan0
auto wlan0
iface wlan0 inet dhcp
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf

If you don’t have a DHCP server, or if you want to just statically assign the IP address you can use the following, however update the IP, Netmask and Gateway to match your network.

auto lo
 
iface lo inet loopback
iface eth0 inet dhcp
 
allow-hotplug wlan0
iface wlan0 inet manual
address 192.168.0.100
netmask 255.255.255.0
gateway 192.168.0.1
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf

Setup the WPA configuration

sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
network={
ssid="SSID-GOES-HERE"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP TKIP
group=CCMP TKIP
psk="WIFI-PASSWORD-GOES-HERE"
}

Reference :

How To: WiFi on your Raspberry PI

Twitter Bootstrap Typeahead

Here is the structure of the bootstrap typeahead script

$('#search').typeahead({
    source: function (query, process) {
        // implementation
    },
    updater: function (item) {
        // implementation
    },
    matcher: function (item) {
        // implementation
    },
    sorter: function (items) {
        // implementation
    },
    highlighter: function (item) {
       // implementation
    },
});

1. source
This option specifies the data set to use for the auto-suggest list. It can take either an array of strings (which we saw in the first example) or a function:

source: function (query, process) {
    states = [];
    map = {};
 
    var data = [
        {"stateCode": "CA", "stateName": "California"},
        {"stateCode": "AZ", "stateName": "Arizona"},
        {"stateCode": "NY", "stateName": "New York"},
        {"stateCode": "NV", "stateName": "Nevada"},
        {"stateCode": "OH", "stateName": "Ohio"}
    ];
 
    $.each(data, function (i, state) {
        map[state.stateName] = state;
        states.push(state.stateName);
    });
 
    process(states);
},

2. updater
This function is called by Bootstrap once the user selects an item, which gives us a chance to do something with the selection

updater: function (item) {
    selectedState = map[item].stateCode;
    return item;
}

3. matcher
This function is used by Bootstrap to check if the search string typed by the user matches anything in the source list. Its purpose is to filter the auto-suggest list to only the relevant values:

matcher: function (item) {
    if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
        return true;
    }
}

4. sorter
The Sorter function is responsible for sorting the list of suggestions filtered by the matcher:

sorter: function (items) {
    return items.sort();
}

5. highlighter
This function is used to highlight user’s input within auto-suggested results.

highlighter: function (item) {
    var regex = new RegExp( '(' + this.query + ')', 'gi' );
    return item.replace( regex, "$1" );
}

References:

How to Use JSON Objects With Twitter Bootstrap Typeahead

How To Install PPTP VPN on VPS

This is a guide to install the pptp VPN service on your VPS.
Please make sure that ppp module has been enabled for OpenVZ based VPS. Simply just check wheter the /dev/ppp is available or not.

On Ubuntu OS
Install the pptp server package

sudo apt-get install pptpd

On CentOS
Install the pptp server package
Download the RPM file pptpd-1.3.4-2.rhel5.i386.rpm from http://poptop.sourceforge.net/yum/stable/packages/

wget http://poptop.sourceforge.net/yum/stable/packages/pptpd-1.3.4-2.rhel5.i386.rpm

Install the RPM by running this command: –

rpm -ivh pptpd-1.3.4-2.rhel5.i386.rpm

Edit the pptp configuration file

sudo vim /etc/pptpd.conf

Go to the bottom of the file and uncomment the localip and remoteip

localip 192.168.0.1
remoteip 192.168.0.234-238,192.168.0.245

Localip is the IP address of your server whereas the remoteip are the addresses that will be used on the clients that connected to the server.

Edit the chap secrets file:

sudo vim /etc/ppp/chap-secrets

Add to it the authentication credentials for a user’s. Use following syntax:

username * users-password *

At this point, the pptp service should be working after restart the service using following command :

sudo /etc/init.d/pptpd restart

If you do not want to access anything beyond the server, than you are done. But if you want the user can access beyond the server for example internet, please follow these next few more step.

Edit the “sysctl” file to enable the IP forwarding

sudo vim /etc/sysctl.conf

Find the “net.ipv4.ip_forward” line and change the parameter from 0 (disabled) to 1 (enabled):

net.ipv4.ip_forward=1

Edit the iptables using these following command :

iptables -t nat -A POSTROUTING -j SNAT --to-source xx.xx.xx.xx
iptables -A INPUT -i venet0 -p tcp --dport 1723 -j ACCEPT
iptables -A INPUT -i venet0 -p gre -j ACCEPT
iptables -A FORWARD -i ppp+ -o venet0 -j ACCEPT
iptables -A FORWARD -i venet0 -o ppp+ -j ACCEPT

Please replace the xx.xx.xx.xx with your VPS IP address

Edit the following file vi /etc/ppp/ip-up
Put this script on the end of the file

/sbin/ifconfig $1 mtu 1400
exit 0

To add a DNS server, edit the options.pptpd file, and add the following command

ms-dns 10.0.0.1
ms-dns 10.0.0.2

Change the IP address with your DNS IP Address

For more information on pptp, you can see the pptp log in file /var/log/syslog.

mPDF : Your web based PDF report

Looking for report for your web based application? mPDF would be one of the good option to choosed.

mPDF Installation and setup
Download latest mPDF version from the official website. Extract zipped file content to your defined folder and rename it to mpdf for better usage.
You may also allow three catalogs to be written. Folders list:
/ttfontdata/
/tmp/
/graph_cache/

Initializing mPDF and a first try
You may try your first code as example bellow

require_once('library/mpdf.php'); 
$mpdf = new mPDF();	 
$mpdf->WriteHTML('Your first taste of creating PDF from HTML');
$mpdf->Output();
exit;

More complex usage
We are trying to parse only CSS contents from file and add some div to the file. View the example here:

$mpdf = new mPDF();
$stylesheet = file_get_contents('stylesheet.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML('HTML content goes here...', 2);
$mpdf->Output();
exit;

Specific Page Format

$mpdf = new mPDF('utf-8', 'A4');
$mpdf = new mPDF('utf-8', array(190,236));

Some output method provided by mPDF
Method 1: Saving the PDF to a file:

$pdf->Output('filename.pdf','F');

Method 2: Prompting user to choose where to save the PDF file:

$pdf->Output('filename.pdf','D');

Method 3: Automatically open PDF in your browser after being generated:

$pdf->Output('filename.pdf','I');

Method 4: Returning the PDF file content as a string:

$pdf->Output('','S');

Reference :

mPDF: HTML to PDF introduction


http://blog.startq.com/index.php/2011/10/25/fpdf-output-methods-for-pdf-files-in-php/

Common Apache Tuning

Here are some tips how to optimized your apache setting.

Some typical setting for apache in some different server specification:

Apache Directive 1/4GiB 1GiB 2GiB 4GiB
StartServers 2 8 16 32
MinSpareServers 1 4 8 16
MaxSpareServers 2 8 16 32
ServerLimit 8 64 128 256
MaxClients 8 64 128 256
MaxRequestsPerChild 0 0 0 0
ListenBacklog 1000 1000 1000 100

Disabling mod_passenger

If you are not using Phusion Passenger (for Ruby on Rails apps), you can safely comment out the lines to load the dso under
/opt/local/etc/httpd/includes/dso.conf:

#LoadModule passenger_module lib/httpd/mod_passenger.so

/opt/local/etc/httpd/httpd.conf that loads the module:

#Include etc/httpd/includes/passenger.conf

Choose appropriate MPM:

Apache server ships with a selection of Multi-Processing Modules (MPMs) which are responsible for binding to network ports on the machine, accepting requests, and dispatching children to handle the requests [3]. Only one MPM can be loaded into the server at any time.

Choosing an MPM depends on various factors such as whether the OS supports threads, how much memory is available, scalability versus stability, whether non-thread-safe third-party modules are used, etc.. Linux systems can choose to use a threaded MPM like worker or a non-threaded MPM like prefork:

Worker MPM uses multiple child processes. It’s multi-threaded within each child and each thread handles a single connection. Worker is fast and highly scalable and the memory footprint is comparatively low. It’s well suited for multiple processors. On the other hand, worker is less tolerant to faulty modules and faulty threads can affect all the threads in a child process.

Prefork MPM uses multiple child processes, each child handles one connection at a time. Prefork is well suited for single or double CPU systems, speed is comparable to that of worker and it’s highly tolerant to faulty modules and crashing children. But the memory usage is high, more traffic leads to more memory usage.

MaxClients:

The MaxClients sets the limit on maximum simultaneous requests that can be supported by the server. No more than this much number of child processes are spawned. It shouldn’t be set too low such that new connections are put in queue, which eventually time-out and the server resources are left unused. Setting this too high will cause the server to start swapping and the response time will degrade drastically. Appropriate value for MaxClients can be calculated as: MaxClients = Total RAM dedicated to the web server / Max child process size —- [4] Child process size for serving static file is about 2-3M. For dynamic content such as PHP, it may be around 15M.

"ps -ylC httpd --sort:rss"

MinSpareServers, MaxSpareServers, and StartServers:

MaxSpareServers and MinSpareServers determine how many child processes to keep while waiting for requests. If the MinSpareServers is too low and a bunch of requests come in, then Apache will have to spawn additional child processes to serve the requests. Creating child processes is relatively expensive. If the server is busy creating child processes, it won’t be able to serve the client requests immediately. MaxSpareServers shouldn’t be set too high, it can cause resource problems since the child processes consume resources.

Tune MinSpareServers and MaxSpareServers such that Apache need not frequently spwan more than 4 child processes per second (Apache can spwan a maximum of 32 child processes per second). When more than 4 children are spawned per second, a message will be logged in the ErrorLog.

The StartServers directive sets the number of child server processes created on startup. Apache will continue creating child process until the MinSpareServers setting is reached. Doesn’t have much effect on performance if the server isn’t restarted frequently. If there are lot of requests and Apache is restarted frequently, set this to a relatively high value.

MaxRequestsPerChild:

The MaxRequestsPerChild directive sets the limit on the number of requests that an individual child server process will handle. After MaxRequestsPerChild requests, the child process will die. It’s set to 0 by default, that means the child process will never expire. It is appropriate to set this to a value of few thousands. This can help prevent memory leakage since the process dies after serving a certain number of requests. Do not set this too low, since creating new processes does have overhead.

KeepAlive and KeepAliveTimeout:

The KeepAlive directive allows multiple requests to be sent over the same TCP connection. This is particularly useful while serving HTML pages with lot of images. If KeepAlive is set to Off, then for each images, a separate TCP connection has to be made. Overhead due to establishing TCP connection can be eliminated by turning On KeepAlive.

KeepAliveTimeout determines how long to wait for the next request. Set this to a low value, perhaps between two to five seconds. If it is set too high, child processed are tied up waiting for the client when they could be used for serving new clients.

References :

http://wiki.joyent.com/
http://www.howtoforge.com/configuring_apache_for_maximum_performance

How to check your disk IO performance

The easiest way to check your disk io performance is by running the following command on command line

dd if=/dev/zero of=test bs=64k count=16k conv=fdatasync

The result would be like this :
=====================================
16384+0 records in
16384+0 records out
1073741824 bytes (1.1 GB) copied, 19.0812 seconds, 56.3 MB/s
=====================================
If the average result is above 25, then it should be just fine. But if your average test result is always bellow 25, you have to start worry about your disk io performance.

Using TAR command on console

In linux, we are usualy using TAR to archive or extract files.. Here are the simple command you can run on the console.

To archive with compression

tar -czvf myarchive.tgz mydirectory/

To archive without compression

tar -cvf myarchive.tar mydirectory/

To extract file with compression

tar -xzvf mystuff.tgz

To extract file without compression

tar -xvf mystuff.tar