Tuesday 13 December 2016

Practice Python skills

Client/Server interaction via Socket


Git Notes

GIT STATES:
Working Directory <==> Staging <==> Repository (.git folder) <==> Remote
COMMANDS
#git init .
#git status
#git add . (or file names)
#git log
#git show
#git ls-files
#git commit -am “Commit comments go here” –> Combine express commit and add files to staging age
#git commit -m “Commit comments go here”
#git config –global user.email “”
#git config –global user.name “”
#git config –global color.ui auto –> show color
#git config –global alias.hist “log –oneline –graph –decorate –all”

Saturday 17 October 2015

Saturday 3 October 2015

KB CMStorm - Backlight issue - Slackware

run the command:
xmodmap -e 'add mod3 = Scroll_Lock'

Tuesday 10 March 2015

SCP examples

 

Source: http://www.hypexr.org/linux_scp_help.php

Example syntax for Secure Copy (scp)

What is Secure Copy?

scp allows files to be copied to, from, or between different hosts. It uses ssh for data transfer and provides the same authentication and same level of security as ssh.

Examples

Copy the file "foobar.txt" from a remote host to the local host

    $ scp your_username@remotehost.edu:foobar.txt /some/local/directory

Copy the file "foobar.txt" from the local host to a remote host

    $ scp foobar.txt your_username@remotehost.edu:/some/remote/directory

Copy the directory "foo" from the local host to a remote host's directory "bar"

    $ scp -r foo your_username@remotehost.edu:/some/remote/directory/bar

Copy the file "foobar.txt" from remote host "rh1.edu" to remote host "rh2.edu"

    $ scp your_username@rh1.edu:/some/remote/directory/foobar.txt \
    your_username@rh2.edu:/some/remote/directory/

Copying the files "foo.txt" and "bar.txt" from the local host to your home directory on the remote host

    $ scp foo.txt bar.txt your_username@remotehost.edu:~

Copy the file "foobar.txt" from the local host to a remote host using port 2264

    $ scp -P 2264 foobar.txt your_username@remotehost.edu:/some/remote/directory

Copy multiple files from the remote host to your current directory on the local host

    $ scp your_username@remotehost.edu:/some/remote/directory/\{a,b,c\} .
    $ scp your_username@remotehost.edu:~/\{foo.txt,bar.txt\} .

scp Performance

By default scp uses the Triple-DES cipher to encrypt the data being sent. Using the Blowfish cipher has been shown to increase speed. This can be done by using option -c blowfish in the command line.
    $ scp -c blowfish some_file your_username@remotehost.edu:~
It is often suggested that the -C option for compression should also be used to increase speed. The effect of compression, however, will only significantly increase speed if your connection is very slow. Otherwise it may just be adding extra burden to the CPU. An example of using blowfish and compression:
    $ scp -c blowfish -C local_file your_username@remotehost.edu:~

Contributions

Thanks Stewart Macleod for port example.

Friday 13 February 2015

Convert mkv to mp4

ffmpeg -i file.mkv -vcodec copy -acodec copy file.mp4

Thursday 12 February 2015

Install Vmware Workstation 11 on Slackware 14.1

./VMware-Workstation-Full-10.0.2-1744117.x86_64.bundle  --console --custom --eulas-agreed -I --regular


if you get the error message when creating a new image:

“Error: Could not open /dev/vmmon: No such file or directory. Please make sure that the kernel module vmmon is loaded.”

Solution:

vmware-modconfig --console --install-all

 

Saturday 7 February 2015

Bash shell - moving faster

Source:
http://teohm.com/blog/2012/01/04/shortcuts-to-move-faster-in-bash-command-line/

Basic moves

  • Move back one character. Ctrl + b
  • Move forward one character. Ctrl + f
  • Delete current character. Ctrl + d
  • Delete previous character. Backspace
  • Undo. Ctrl + -

Moving faster

  • Move to the start of line. Ctrl + a
  • Move to the end of line. Ctrl + e
  • Move forward a word. Meta + f (a word contains alphabets and digits, no symbols)
  • Move backward a word. Meta + b
  • Clear the screen. Ctrl + l
What is Meta? Meta is your Alt key, normally. For Mac OSX user, you need to enable it yourself. Open Terminal > Preferences > Settings > Keyboard, and enable Use option as meta key. Meta key, by convention, is used for operations on word.

Cut and paste (‘Kill and yank’ for old schoolers)

  • Cut from cursor to the end of line. Ctrl + k
  • Cut from cursor to the end of word. Meta + d
  • Cut from cursor to the start of word. Meta + Backspace
  • Cut from cursor to previous whitespace. Ctrl + w
  • Paste the last cut text. Ctrl + y
  • Loop through and paste previously cut text. Meta + y (use it after Ctrl + y)
  • Loop through and paste the last argument of previous commands. Meta + .

Search the command history

  • Search as you type. Ctrl + r and type the search term; Repeat Ctrl + r to loop through results.
  • Search the last remembered search term. Ctrl + r twice.
  • End the search at current history entry. Ctrl + j
  • Cancel the search and restore original line. Ctrl + g

Thursday 22 January 2015

Premium Link Generators

http://www.exrapidleech.info/index.php
http://generatorlinkpremium.com/
http://debridx.com/download

Wednesday 21 January 2015

Fix : Google Chrome can not be run as Root user

" Google Chrome can not be run as Root user Please Start Google Chrome as a normal user. To run as Root, you must specify an alternate –user–data-Dir for storage of profile information. "
Edit file: #vim /opt/google/chrome/google-chrome
change the line:
exec -a “$0″ “$HERE/chrome” “$PROFILE_DIRECTORY_FLAG” \
to: exec -a “$0″ “$HERE/chrome” –user-data-dir “$PROFILE_DIRECTORY_FLAG” \

Make Firefox for Linux use Dolphin to ‘Open Containing Folder’

KDE --> System Settings --> File Associations --> inode/directory --> move Dolphin up to the first position

Monday 19 January 2015

git diff showing a weird output

Source: http://www.jpichon.net/blog/2013/05/git-diff-showing-weird-output/ Either of these commands things works well: $ git --no-pager diff # No paging $ git diff --color | less -R # With paging #export LESS='-M -R'

