Tuesday, September 20, 2016

Three Minutes Daily Vim Tip: Indentation

Say you want to indent a block of code inside curly brackets. There are a couple of ways to do this. Before we run the commands, make sure to place your cursor inside the block of curly brackets.

>i{
>i}

The two commands above will indent the code inside the curly brackets. Specifically > indicates indentation, i indicates inside, and { or } indicates curly brackets.

You could of course make small manipulations, for example use < for de-indentation, and use any one of (){}[]<> after i for corresponding types of brackets/parenthesis.

Another way is to use vim's re-indentation feature, which will automatically adjust indentation by its own. Again, you will need to make sure to place the cursor within the block to run the following:

=i{

The first character = indicates re-indentation, and the rest should be identical to the previous context.

Finally, you may also re-indent the entire file by

gg=G

where gg places your cursor to the beginning of the file, and G indicates all the lines till the end of the file.

Sunday, September 18, 2016

How to Monitor CPU Temperature from OS X Terminal

You could of course install some Mac OS X apps that can do this, probably at some small fee or ads. Well, here is a much better and non-intrusive method for that, thanks to lavoiesl of github.

First, download osx-cpu-temp from github:
$ git clone https://github.com/lavoiesl/osx-cpu-temp.git

Compile, and install.
$ cd osx-cpu-temp
$ make
$ sudo make install

To run, simply run
$ osx-cpu-temp
55.2°C

That's it!

Friday, September 16, 2016

How to List Sizes of Directories or Folders in Linux

When you use
$ ls -lh
it only displays the sizes of files, but not the directories or folders.

Here is how to list the sizes of directories or folders:
$ du -sh *

Very handy!

Thursday, September 15, 2016

How to Open up Ports for Web Server with IPTABLES

I have a personal VPN server that I also want to setup as a web server. The VPN server is configured with iptables to drop all other connections, including TCP 80 (HTTP) and TCP 443 (HTTPS). So, here is how to open up those two ports.

Edit /etc/iptables.rules and insert two lines (green) as shown below:
...
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m conntrack --ctstate INVALID -j DROP
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -d 127.0.0.0/8 -j REJECT
-A INPUT -p icmp -j ACCEPT
-A INPUT -p udp --dport 67:68 --sport 67:68 -j ACCEPT
-A INPUT -p tcp --dport 22 -j ACCEPT
-A INPUT -p udp -m multiport --dports 500,4500 -j ACCEPT
-A INPUT -p udp --dport 1701 -m policy --dir in --pol ipsec -j ACCEPT
-A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
-A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT
-A INPUT -p udp --dport 1701 -j DROP
-A INPUT -j DROP
-A FORWARD -m conntrack --ctstate INVALID -j DROP
...

Your iptables.rules configuration is probably different from mine, but just make sure to add the two lines in green. Just make sure that these two lines should be inserted before the lines with DROP.

Next, reload the iptable
$ sudo iptables-restore < /etc/iptables.rules

That's it!

How to Extract Attachments from Gmail and Save to Files

This is a follow-up post from my previous post on how to retrieve messages from Gmail.

In order to save attached files, you just need to modify ~/.procmailrc file to read something like:
# First Recipe
:0HB
* ^(From).*(SOMEBODY)
* filename=
* ^Content-Disposition: attachment;
| munpack -q -C /WHERE/TO/SAVE

# Second Recipe
:0
/dev/null

The first recipe will filter out those mails from SOMEBODY with attachment(s) and save the file(s) to /WHERE/TO/SAVE folder. Make sure that you have mpack installed on the system:
$ sudo apt-get install -y mpack

The second recipe will simply discard all messages afterward. Therefore, nothing but the attachments will be saved locally.

Tuesday, September 13, 2016

How to Retrieve Emails from Gmail Periodically and Save as Files in Linux

In this tutorial, I will go over my own attempt to automate a process for fetching gmail and saving as files. This post is heavily based on the tutorial here with some modifications.

IMPORTANT:
In order for this to work, you will need to enable POP in Gmail setting.

You will also need to go to Google Account Security page and disable 2-step verification and turn on the option that allows less secure app.


First, install some necessary software:
$ sudo apt-get install -y fetchmail procmail openssl ca-certificates

Next, create ~/.fetchmailrc file and edit it with the following content
poll pop.gmail.com
with proto POP3
user "GMAIL_USERNAME@gmail.com"
there with password "YOUR_PASSWORD"
is "LINUX_USERNAME" here
mda "/usr/bin/procmail -f %F -d %T"
options
no keep
ssl
sslcertck
sslcertpath /etc/ssl/certs

Note that LINUX_USERNAME should be exactly what you would get from the following command:
$ echo $USER

Since your password is saved as a plain text, you will need to make sure to set read/write flags only for the owner:
$ chmod 600 ~/.fetchmailrc

Now, we need to configure procmail. Create ~/.procmailrc file and edit it with the following content:
# Environment variable assignments
PATH=/bin:/usr/bin:/usr/local/bin
VERBOSE=off                   # Turn on for verbose log
MAILDIR=$HOME/Mail            # Where Procmail recipes deliver
LOGFILE=$HOME/.procmaillog    # Keep a log for troubleshooting.
# Recipes
:0:
* ^(From).*(SOMEBODY)
$MAILDIR/SOMEBODY

This configuration will have procmail filter out any mails from SOMEBODY and save the message by appending to the file ~/Mail/SOMEBODY. Make sure to create the folder where it will be saved to:
$ mkdir ~/Mail

What about any other messages? They should be saved to path pointed by $MAIL, which we will need to specify. Edit ~/.bashrc to append the following line:
MAIL=/var/spool/mail/$USER && export MAIL

Let the change take effect immediately
$ source ~/.bashrc

Well, looks good. Let's test out. Run
$ fetchmail
2 messages for xxx@gmail.com at pop.gmail.com (3998 octets).
reading message xxx@gmail.com@gmail-pop.l.google.com:1 of 2 (3383 octets) flushed
reading message xxx@gmail.com@gmail-pop.l.google.com:2 of 2 (615 octets) flushed
You have new mail in /var/spool/mail/linuxnme

If your message is sent from SOMEBODY, it will be saved into ~/Mail/SOMEBODY file. If not, it will be saved to /var/spool/mail/$USER file. Open up these files and see if you are receiving the messages.

Finally, to schedule fetchmail every 5 minute, do the following:
$ crontab -e

Append the following line:
*/5 * * * * /usr/bin/fetchmail &> /dev/null

By the way, if you want fetching to run system-wise, edit /etc/crontab file instead.

Transition from Ubuntu to FreeBSD - sh, csh, bash

FreeBSD 10.3 comes with sh and csh in the base distribution. In fact, root's default shell is csh whereas a normal user default shell is sh.

It is possible to install bash by
# pkg install -y bash
...
======================================================================

bash requires fdescfs(5) mounted on /dev/fd

If you have not done it yet, please do the following:

mount -t fdescfs fdesc /dev/fd

To make it permanent, you need the following lines in /etc/fstab:

fdesc /dev/fd fdescfs rw 0 0

======================================================================

Because bash, derived from Linux world, may utilize fdescfs, some bash scripts may not properly run on FreeBSD unless it is mounted as mentioned above. For this reason, I decided not to stick with bash on FreeBSD, as learning BSD as BSD, not Linux, is the whole purpose.

However, I immediately changed root's default shell as sh, as I csh is just too different from bash. For instance, one needs to use setenv in place of export in csh.

To change default shell to sh, run
# chsh -s /bin/sh
and change the default shell from /bin/csh to /bin/sh

Note: do not change root's default shell as anything other than those included in the base distribution. Read here for more details.

Transition from Ubuntu to FreeBSD - root, su, sudo

In this series of posts, I will write my own attempt to transition from Linux (Ubuntu) to BSD (FreeBSD).

In Ubuntu, the security model is to invoke sudo command whenever root privilege is required. On the contrary, one needs to login as root using su - command. In fact, only those who are in the wheels group can login as root with su command.

A user not in wheels group cannot login as root:
$ su -
su: Sorry

To manually add a user, say unixnme, to wheels group, one needs to edit /etc/group to read something like
wheel:*:0:root,unixnme
...
operator:*:5:root,unixnme
...

Note that root is in the operator group as well. The operator group will have access to devices, so I might as well add to this group as well.

Now, the user can issue
$ su
or
$ su -
commands to login as root.

By the way, if one prefers the Ubuntu way with sudo command, it can be done.
Install sudo
# pkg install -y sudo

Add to sudoer by editing /usr/local/etc/sudoers to read something like
...
root ALL=(ALL) ALL
unixnme ALL=(ALL) ALL
...

That's it!

How to Compile From Sources with Debug Symbols

Say you want to debug vim. If you install vim using apt-get install command, it will install binary, which does not include debug symbol. Here is how to compile a program, for example vim, from source and compile with debug symbols.

First, un-comment lines that start with deb-src in /etc/apt/sources.list file.

Next, update the sources list
$ sudo apt-get update

Download source files
$ apt-get source vim
Note that I am issuing apt-get without sudo command.

Move to the vim directory and configure with -g option
$ cd vim_7.4.1689
$ ./configure CFLAGS='-g'

This -g option is important, as this will tell gcc to compile with debug symbols. If you need to tweak more options, run the following for help:
$ ./configure --help

Finally, make and install.
$ make -j4
$ sudo make install

How to Debug a Running Process Using GDB

Let's say you want to debug vim when run with sudo command, for example:
$ sudo vim /etc/fstab

It is easy to debug vim directly, but how would you do it when run with sudo? Well, here is one way to do it.

First, I will assume that you have vim executable file debug symbols. To find out how to compile vim with debug symbol, please refer to here. Say the file path is /usr/local/bin/vim.

Next, run the command that you want in one terminal:
$ sudo /usr/local/bin/vim /etc/fstab

Now, open up another terminal, and search for your vim process:
$ ps aux | grep vim
root     24687  0.0  0.0  63144  4212 pts/6    S+   19:04   0:00 sudo /usr/local/bin/vim /etc/fstab
root     24688  0.0  0.0  34180  5684 pts/6    S+   19:04   0:00 /usr/local/bin/vim /etc/fstab
linuxnme 24692  0.0  0.0  22572   988 pts/0    S+   19:04   0:00 grep --color=auto vim

We see two processes by root, one is sudo and the other is /usr/local/bin/vim, which is precisely what we want to debug, and its pid is 24668. To attach gdb to this process,
$ sudo gdb /usr/local/bin/vim 24688 -q
Reading symbols from /usr/local/bin/vim...done.
Attaching to program: /usr/local/bin/vim, process 24688
...
(gdb) 

Note that we are issuing sudo command before gdb here because we need superuser privilege to debug the process run by root.

Happy hacking!