Monday 12 January 2015

Django - Translation check list

1. Mark your text for translation. ex: a. In template: using {% load i18n %} (at the top but have to be after the 'extends' tag) and {% trans 'text to be translated' %} b. in your code: from django.utils.translation import ugettext as _ ; _('Your text to be translated here') 2. Build the message file for language translations (creating .po files: ./manage makemessages -l vi (my django-admin.py doesn't work for me) You can run this again to reexamine the other text 3. Compile messages files ./manage compilemessages (do this again after you make changes to your po file 4. settings file LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGE_CODE = 'vi' 5. use URL international with i18n_patterns and set_length() add django.middleware.locale.LocaleMiddleware to MIDDLEWARE_CLASSES Use this form to set user's language preference
{% csrf_token %}
6.Others: TEMPLATE_CONTEXT_PROCESSORS += ( 'django.core.context_processors.request', ) add this to use request.get_full_path in your template

Friday 9 January 2015

Activating Unicode/UTF-8 Support and Changing Default Locale Language in Slackware

Source: http://gnu-linux-slackware.blogspot.com/2009/06/changing-system-wide-default-language.html For a list of locales which are supported by your Slackware box, type: $ locale -a If you have full installation of Slackware, all languages will be listed. To get UTF-8 support, edit lang.sh file as root by: # nano /etc/profile.d/lang.sh Comment default locale and add uncommented line export LANG=en_US.UTF-8 After modifying lang.sh file, save it and reboot your computer.

Thursday 8 January 2015

Konsole command -the text starts from the same line overwriting the prompt

Try enclosing each of the colour escape sequences in escaped square brackets. ex: PS1='\[\e[0;31m\]\t\[\e[m\]-\[\e[0;32m\]\u\[\e[m\]@\[\e[0;36m\]\h\[\e[m\]:\[\e[0;23m\]\w\[\e[m\e[0;32m\]\$\[\e[m\]'

Wednesday 24 December 2014

Show line numbers in VIM

Enable: :set number Disable :set nonumber

Comment/Uncomment multiple lines in Vim

SOURCE: https://hurley.wordpress.com/2007/06/13/vim-tip-comment-out-multiple-lines/ Commenting out a bunch of lines without a vim plugin: Select your lines with VISUAL BLOCK (CTRL-V), then press I to insert before all highlighted lines. Next type your comment character, # (for python, shell, etc). Last press ESC. I forget not frequently used, but helpful VIM commands from time to time. Why not blog it? You can alternatively select your lines with VISUAL LINE (SHIFT-V), then type : s/^/# This tells the selected lines that you wish to substitute the start of the line with the # char.

Sunday 21 December 2014

Install English dictionary on Slackware

Go to Slackbuilds.org and install the package Artha.

slocate: fatal error: Could not find user database '/var/lib/slocate/slocate.db': No such file or directory

You will see this message if you just run the slocate command the first time. Just run the following command to update slocate db: #updatedb

Fix mouse pointer disappeared (touchpad) after suspending

modprobe -r psmouse modprobe psmouse

Unzip multiple .zip files

unzip '*.zip'
( single quotes)

Install new TTF fonts on Slackware 14

1. Copy your ttf fonts to the folder /usr/share/fonts/TTF 2. Run the command to update your fonts cache: fc-cache -f -v

Sunday 27 April 2014

php mcrypt so slow



If you don't specify argument for mcrypt_create_iv(), it will use /dev/random(on Linux) by default as a random number generator. The problem of /dev/random is that its random pool depends on the system interrupts, when there is not enough system interrupts, it cannot generate enough random numbers, then the process tries to get the random numbers will wait and hang. Let's look at a simple example.
$ dd if=/dev/random bs=1024k count=1
When your system is busy, you will find the output speed is very slow, sometimes there will be pause.
The solution is using /dev/urandom instead of /dev/random, /dev/urandom is also a random number generator, but it doesn't depends on system interrupts.

mcrypt_create_iv ($length, MCRYPT_DEV_URANDOM); 

Friday 18 April 2014

English Learning Links


http://www.englishclub.com/learn-english/learn-english-how.htm

watching short films
http://www.multimedia-english.com/videos/section/official-1/tag/short-film-88

LISTENING

Kid's Storybooks:
http://freekidsbooks.org/
http://www.magickeys.com/books/
http://www.techsupportalert.com/free-audio-books-children
http://www.workaudiobook.com/WorkAudioBook/Download--Audiobooks-with-Subtitles.aspx?tag=windows
http://www.ted.com/talks
https://librivox.org/


TOEIC
http://blog.eslexplorer.com/blog/a-list-of-the-best-toeic-preparation-resources

Friday 4 April 2014

Sites for first grade math worksheets

http://www.homeschoolmath.net/worksheets/grade_1.php

http://www.eduplace.com/math/mw/models/tm_1.html

http://www.worksheetfun.com/letter%20and%20numbers/cloud%20rain%20missing%20numbers%201-30%20-%201.pdf

Monday 31 March 2014

Fixing slow performance of sending mail from PHP via Sendmail

Source: http://www.alphadevx.com/a/372-Fixing-slow-performance-of-sending-mail-from-PHP-via-Sendmail


Recently I have had two separate test servers that were very slow sending out emails from PHP scripts via the mail() function, where PHP was configured to use a local Sendmail binary to send the emails. The scripts were hanging for roughly one minute while waiting for Sendmail to work, which was severely impacting testing efforts.
When I run a test call to mail() and tail the maillog file, I see the following entries:
 1 
 2 
 3 
 4 
 5 
$ tail -f /var/log/maillog
Sep 13 11:30:27 myserver sendmail[29118]: My unqualified host name (myserver) unknown; sleeping for retry
Sep 13 11:31:27 myserver sendmail[29118]: unable to qualify my own domain name (myserver) -- using short name
Sep 13 11:31:27 myserver sendmail[29118]: My unqualified host name (myserver) unknown; sleeping for retry
Sep 13 11:31:35 myserver sendmail[29135]: My unqualified host name (myserver) unknown; sleeping for retry
So it seems that this is a local domain name resolution issue. The trick here is to ensure that you have an entry in your /etc/hosts file for your unqualified hostname, that is the short version returned by the hostname command, which points to the local loop-back IP rather than it's external IP like so:
 1 
127.0.0.1               localhost localhost.localdomain myserver
You need to also ensure that this is the only line in that file for the 127.0.0.1 loop-back IP, as Sendmail will only look at a single line.

Friday 28 March 2014

Subversion: reset user password

./htpasswd -m /path/to/your_svn_auth_file username_to_reset

Wednesday 5 March 2014

Notes on setting up Web server for php mysql development on centos

Setup LAMP on Centos for dev:
- Install Centos
- configure networking
- update system
- disable selinux
- restart system
- configure hostname for dsn resolution at webserver and dev host
- install Apache (httpd)
- configure Apache to use hostname
- install php
- restart Apache
- setup web server document folder
- code sample info.php file to test the configuration and run to verify the current setup
- install mysql and setup securely r(i.e: run mysql_secure_installation)

How do I get PHP remote debugging working under Komodo?

Question:

How do I get PHP remote debugging working under Komodo?
Answer:

There are a couple of things you need to make sure of in order to get PHP remote debugging working:

1. xdebug must be configured correctly. The php.ini that your web server is using should contain statements like this:

; xdebug config for Linux and Mac OS X
zend_extension=/usr/share/php5/debug/xdebug.so
xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=foo.bar.com
xdebug.remote_port=9000
xdebug.idekey=kyla

Note in particular that remote_host needs to be the hostname or ip address of the machine Komodo is running on, and remote_port needs to be the same as the remote port Komodo is using. You can check this by creating a script like this:



...and looking at the xdebug section in the output page.

2. Komodo must be configured correctly. At

Preferences / Debugger / Proxy

...set the field 'Listen for debug connections on port' to 9000 as above. Close the preferences and make sure that

Debug / Listen for remote debugger

...has a checkmark beside it.

3. You need to explicitly initiate a debugger session by adding the XDEBUG_SESSION_START get variable to the url in your browser:

http://baz.bar.com/script.php?XDEBUG_SESSION_START=1

If everything is correct, Komodo should pop-up a dialog inidicating that a remote application has requested a debugging session. If you click on 'OK', Komodo will step in to the first line of code in that script.

If this is still not working, some things to check are:

- can you ping the machine Komodo is running on form your web server?
- is the machine Komodo is on running some sort of software firewall that might be blocking the debugger requests?

Sunday 12 January 2014

Mobile Internet Profile

Mạng: MobiFone
Dịch vụ: Mobile Internet
APN: m-wap
Username: mms
Password: mms
----
Mạng: MobiFone
Dịch vụ: Fast Connect
APN: m-wap
Username: mms
Password: mms
----
Mạng: Vinaphone
Dịch vụ: Mobile Internet
APN: m3-world
Username: mms
Password: mms
----
Mạng: Vinaphone
Dịch vụ: Mobile Broadband
(chưa có thông tin)
----
Mạng: S-Fone
Số quay: (chưa có thông tin)
(Cần xác nhận sử dụng thực tế và danh sách các dịch vụ hiện cung cấp bởi S-Fone)
(Sự khác nhau khi sử dụng điện thoại và USB để truy cập.)
----
Mạng: Viettel Mobile
Dịch vụ: Mobile Internet
APN: v-internet
----
Mạng: Viettel Mobile
Dịch vụ: D-Com 3G
APN: e-connect
----
Mạng: Vietnamobile
Dịch vụ: GPRS
APN: internet
----
Mạng: Vietnamobile
Dịch vụ: Mobile Internet (cần xác nhận có cùng thông tin với GPRS hay không, sử dụng điện thoại có khác với USB không)
----
EVN telecom

E-Mobile (CDMA)
username: evntelecom
password: evntelecom
(cần thông tin xác nhận kết nối, tên dịch vụ và số điện thoại quay)
EVNTelecomNet (3G)
APN: e-internet

----
Beeline VN
APN: internet
(cần xác nhận có cùng thông tin với GPRS hay không, sử dụng điện thoại có khác với USB không)

Wednesday 8 January 2014

Charge ipad on centos

wget https://github.com/mkorenkov/ipad_charge/archive/master.zip

unzip master.zip

And compile it:
cd ipad_charge-master
make
sudo make install
 
Notes: libusb and libusb-devel should be installed before this.

Friday 3 January 2014

Allow remote connection to mysql

1. Comment out the line here if any in file /etc/my.conf
#bind-address = 127.0.0.1

2. Restart mysql

3. Login mysql
mysql>GRANT ALL PRIVILEGES ON *.* TO username@ipaddress IDENTIFIED BY "password";

Friday 20 December 2013

convert mp3 to gsm/ulaw for Asterisk

# Install mpg123 to convert mp3 to wav file
mpg123 -w
; convert the output wav file to format that Asterisk can recognize
sox -v 0.9 input.wav -c 1 -r 8000  output.wav
; -v: reduce volume

Monday 16 December 2013

Install chan_mobile on ClearOS 5.2 SP2, Asterisk 1.8 and FreePBX 2.8

Source: http://samyantoun.50webs.com/asterisk/chan_mobile/

 
Install chan_mobile on ClearOS 5.2 SP2, Asterisk 1.8 and FreePBX 2.8

  • Legend (Variable and Scope)
    • PBX Pairing Password User
      PBX Name User
      Context User
      Bluetooth USB Device Name User
      MAC Address System
      ID System
      Mobile Phone MAC Address System
      Port System
      Number User
      ID User
  • ClearOS
    • Install Bluez
      • Yum
        • yum install -y bluez-utils bluez-libs bluez-libs-devel bluez-hcidump
      • Edit /etc/bluetooth/hcid.conf
        • Backup
          • cp -vf /etc/bluetooth/hcid.conf /usr/src/svn/hcid.conf.original
        • Clean (Optional)
          • sed -i '/^\t#/d;/^#/d;/^$/d' /etc/bluetooth/hcid.conf
        • Edit options Section
          • Change security user to security auto
            • sed -i 's/security user/security auto/' /etc/bluetooth/hcid.conf
          • Change passkey "BlueZ" to passkey "1234"
            • sed -i 's/passkey "BlueZ"/passkey "1234"/' /etc/bluetooth/hcid.conf
        • Edit device Section
          • Change name "%h-%d" to name "My PBX"
            • sed -i 's/name "%h-%d"/name "My PBX"/' /etc/bluetooth/hcid.conf
          • Change class 0x120104 to class 0x000100
            • sed -i 's/class 0x120104/class 0x000100/' /etc/bluetooth/hcid.conf
      • Service
        • service bluetooth start
    • Setup Bluetooth USB
      • Connect Bluetooth USB
      • Make Sure USB is connected
        • Test 1
          • Run Command
            • hciconfig -a
          • You should see something like this:
            • hci0: Type: USB
            • BD Address: 00:15:E9:66:BF:B6 ACL MTU: 192:8 SCO MTU: 64:8
            • UP RUNNING
            • RX bytes:949 acl:0 sco:0 events:23 errors:0
            • TX bytes:331 acl:0 sco:0 commands:22 errors:0
            • Features: 0xff 0xff 0x0f 0x00 0x00 0x00 0x00 0x00
            • Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
            • Link policy: RSWITCH HOLD SNIFF PARK
            • Link mode: SLAVE ACCEPT
            • Name: 'My PBX'
            • Class: 0x000100
            • Service Classes: Unspecified
            • Device Class: Computer, Uncategorized
            • HCI Ver: 1.1 (0x1) HCI Rev: 0x20d LMP Ver: 1.1 (0x1) LMP Subver: 0x20d
            • Manufacturer: Cambridge Silicon Radio (10)
        • Test 2
          • Run Command
            • hcitool dev
          • You should see something like this:
            • Devices:
            •     hci0   00:15:E9:66:BF:B6
    • Setup Mobile Phone
      • Make PBX discoverable:
        • dbus-send --system --type=method_call --print-reply --dest=org.bluez /org/bluez/hci0 org.bluez.Adapter.SetMode string:discoverable
      • Pair PBX
        • On the mobile phone, Search for devices (Nokia, Settings > Connectivity > Bluetooth > Paired devices > Add new device
        • You should find your PBX as My PBX. Pair with a pin of 1234
      • Make sure we can see your phone
        • Run Command
          • hcitool scan
        • You should see something like this:
          • Scanning ...
          •    FC:E5:57:EB:4A:87    MyMobile
  • Asterisk
    • Edit /etc/asterisk/mobile.conf
      • Create Config File
        • touch /etc/asterisk/mobile.conf
        • chown asterisk:asterisk /etc/asterisk/mobile.conf
        • chmod 664 /etc/asterisk/mobile.conf
      • Create [adapter] sections
        • echo "[adapter]
        • id=dlink01
        • address=00:15:E9:66:BF:B6" > /etc/asterisk/chan_mobile.conf
    • Search for your bluetooth devices from Asterisk. This command might take 8 - 10 seconds
      • Rum Commands
        • asterisk -r
        • module load chan_mobile.so
        • mobile search
      • You should see something like this:
        • Address            Name       Usable  Type   Port
        • FC:E5:57:EB:4A:87  My Mobile  Yes     Phone  13
    • Edit /etc/asterisk/mobile.conf
      • echo "[nokia_c1_01_01]
      • address=FC:E5:57:EB:4A:87
      • port=13
      • context=from-mobile-nokia-c1-01-01
      • adapter=dlink01
      • group= 1">> /etc/asterisk/mobile.conf
    • Show the status of configured devices, and whether or not the device is capable of sending / receiving SMS via bluetooth:
      • Run Command
        • mobile show devices
      • You should see something like this:
        • ID              Address            Group  Adapter  Connected  State  SMS
        • nokia_c1_01_01  FC:E5:57:EB:4A:87  1      dlink01  Yes        Free   No
  • FreePBX
    • Outgoing
      • Trunk
        • Create a custom trunk
        • Outbound Caller ID = 0123456789
        • Maximum channels = 1
        • Custom Dial String = Mobile/nokia_c1_01_01/$OUTNUM$
      • Outbound Route
        • As desired
    • Incoming
      • Edit /etc/asterisk/extensions_custom.conf
        • echo "
        • ;************* Mobile Nokia C1-01 01 ***************
        • [from-mobile-nokia-c1-01-01]
        • exten => s,1,Noop(Setting DID = 0123456789)
        • exten => s,n,Set(__FROM_DID=0123456789)
        • exten => s,n,Goto(from-trunk,0123456789,1)
        • exten => s,h,Hangup
        • ;*********** End Mobile Nokia C1-01 01 *************
        • " >> /etc/asterisk/extensions_custom.conf
      • Inbound Route
        • DID Number = 0123456789
  • Notes
    • Asterisk Mobile Commands
      • mobile cusd Send CUSD commands to the mobile
        mobile rfcomm Send commands to the rfcomm port for debugging
        mobile search Search for Bluetooth Cell / Mobile devices
        mobile show devices Show Bluetooth Cell / Mobile devices
    • To load or unload chan_mobile module
      • module load chan_mobile.so
      • module unload chan_mobile.so

Use an old Mobile Phone as a GSM Gateway in Asterisk

SOURCE: http://www.stocksy.co.uk/articles/Networks/use_an_old_mobile_phone_as_a_gsm_gateway_in_asterisk/

Like most people I carry a mobile phone, but mine is for emergencies only. Just a handful of people know the the number and that's how I like to keep it. Because I use Asterisk, I'm always reachable through my land line number which I route around between various destinations or voicemail depending on what suits me. I'm spoilt by this, so having my mobile phone ring unexpectedly at an inconvenient time is a bit intrusive.
But, increasingly, almost everyone I interact with wants my mobile number - employers, customers, banks, garages, insurance companies - if it doesn't start '07', they're not happy.
As usual I've decided to try a technical solution to a social problem. I began by using a 'personal use' 070 number which is designed for precisely the kind of single-number-reach setup I use. This 070 number was presented at my SIP provider, who would then route the calls to my Asterisk server across the internet. In the end, this proved to be unsatisfactory because many providers block the 070 range with the justification that it has been abused for premium-rate scams. For example, the number couldn't be dialled from T-Mobile or Orange. Shame.
Undeterred, I tried another approach. I now have an old spare mobile phone which never leaves the house and is permanently connected through bluetooth to Asterisk. This is a real mobile with a real mobile number. I simply feed any incoming calls to this mobile into a macro which handles the call in the same way as calls to my landline. If I want to take calls on my (real) mobile, I can. If I'm not available to take the call, the caller is passed to my Asterisk voicemail box. SMS text messages arrive as emails, my replies to which are sent by SMS. Having all my incoming calls and voicemail messages in one place is very convenient and it prevents me from missing calls when I am in the house and probably would not hear a mobile phone ringing.
Asterisk has included support for bluetooth connections to mobile phones and headsets for some time now. This is accomplished through chan_mobile. Not all phones are supported, so it's worth taking a look at voip-info.org's page which lists the confirmed compatible dongles and phones. I am getting good results with a D-Link DBT-120 dongle and a Nokia E72, 6306i, 6021 handsets, however only the 6021 works with SMS. It is worth noting that each bluetooth dongle can support only one mobile device - this is an annoying limitation of chan_mobile, but it's not as though USB dongles are very expensive.

How it's Done

chan_mobile is an addon, so it needs to be enabled before Asterisk is compiled. On Debian, it's pretty simple, just add a few packages:
# apt-get install bluez-utils bluez-hcidump libbluetooth-dev
then, go to your Asterisk source directory and use make menuselect to enable chan_mobile. It's in Add-ons -> chan_mobile:
# cd /usr/src/asterisk-1.8.11.0
# ./configure && make menuselect
Whilst it compiled and installed OK, I had to make a modification to the chan_mobile source before it would recognise my phone:
# vi /usr/src/asterisk-1.8.11.0/addons/chan_mobile.c

Find this:
 addr.rc_channel = (uint8_t) 1;

Replace with:
 addr.rc_channel = (uint8_t) 0;
Build Asterisk and (re)install:
# make && make install
In order to use a bluetooth-connected phone as a GSM gateway, it's necessary to pair the phone with the Asterisk server. In Debian, this can be accomplished painlessly through the CLI. First, make your phone discoverable and then scan for it:
# hcitool scan
Scanning ...
 EC:1B:6B:64:C2:88 Trollphone
Make a note of the MAC address. In order to pair, a helper is required to handle the PIN. Run the helper in the background and begin the pairing process:
# bluetooth-agent 7472 &
# rfcomm connect hci0 EC:1B:6B:64:C2:88
Once the pairing has succeeded, make sure your phone is configured to automatically accept connections for this paring in future. You can verify that the paring is working at any time by running:
# hcitool con
Connections:
 < ACL EC:1B:6B:64:C2:88 handle 41 state 1 lm MASTER AUTH ENCRYPT
Now, Asterisk needs to be configured to use the paired phone. We need to know which rfcomm channel offers the voice service. The easiest way is to use chan_mobile:
# rasterisk
*CLI> module load chan_mobile.so
Don't worry about any errors loading the module, it'll do for now:
*CLI> mobile search 
EC:1B:6B:64:C2:88 Trollphone                     Yes    Phone   2
In this case it is rfcomm channel 2. In addition, we need to know the MAC address of the bluetooth dongle installed in the Asterisk server. Exit the Asterisk CLI and use hcitool:
# hcitool dev
Devices:
 hci0 00:81:C5:33:25:A4
At last we have all the information needed. Edit or create the chan_mobile configuration file:
# vi /etc/asterisk/chan_mobile.conf

[Adapter]
address = 00:81:C5:33:25:A4
id = pabx

[Trollphone]
address = EC:1B:6B:64:C2:88
port = 2
context = from-trollphone
adapter = pabx
You will need something in the dialplan to handle this, at minimum something like:
# vi /etc/asterisk/extensions.conf

[from-trollphone]
exten => s,1,Dial(SIP/100)

[my-phones]
exten => *12,1,Dial(MOBILE/Trollphone/150)
When the mobile rings, you should get a call on SIP extension 100. Dialling *12 will cause the phone to dial 150, which in my case gives me Orange customer services. I'm sure you get the idea.

What about SMS?

Trickier, but there is a solution. None of the phones I had spare were supported by chan_mobile's SMS capabilities. According to the chan_mobile wiki page, only three phones are known to support SMS: the Nokia models E51, 6021 and 6230i. Of the three, the 6021 seems to be the most widely available - I was able to get three of them from eBay for just a few pounds.
Once the phone is paired in the normal way, it will send any incoming SMS messages to Asterisk over the bluetooth connection. Asterisk looks for an 'sms' extension in the context you specified in chan_mobile.conf. I suggest something like this in your dialplan:
[from-trollphone]
exten => sms,1,Verbose(Incoming SMS from ${SMSSRC} ${SMSTXT})
exten => sms,n,System(echo "To: stocksy@stocksy.co.uk" > /tmp/smsmail)
exten => sms,n,System(echo "Subject: SMS from ${SMSSRC}" >> /tmp/smsmail)
exten => sms,n,System(echo "${SMSTXT}" >> /tmp/smsmail)
exten => sms,n,System(sendmail -t -f ${SMSSRC}@sms.stocksy.co.uk < /tmp/smsmail)
exten => sms,n,Hangup()
At first, incoming messages were all arriving with a blank ${SMSSRC}, the easy solution was to apply a patch and re-compile:
# cd /usr/src/asterisk-1.8*
# wget --no-check-certificate https://issues.asterisk.org/jira/secure/attachment/42026/sms-sender-fix.diff
# patch -p0 < sms-sender-fix.diff
# ./configure && make && make install
Now, incoming messages are delivered to me as emails claiming to be from +MOBILENUMBER@sms.stocksy.co.uk. Obviously, this requires the Asterisk system to have a working MTA, the setup of which I won't cover here. If you don't have an MTA at present, take a look at postfix.
Outgoing SMS messages are more work because it's necessary to parse the contents of the email message, the format of which will be a little less predicatable than an SMS. I elected to use python to do this because it already has a library to do this.
#!/usr/bin/env python
# (:? YOUR SCRIPT IS BAD AND YOU SHOULD FEEL BAD! (:?
# I'M NOT A DEVELOPER AND THIS IS PROBABLY VERY, VERY BAD, but it does work.
# email2sms.py James Stocks
# based upon emailspeak.py by sysadminman - http://sysadminman.net
# v0.0  2012-04-28


# Import libs we need
import sys, time, email, email.Message, email.Errors, email.Utils, smtplib, os, socket, random, re
from datetime import date
from email.Iterators import typed_subpart_iterator
from time import sleep

# Asterisk Manager connection details
HOST = '127.0.0.1'
PORT = 5038
# Asterisk Manager username and password
USER = 'your-ast-man-user'
SECRET = 'dysmsdvsa'

# Generate a random number as a string. We'll use this for file names later on
callnum = str(random.randint(1, 100000000))

# Taken from here, with thanks -
# http://ginstrom.com/scribbles/2007/11/19/parsing-multilingual-
# email-with-python/
def get_charset(message, default="ascii"):
    """Get the message charset"""

    if message.get_content_charset():
        return message.get_content_charset()

    if message.get_charset():
        return message.get_charset()

    return default

# Taken from here, with thanks -
# http://ginstrom.com/scribbles/2007/11/19/parsing-multilingual-
# email-with-python/
def get_body(message):
    """Get the body of the email message"""

    if message.is_multipart():
        #get the plain text version only
        text_parts = [part
                      for part in typed_subpart_iterator(message,
                                                         'text',
                                                         'plain')]
        body = []
        for part in text_parts:
            charset = get_charset(part, get_charset(message))
            body.append(unicode(part.get_payload(decode=True),
                                charset,
                                "replace"))

        return u"\n".join(body).strip()

    else: # if it is not multipart, the payload will be a string
          # representing the message body
        body = unicode(message.get_payload(decode=True),
                       get_charset(message),
                       "replace")
        return body.strip()

# Read the e-mail message that has been piped to us by Postfix
raw_msg = sys.stdin.read()
emailmsg = email.message_from_string(raw_msg)

# Extract database Fields from mail
msgfrom = emailmsg['From']
msgto =  emailmsg['To']
msgsubj = emailmsg['Subject']
msgbody = get_body(emailmsg)

# Find the part of the 'To' field that is the phone number
phonenum = re.match( r'\+?([0-9]+)', msgto, re.M)

# Whose mobile is this?
mobile = sys.argv[1]

# Write a log file in /tmp with a record of the e-mails
currtime = date.today().strftime("%B %d, %Y")
logfile = open('/tmp/email2sms.log', 'a')
logfile.write(currtime + "\n")
logfile.write("Call Number: " + callnum + "\n")
logfile.write("From: " + msgfrom + "\n")
logfile.write("To: " + msgto + "\n")
logfile.write("Subject: " + msgsubj + "\n")
logfile.write("Body: " + msgbody + "\n\n")
logfile.close()

# Send the call details to the Asterisk manager interface
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
sleep(1)
s.send('Action: login\r\n')
s.send('Username: ' + USER + '\r\n')
s.send('Secret: ' + SECRET + '\r\n\r\n')
sleep(1)
s.send('Action: originate\r\n')
# Dummy channel - I don't actually want any phones to ring
s.send('Channel: LOCAL/1@sms-dummy\r\n')
s.send('Context: mobiles\r\n')
s.send('Exten: ' + mobile + '\r\n') 
s.send('WaitTime: 30\r\n')
# This is a bogus value, but the field is required
s.send('CallerId: 5555\r\n')
# Do not wait for response from dummy channel
s.send('Async: true\r\n')
s.send('Priority: 1\r\n')
# The variables ${SMSTO} and ${SMSBODY} are used in the dialplan
s.send('Variable: SMSTO=' + phonenum.group(1) + ',SMSBODY=\"' + msgbody + '\"\r\n\r\n')
sleep(1)
s.send('Action: Logoff\r\n\r\n')
#Omitting this causes "ast_careful_fwrite: fwrite() returned error: Broken pipe"
sleep(3)
s.close()
Copy the above script to /usr/sbin/email2sms.py and make executable:

# chmod +x /usr/sbin/email2sms.py
The script uses the Asterisk Manager Interface, so it will need an AMI user. Append this to manager.conf:
# vi /etc/asterisk/manager.conf

[your-ast-man-user]
secret=dysmsdvsa
read=call,user,originate
write=call,user,originate
and also make sure it is enabled in the general section:
# vi /etc/asterisk/manager.conf

[general]
enabled = yes
webenabled = yes
port = 5038
You'll note that I'm using the context 'mobiles'. You'll need to make sure that the extensions you'll be using exist in this context in extensions.conf:
# vi /etc/asterisk/extensions.conf

exten => stocksy,1,MobileSendSMS(JS6021,${SMSTO},${SMSBODY})
exten => karen,1,MobileSendSMS(trollphone,${SMSTO},${SMSBODY})
Secondly, there is a dummy extension which the 'call' needs to connect to. A NoOp isn't quite sufficient, I could only get it to work if the extension answered and then did something, in this case answer and wait 10 seconds:
# vi /etc/asterisk/extensions.conf

[sms-dummy]
exten => 1,1,Answer()
exten => 1,n,Wait(10)
exten => 1,n,Hangup
Reload Asterisk to pick up the changes.
So, calling email2sms.py with the argument 'stocksy' uses the JS6021 mobile, and calling it with 'karen' uses the trollphone mobile.
You need to make sure that email for the domain you have chosen - in my case sms.stocksy.co.uk - is routed to the Asterisk box. This will normally be accomplished by creating an MX record or creating a transport for the domain on your mail server. Again, I'm not going to cover that part here, but I will cover how to pipe the incoming messages into the python script.
Assuming that you are using postfix, you'll need a new transport for each mobile you want to use. In my case:
# vi /etc/postfix/master.cf

sms-stocksy unix -      n       n       -       -       pipe
  flags=FR user=stocksy argv=/usr/sbin/email2sms.py stocksy

sms-karen unix  -       n       n       -       -       pipe
  flags=FR user=stocksy argv=/usr/sbin/email2sms.py karen
postfix needs to know that it must use these transports for SMS domains:
# vi /etc/postfix/transport ; postmap /etc/postfix/transport

sms.stocksy.co.uk sms-stocksy
sms.herdomain.co.uk sms-karen
If postfix doesn't already have a transport_maps setting, create one. Obviously this could break any existing postfix setup you might have, but if so I'm expecting you to know what you're doing:
# postconf -e transport_maps=hash:/etc/postfix/transport
Restart postfix and that should be all that's necessary.
# /etc/init.d/postfix restart
You need to satisfy yourself that you are not allowing the entire world to relay through your SMS gateway! Understand and make use of postfix's security features! Don't wait until you've racked up a collosal SMS bill! Loud noises!
If things aren't quite working, start by checking your mail log:
# tail -f /var/log/mail.log
You can do a packet trace to see what's happening on the Asterisk Manager Interface:
# tcpdump -A -i lo port 5038
Try talking to the AMI directly:
$ nc localhost 5038

Action: login
Username: your-ast-man-user
Secret: dysmsdvsa

Action: originate
Channel: LOCAL/1@sms-dummy
Context: mobiles 
Exten: stocksy
WaitTime: 30
CallerId: 5555
Async: true
Priority: 1
Variable: SMSTO=5555555555,SMSBODY="foo"

Action: Logoff
Watch out for whitespace in the AMI - exten 'stocksy' != 'stocksy '.
Good luck.

Tuesday 10 December 2013

Stop SIP Flood Attack

 Source:http://kb.smartvox.co.uk/asterisk/friendlyscanner-gets-aggressive/

Not so friendly after all

In my October 2010 articles about Asterisk IP-PBX security (linked here), I described how port scanning probes from the so-called “friendly-scanner” could be seen several times a day on a typical SIP server exposed to the Internet. Since then, I – or at least one of my clients – had the displeasure of experiencing the full fury of this remarkably unfriendly scanner which, when provoked, seems to change from a gentle prod every few hours to a full scale Denial of Service attack at a rate of more than 80 SIP REGISTER requests per second, utterly relentless and lasting for days or even weeks. 
The port scanning probes used SIP OPTIONS while the really unpleasant, full-on, bandwidth-eating manifestation uses SIP REGISTER requests. The fact that in both cases the User Agent is declared to be “friendly-scanner” does not mean that this is a single application operating in two different modes. It probably indicates that some of the source code for these loathsome applications was derived from a common ancestor or that one is a re-worked version of the other. I believe sipvicious and a python program called svwar.py may have the dubious honour of being in some way the original seed for what has now turned into an irritating and potentially costly problem for VoIP users around the world. But should we blame gun manufacturers when there is an armed robbery or illegal shooting? Perhaps not. Anyway, I digress. 

Symptoms of an attack

My client called me to say that their remote users were experiencing serious problems with their connection to the Asterisk phone system at the office. My own phone refused to register using exactly the same credentials as had worked a few days earlier. I tried to use remote access to check the server, but the connection was dreadfully slow to the point where it was unusable. 
Making sense of what was happening was difficult because there did not seem to be any unauthorised calls and the internal office extensions were all working fine as were the analogue trunks that they use for inbound calls and as a backup in case of Internet problems. I knew the phone account passwords were all sufficiently strong and complex to not be hacked and other security settings such as “alwaysauthreject=yes” were configured for maximum resistance to attack, yet the firewall logs showed that there was a continuous heavy use of bandwidth from the Asterisk PBX to some address on the Internet. The fact that the outbound traffic was using approximately four times the bandwidth of the inbound made me think it must be some malware running on the server. This misconception caused me a considerable delay before I finally thought to run tcpdump and see exactly what was going on. By the way, the Asterisk CLI command “sip set debug on” will also show what is happening, but you may then find it difficult to turn off the sip debug because of the rate at which information is being written to the screen. Running “tcpdump udp -nn” at the Linux command prompt is safer because it just writes one line to the screen per request and Control-C is all that is required to stop it.
The outbound UDP packets outnumbered the inbound because Asterisk was sending a rejection for each registration attempt and then re-sending it when it didn’t get an ACK response – it would send as many as 5 responses to every one inbound REGISTER request. With inbound requests running at nearly 100 per second this was causing it a bit of a headache. 

Blocking the attack

As soon as I realised what was happening, it was relatively simple to add a firewall rule to block all inbound data from the single IP address that was sending the requests. Yes, it was all from one IP address and No, contacting the owners of that address was as much use as a chocolate teapot. 
As soon as I blocked the inbound requests, the remote users were suddenly able to make calls again and everything went quiet. Job done I thought. Well, not quite. 

It just carried on and on

I assumed the attack would stop pretty quickly once the inbound packets were blocked at the firewall and no responses were coming back from Asterisk. Not so. I checked the traffic monitor on their firewall the next day and the day after. The inbound stream of requests was still there. After a week, the firewall began to creak and get sick because it was running out of memory. Well it is only a modest little Draytek router, but it is designed for a small business environment and should have been able to cope with the simple task of blocking a continuous stream of unwanted SIP requests coming from one IP address on the Internet. In my opinion, someone at Draytek should be shot for designing a router/firewall that adds an entry to the NAT sessions table before it inspects the firewall rules to see if the source address is blocked! 
So a quick solution at this point was to add a rule to iptables on the Asterisk box and let the requests come through the Draytek. That took the pressure off the Draytek, but no matter what ICMP response I sent back (including no response), the requests just kept flooding in. If anything, they were getting faster and using more bandwidth (see graph below). 
I am now convinced that the unending nature of the attack is not deliberate, but is as a result of a bug in the code which puts it into an infinite loop. Clearly the people who produced these friendly-scanner hacking tools aren’t  as clever as they would no doubt like to believe. 

How to stop it completely

The answer was in a blog by Joshua Stein, to whom I am indebted. His solution involved redirecting the requests to a new port so it would not be necessary to shut down the Asterisk PBX application. However, my client didn’t need 24×7 operation of their phone system so instead I just modified Joshua’s Ruby script to use port 5060, stopped Asterisk, ran the Ruby script and that was it. The requests just stopped. Then I restarted Asterisk. This graph from the firewall shows the bandwidth being used over a week and the abrupt end of the problem when I finally ran Joshua’s script. 
Internet bandwidth as a graph during friendly scanner attack
Graph of Internet bandwidth

Using Joshua’s Ruby script on a CentOS server

Install Ruby using yum: yum install ruby 
Copy the script from the box below and paste it into a file. I called my file spoof_sip_ok. (If you use a text editor like vi or nano while connected through SSH with Putty, then a right-click of the mouse will paste text previously copied into the clipboard). The original script is no longer available at Joshua’s own blog site, so I have reproduced the whole thing here with a couple of minor adjustments: 
#!/usr/bin/env ruby
require "socket"

s = UDPSocket.new
s.bind("0.0.0.0", 5060)
while true
  packet = s.recvfrom(1024)

  via = packet[0].match(/Via: (.+);rport/)[1]
  from = packet[0].match(/From: (.+)/)[1]
  to = packet[0].match(/To: (.+)/)[1]
  call_id = packet[0].match(/Call-ID: (.+)/)[1]
  cseq = packet[0].match(/CSeq: (\d+) REGISTER/)[1]

  remote_ip = packet[1][3]
  remote_port = packet[1][1].to_i

  puts packet.inspect

  if packet[0].match(/^REGISTER /)
    ret = "SIP/2.0 200 OK\r\n" +
      "Via: #{via};received=#{remote_ip}\r\n" +
      "From: #{from}\r\n" +
      "To: #{to}\r\n" +
      "Call-ID: #{call_id}\r\n" +
      "CSeq: #{cseq.to_i + 1} REGISTER\r\n" +
      "\r\n"

    puts "sending to #{remote_ip}:#{remote_port}:\n#{ret}"

    s.send(ret, 0, remote_ip, remote_port)
  end
end
 
 
You can insert your own server’s IP address in the s.bind parameters if you want, but 0.0.0.0 should just bind to all interfaces. Also remember to make the file executable, for example using the Linux command chmod 755 spoof_sip_ok
The original article was at “http://jcs.org/notaweblog/2010/04/11/properly_stopping_a_sip_flood”, but the whole domain seems to no longer be active (as of March 2013).
Before you run the above version of the script, make sure Asterisk is stopped. I found it would immediately restart when I used ”amportal stop” and instead used the CLI command “stop now”. You can check that it has stopped by typing this command at the Linux command prompt: netstat -lunp 
If Asterisk is running, it will be using port 5060 and the output of the netstat command would look like this: 
user@asterisk:~ $ netstat -lunp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address     Foreign Address   State    PID/Program name
udp        0      0 0.0.0.0:5060      0.0.0.0:*                  16301/asterisk

To run the Ruby script, just type ./spoof_sip_ok at the Linux prompt.

Thursday 28 November 2013

Tìm hiểu thêm về acquy & ups

SOURCE: http://www.powerload.vn/news/detail/acquy,-accu,-binh-dien-30.html




Chào các bạn,
Sau đây là một số thuật ngữ được dùng nhiều trong acquy và ups.
Dung lượng của acquy (accu) là lượng điện (điện tích) mà accu đó sau khi đã được nạp đầy sẽ phát ra được trước khi hiệu điện thế giảm xuống đến mức ngừng. Mức ngừng là mức mà không nên để acquy phát điện tiếp, nếu cứ để acquy phát điện ở dưới mức ngừng thì sẽ giảm tuổi thọ, thậm chí có thể làm acquy hỏng ngay. Đó là trường hợp dùng nhiều acquy mắc nối tiếp nhau khi 1 hay nhiều acquy trong dãy đó đã phát hết điện mà những cái khác chưa hết điện và ta tiếp tục dùng thì cái hết điện trước sẽ bị đảo cực và hỏng hoàn toàn. Với acquy acid chì thì mức ngừng là 1,67V cho mỗi ngăn (cell) (10V đối với acquy 12VDC)
Coulomb là đơn vị đo điện tích. Đại lượng điện tích không phụ thuộc vào điện thế của acquy. 1 Coulomb = 1 Ampere * 1 sec: như vậy cũng có thể dùng Ampere * second để chỉ đại lượng điện tích. Tụ điện (Capacitor) cũng có chức năng như acquy. Đơn vị đo điện dung của tụ điện là Farad, lấy từ tên nhà khoa học Michael Faraday. 1 Farad = 1 Coulomb / 1 Volt.
Đơn vị đo điện tích acquy thường dùng trong thực tế là Ah (Ampere * hour).
Thông số điện tích của acquy do nhà sản xuất công bố thường được tính khi phát điện với dòng điện nhỏ trong 20 giờ (20Hr). Ví dụ acquy 100Ah sẽ phát được dòng điện 5A trong 20 giờ. Khi dòng điện phát ra càng lớn thì thời gian phát điện càng ngắn. Các bạn nên xem bảng thông số kỹ thuật chi tiết của sản phẩm do nhà máy công bố trước khi chọn mua hàng. Tại trang www.powerload.vn, các sản phẩm hầu hết được đính kèm file .pdf thông số kỹ thuật trong phần "chi tiết sản phẩm" ngay bên dưới hình ảnh của sản phẩm khi xem chi tiết.
Sau đây là câu chuyện có thật, xin được chia sẽ:
Có một bác nọ mua một UPS dùng điện áp charge là 12VDC và một chiếc acquy 12V-65Ah để dùng cho một chú laptop IBM T61. Sau khi xả tải (dùng điện acquy để cấp nguồn cho con T61 (75w) được hơn 6 giờ. Bác ấy gọi điện cho em thắc mắc: "tại sao pin của laptop bé tí tẹo (nằm gọn trong lòng bàn tay) mà xài được 3 giờ, trong khi cái acquy nặng 23 cân chỉ xài được có 6 giờ là thế nào?".
Điện thế của acquy là DC (một chiều), trong khi điện lưới là AC (xoay chiều). UPS phải dùng inverter để chuyển đổi điện từ 12VDC lên 220VAC rồi mới cấp cho adaptor của máy laptop. Chắc là bác ấy lấy điện tích của acquy đó (65Ah) chia cho dòng điện cấp cho máy tính T61 (khoảng 3.4A) = 19 giờ.