Category Archives: FreeBSD

BIND: HOWTO Close an Open DNS

BIND 9.9.7
BIND 9.9.5

Book: ZyTrax Pro DNS and BIND

Time-to-Live (TTL) Values
Start of Authority Resource Record (SOA)
BIND Time formats
IPv6 Address Record (AAAA)
HOWTO Close an Open DNS
DNS BIND Query Statements
DNS Configuration Types
DNS Sample BIND Configurations
$ORIGIN, @ and blank Substitution
DNS BIND9 logging Clause

    #s = seconds = # x 1 seconds (really!)
    #m = minutes = # x 60 seconds
    #h = hours = # x 3600 seconds
    #d = day = # x 86400 seconds
    #w = week = # x 604800 seconds

Problems

nslookup not found in FreeBSD 10

# pkg install bind-tools

May you please add alias for nslookup?
FreeBSD 10 sysinstall, nslookup

named: the working directory is not writable

# chown -R bind:bind /var/named/etc/namedb

named: the working directory is not writable

open: /usr/local/etc/rndc.key: file not found

# rndc-confgen -a

Bind does not provide /etc/rndc.key

Stopping named: rndc failed, trying killall: .


Die Verwendung von rndc
Using rndc
Stopping named: rndc failed, trying killall: .

rndc: ‘stats’ failed: permission denied

options {
    dump-file       "/var/named/dump/named_dump.db";
    statistics-file "/var/named/stats/named.stats";
};

rndc works, but rndc stats doesnt
rndc dumpdb could not open dump file

Howto

DNS-Request

- autoritativ (der Server holt die Daten aus einer lokalen Zonendatei)
- nicht-autoritativ
  o rekursiv (der Server holt die Daten von einem anderen Nameserver)
  o iterativ (der Server antwortet mit einem oder mehreren Verweisen
              oder einem Resource Record auf andere Nameserver)

Rekursive und iterative Namensauflösung

recursion
If yes, and a DNS query requests recursion, then the server will attempt to do all the work required to answer the query. If recursion is off and the server does not already know the answer, it will return a referral response. The default is yes. Note that setting recursion no does not prevent clients from getting data from the server’s cache; it only prevents new data from being cached as an effect of client queries. Caching may still occur as an effect the server’s internal operation, such as NOTIFY address lookups. See also fetch-glue above.

fetch-glue
This option is obsolete. In BIND 8, fetch-glue yes caused the server to attempt to fetch glue resource records it didn’t have when constructing the additional data section of a response. This is now considered a bad idea and BIND 9 never does it.

BIND 9 Configuration Reference

Configuring an Authoritative-Only Name Server

Problem
You want to configure an “authoritative-only” or nonrecursive name server.
Cooking with DNS & BIND

Wireshark

(dns) && (dns.qry.type == 1)   => Record type A
$ tcpdump -s 1500 -p 53 -w output.pcap
-s <number>   number in bytes per packet
-w <file>     output file
-p <number>   port number (ex. 53 = DNS)

List of DNS record types

Fail2Ban

Fail2Ban
DNS Root Query Amplification with Fail2Ban
Fail2Ban with FreeBSD
Integrating PF with Fail2ban 0.9

Tutorials

A Nonrecursive Name Server, O’Reilly DNS and BIND
How to Disable External DNS recursion?
Configuring Bind Non Recursive
Wikipedia: Rekursive und iterative Namensauflösung
What is a “recursive DNS query”?

# /usr/sbin/named -t /var/named -u bind -fg
-t chroot() to directory after processing the command line arguments
-u setuid() to user after completing privileged operations
-f Run the server in the foreground
-g Run the server in the foreground and force all logging to stderr
recursion  no;

# /usr/sbin/named -t /var/named -u bind -fg
05-Aug-2013 19:58:10.872 starting
05-Aug-2013 19:58:10.876 listening on IPv4 interface em0, 1.2.3.4#53
05-Aug-2013 19:58:10.877 listening on IPv4 interface lo0, 127.0.0.1#53
05-Aug-2013 19:58:10.880 running
05-Aug-2013 19:59:11.360 unexpected RCODE (REFUSED) resolving 'www.XXX.ch/A/IN': 1.2.3.4#53
05-Aug-2013 19:59:13.359 lame server resolving 'blog.XXX.net' (in 'XXX.net'?): 1.118.193.3#53
05-Aug-2013 19:59:13.359 lame server resolving 'blog.XXX.net' (in 'XXX.net'?): 2.134.128.59#53
05-Aug-2013 19:59:13.360 lame server resolving 'blog.XXX.net' (in 'XXX.net'?): 2.134.128.59#53
05-Aug-2013 19:59:13.361 lame server resolving 'blog.XXX.net' (in 'XXX.net'?): 1.118.193.3#53

05-Aug-2013 20:00:22.718 shutting down
05-Aug-2013 20:00:22.719 no longer listening on 1.2.3.4#53
05-Aug-2013 20:00:22.719 no longer listening on 127.0.0.1#53
05-Aug-2013 20:00:22.720 exiting
# /usr/local/sbin/named -t /var/named -u bind -fg -c /etc/namedb/named.conf
29-Sep-2015 20:16:29.117 starting BIND x.x.x. -t /var/named -u bind -fg -c /etc/namedb/named.conf
29-Sep-2015 20:16:29.117 found 2 CPUs, using 2 worker threads
29-Sep-2015 20:16:29.117 using 2 UDP listeners per interface
29-Sep-2015 20:16:29.120 using up to 4096 sockets
29-Sep-2015 20:16:29.137 ENGINE_by_id failed (crypto failure)
29-Sep-2015 20:16:29.138 error:25070067:DSO support routines:DSO_load:could not load the shared library:dso_lib.c:244:
29-Sep-2015 20:16:29.138 error:260B6084:engine routines:DYNAMIC_LOAD:dso not found:eng_dyn.c:450:
29-Sep-2015 20:16:29.138 error:2606A074:engine routines:ENGINE_by_id:no such engine:eng_list.c:417:id=gost
29-Sep-2015 20:16:29.140 initializing DST: crypto failure
29-Sep-2015 20:16:29.140 exiting (due to fatal error)

# /usr/local/sbin/named -u bind -fg -c /etc/namedb/named.conf
29-Sep-2015 20:16:51.826 starting BIND x.x.x -u bind -fg -c /etc/namedb/named.conf
29-Sep-2015 20:16:51.826 found 2 CPUs, using 2 worker threads
29-Sep-2015 20:16:51.826 using 2 UDP listeners per interface
29-Sep-2015 20:16:51.829 using up to 4096 sockets
29-Sep-2015 20:16:51.853 loading configuration from '/etc/namedb/named.conf'
29-Sep-2015 20:16:51.855 using default UDP/IPv4 port range: [49152, 65535]
29-Sep-2015 20:16:51.855 using default UDP/IPv6 port range: [49152, 65535]
29-Sep-2015 20:16:51.856 listening on IPv4 interface em0, 195.134.157.20#53
29-Sep-2015 20:16:51.858 listening on IPv4 interface lo0, 127.0.0.1#53
[...]
29-Sep-2015 20:16:51.891 command channel listening on 127.0.0.1#953
29-Sep-2015 20:16:51.891 not using config file logging statement for logging due to -g option
29-Sep-2015 20:16:51.892 managed-keys-zone: loaded serial 0
29-Sep-2015 20:16:51.893 redirect-zone: loaded serial 2014060401
29-Sep-2015 20:16:51.907 zone 157.x.x.in-addr.arpa/IN: loaded serial 2007020101
29-Sep-2015 20:16:51.912 zone xxx.ch/IN: loaded serial 2007020101
29-Sep-2015 20:16:51.929 zone yyy.ch/IN: loaded serial 2007020101
29-Sep-2015 20:16:51.930 all zones loaded
29-Sep-2015 20:16:51.933 running

What is the meaning of these BIND log messages?

  • “unexpected RCODE (SERVFAIL)…”
  • “lame server resolving…”
allow-recursion { 127.0.0.1; };

05-Aug-2013 20:05:39.820 starting
05-Aug-2013 20:05:39.824 loading configuration from '/etc/namedb/named.conf'
05-Aug-2013 20:05:39.825 listening on IPv4 interface em0, 1.2.3.4#53
05-Aug-2013 20:05:39.825 listening on IPv4 interface lo0, 127.0.0.1#53
05-Aug-2013 20:05:39.830 zone 0.0.127.in-addr.arpa/IN: loaded serial 2007020101
05-Aug-2013 20:05:39.832 zone AAA.ch/IN: loaded serial 2007020101
05-Aug-2013 20:05:39.833 zone BBB.ch/IN: loaded serial 2007020101
05-Aug-2013 20:05:39.833 zone CCC.ch/IN: loaded serial 2007020101
05-Aug-2013 20:05:39.834 zone DDD.ch/IN: loaded serial 2007020101
05-Aug-2013 20:05:39.835 zone localhost/IN: loaded serial 2007020101
05-Aug-2013 20:05:39.837 running
05-Aug-2013 20:05:39.837 zone localhost/IN: sending notifies (serial 2007020101)
05-Aug-2013 20:05:39.838 zone AAA.ch/IN: sending notifies (serial 2007020101)
05-Aug-2013 20:05:39.838 zone BBB.net/IN: sending notifies (serial 2007020101)
05-Aug-2013 20:05:39.838 zone CCC.net/IN: sending notifies (serial 2007020101)
05-Aug-2013 20:05:39.838 zone DDD.net/IN: sending notifies (serial 2007020101)
05-Aug-2013 20:05:39.838 zone 0.0.127.in-addr.arpa/IN: sending notifies (serial 2007020101)
05-Aug-2013 20:05:39.838 client 1.2.3.4#56328: received notify for zone 'localhost'
05-Aug-2013 20:05:40.339 client 1.2.3.4#56328: received notify for zone 'AAA.ch'
05-Aug-2013 20:05:40.339 client 1.2.3.4#56328: received notify for zone 'BBB.net'
05-Aug-2013 20:05:40.340 client 1.2.3.4#56328: received notify for zone 'CCC.net'
05-Aug-2013 20:05:40.340 client 1.2.3.4#56328: received notify for zone 'DDD.net'
05-Aug-2013 20:05:40.840 client 1.2.3.4#56328: received notify for zone '0.0.127.in-addr.arpa'

05-Aug-2013 20:09:10.348 shutting down
05-Aug-2013 20:09:10.348 no longer listening on 1.2.3.4#53
05-Aug-2013 20:09:10.348 no longer listening on 127.0.0.1#53
05-Aug-2013 20:09:10.350 exiting

How to setup Local Authoritative DNS
BIND 10: Authoritative DNS Server

Bash prompt

CLICOLOR and LS_COLORS in bash
dircolors: modify color settings globaly
COLORS-Lscolors

if [ -f ~/.bashrc ]; then
      . ~/.bashrc
fi

How can I shorten my command line (bash) prompt?
Color Bash Prompt
Don’t Reinvent the Wheel

PROMPT_DIRTRIM=3
LS_COLORS="rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:"
CLICOLOR=yes
LSCOLORS=Exfxcxdxbxegedabagacad
TITLEBAR='\[\e]0;\u@\h: \w\a\]'

NONE="\[\033[0m\]"    # unsets color to term's fg color

# regular colors
K="\[\033[0;30m\]"    # black
R="\[\033[0;31m\]"    # red
G="\[\033[0;32m\]"    # green
Y="\[\033[0;33m\]"    # yellow
B="\[\033[0;34m\]"    # blue
M="\[\033[0;35m\]"    # magenta
C="\[\033[0;36m\]"    # cyan
W="\[\033[0;37m\]"    # white

# emphasized (bolded) colors
EMK="\[\033[1;30m\]"
EMR="\[\033[1;31m\]"
EMG="\[\033[1;32m\]"
EMY="\[\033[1;33m\]"
EMB="\[\033[1;34m\]"
EMM="\[\033[1;35m\]"
EMC="\[\033[1;36m\]"
EMW="\[\033[1;37m\]"

# background colors
BGK="\[\033[40m\]"
BGR="\[\033[41m\]"
BGG="\[\033[42m\]"
BGY="\[\033[43m\]"
BGB="\[\033[44m\]"
BGM="\[\033[45m\]"
BGC="\[\033[46m\]"
BGW="\[\033[47m\]"

UC=$EMW               # user's color
[ $UID -eq "0" ] && UC=$R   # root's color

PS1="${TITLEBAR}${EMR}[${UC}\u${EMR}@${UC}\h ${EMB}\w${EMR}]${UC}\\$ ${NONE}"
#!/usr/bin/env bash
 
# Linux
#export LS_COLORS="rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:"
eval "$(dircolors -b /etc/DIR_COLORS)"
alias ls='ls -F --color --show-control-chars'

# FreeBSD
DIR=Ex
SYM_LINK=Gx
SOCKET=Fx
PIPE=dx
EXE=Cx
BLOCK_SP=Dx
CHAR_SP=Dx
EXE_SUID=hb
EXE_GUID=ad
DIR_STICKY=Ex
DIR_WO_STICKY=Ex
export LSCOLORS="$DIR$SYM_LINK$SOCKET$PIPE$EXE$BLOCK_SP$CHAR_SP$EXE_SUID$EXE_GUID$DIR_STICKY$DIR_WO_STICKY"
export CLICOLOR="YES"
 
bash_prompt_command() {
    # How many characters of the $PWD should be kept
    local pwdmaxlen=30
    # Indicate that there has been dir truncation
    local trunc_symbol=".."
    local dir=${PWD##*/}
    pwdmaxlen=$(( ( pwdmaxlen < ${#dir} ) ? ${#dir} : pwdmaxlen ))
    NEW_PWD=${PWD/#$HOME/\~}
    local pwdoffset=$(( ${#NEW_PWD} - pwdmaxlen ))
    if [ ${pwdoffset} -gt "0" ]
    then
        NEW_PWD=${NEW_PWD:$pwdoffset:$pwdmaxlen}
        NEW_PWD=${trunc_symbol}/${NEW_PWD#*/}
    fi
}
 
bash_prompt() {
    case $TERM in
     xterm*|rxvt*)
         local TITLEBAR='\[\033]0;\u:${NEW_PWD}\007\]'
          ;;
     *)
         local TITLEBAR=""
          ;;
    esac
    local NONE="\[\033[0m\]"    # unsets color to term's fg color
 
    # regular colors
    local K="\[\033[0;30m\]"    # black
    local R="\[\033[0;31m\]"    # red
    local G="\[\033[0;32m\]"    # green
    local Y="\[\033[0;33m\]"    # yellow
    local B="\[\033[0;34m\]"    # blue
    local M="\[\033[0;35m\]"    # magenta
    local C="\[\033[0;36m\]"    # cyan
    local W="\[\033[0;37m\]"    # white
 
    # emphasized (bolded) colors
    local EMK="\[\033[1;30m\]"
    local EMR="\[\033[1;31m\]"
    local EMG="\[\033[1;32m\]"
    local EMY="\[\033[1;33m\]"
    local EMB="\[\033[1;34m\]"
    local EMM="\[\033[1;35m\]"
    local EMC="\[\033[1;36m\]"
    local EMW="\[\033[1;37m\]"
 
    # background colors
    local BGK="\[\033[40m\]"
    local BGR="\[\033[41m\]"
    local BGG="\[\033[42m\]"
    local BGY="\[\033[43m\]"
    local BGB="\[\033[44m\]"
    local BGM="\[\033[45m\]"
    local BGC="\[\033[46m\]"
    local BGW="\[\033[47m\]"
 
    local UC=$EMW               # user's color
    [ $UID -eq "0" ] && UC=$R   # root's color
 
    PS1="${TITLEBAR}${EMR}[${UC}\u${EMR}@${UC}\h ${EMB}\${NEW_PWD}${EMR}]${UC}\\$ ${NONE}"
 
    # without colors: PS1="[\u@\h \${NEW_PWD}]\\$ "
    # extra backslash in front of \$ to make bash colorize the prompt
}
 
PROMPT_COMMAND=bash_prompt_command
bash_prompt
# =============================================================== #
#
# PERSONAL $HOME/.bashrc FILE for bash-3.0 (or later)
# By Emmanuel Rouat [no-email]
#
# Last modified: Tue Nov 20 22:04:47 CET 2012

#  This file is normally read by interactive shells only.
#+ Here is the place to define your aliases, functions and
#+ other interactive features like your prompt.
#
#  The majority of the code here assumes you are on a GNU
#+ system (most likely a Linux box) and is often based on code
#+ found on Usenet or Internet.
#
#  See for instance:
#  http://tldp.org/LDP/abs/html/index.html
#  http://www.caliban.org/bash
#  http://www.shelldorado.com/scripts/categories.html
#  http://www.dotfiles.org
#
#  The choice of colors was done for a shell with a dark background
#+ (white on black), and this is usually also suited for pure text-mode
#+ consoles (no X server available). If you use a white background,
#+ you'll have to do some other choices for readability.
#
#  This bashrc file is a bit overcrowded.
#  Remember, it is just just an example.
#  Tailor it to your needs.
#
# =============================================================== #

# --> Comments added by HOWTO author.

# If not running interactively, don't do anything
[ -z "$PS1" ] && return


#-------------------------------------------------------------
# Source global definitions (if any)
#-------------------------------------------------------------


if [ -f /etc/bashrc ]; then
      . /etc/bashrc   # --> Read /etc/bashrc, if present.
fi


#--------------------------------------------------------------
#  Automatic setting of $DISPLAY (if not set already).
#  This works for me - your mileage may vary. . . .
#  The problem is that different types of terminals give
#+ different answers to 'who am i' (rxvt in particular can be
#+ troublesome) - however this code seems to work in a majority
#+ of cases.
#--------------------------------------------------------------

function get_xserver ()
{
    case $TERM in
        xterm )
            XSERVER=$(who am i | awk '{print $NF}' | tr -d ')''(' )
            # Ane-Pieter Wieringa suggests the following alternative:
            #  I_AM=$(who am i)
            #  SERVER=${I_AM#*(}
            #  SERVER=${SERVER%*)}
            XSERVER=${XSERVER%%:*}
            ;;
            aterm | rxvt)
            # Find some code that works here. ...
            ;;
    esac
}

if [ -z ${DISPLAY:=""} ]; then
    get_xserver
    if [[ -z ${XSERVER}  || ${XSERVER} == $(hostname) ||
       ${XSERVER} == "unix" ]]; then
          DISPLAY=":0.0"          # Display on local host.
    else
       DISPLAY=${XSERVER}:0.0     # Display on remote host.
    fi
fi

export DISPLAY

#-------------------------------------------------------------
# Some settings
#-------------------------------------------------------------

#set -o nounset     # These  two options are useful for debugging.
#set -o xtrace
alias debug="set -o nounset; set -o xtrace"

ulimit -S -c 0      # Don't want coredumps.
set -o notify
set -o noclobber
set -o ignoreeof


# Enable options:
shopt -s cdspell
shopt -s cdable_vars
shopt -s checkhash
shopt -s checkwinsize
shopt -s sourcepath
shopt -s no_empty_cmd_completion
shopt -s cmdhist
shopt -s histappend histreedit histverify
shopt -s extglob       # Necessary for programmable completion.

# Disable options:
shopt -u mailwarn
unset MAILCHECK        # Don't want my shell to warn me of incoming mail.


#-------------------------------------------------------------
# Greeting, motd etc. ...
#-------------------------------------------------------------

# Color definitions (taken from Color Bash Prompt HowTo).
# Some colors might look different of some terminals.
# For example, I see 'Bold Red' as 'orange' on my screen,
# hence the 'Green' 'BRed' 'Red' sequence I often use in my prompt.


# Normal Colors
Black='\e[0;30m'        # Black
Red='\e[0;31m'          # Red
Green='\e[0;32m'        # Green
Yellow='\e[0;33m'       # Yellow
Blue='\e[0;34m'         # Blue
Purple='\e[0;35m'       # Purple
Cyan='\e[0;36m'         # Cyan
White='\e[0;37m'        # White

# Bold
BBlack='\e[1;30m'       # Black
BRed='\e[1;31m'         # Red
BGreen='\e[1;32m'       # Green
BYellow='\e[1;33m'      # Yellow
BBlue='\e[1;34m'        # Blue
BPurple='\e[1;35m'      # Purple
BCyan='\e[1;36m'        # Cyan
BWhite='\e[1;37m'       # White

# Background
On_Black='\e[40m'       # Black
On_Red='\e[41m'         # Red
On_Green='\e[42m'       # Green
On_Yellow='\e[43m'      # Yellow
On_Blue='\e[44m'        # Blue
On_Purple='\e[45m'      # Purple
On_Cyan='\e[46m'        # Cyan
On_White='\e[47m'       # White

NC="\e[m"               # Color Reset


ALERT=${BWhite}${On_Red} # Bold White on red background



echo -e "${BCyan}This is BASH ${BRed}${BASH_VERSION%.*}${BCyan}\
- DISPLAY on ${BRed}$DISPLAY${NC}\n"
date
if [ -x /usr/games/fortune ]; then
    /usr/games/fortune -s     # Makes our day a bit more fun.... 🙂
fi

function _exit()              # Function to run upon exit of shell.
{
    echo -e "${BRed}Hasta la vista, baby${NC}"
}
trap _exit EXIT

#-------------------------------------------------------------
# Shell Prompt - for many examples, see:
#       http://www.debian-administration.org/articles/205
#       http://www.askapache.com/linux/bash-power-prompt.html
#       http://tldp.org/HOWTO/Bash-Prompt-HOWTO
#       https://github.com/nojhan/liquidprompt
#-------------------------------------------------------------
# Current Format: [TIME USER@HOST PWD] >
# TIME:
#    Green     == machine load is low
#    Orange    == machine load is medium
#    Red       == machine load is high
#    ALERT     == machine load is very high
# USER:
#    Cyan      == normal user
#    Orange    == SU to user
#    Red       == root
# HOST:
#    Cyan      == local session
#    Green     == secured remote connection (via ssh)
#    Red       == unsecured remote connection
# PWD:
#    Green     == more than 10% free disk space
#    Orange    == less than 10% free disk space
#    ALERT     == less than 5% free disk space
#    Red       == current user does not have write privileges
#    Cyan      == current filesystem is size zero (like /proc)
# >:
#    White     == no background or suspended jobs in this shell
#    Cyan      == at least one background job in this shell
#    Orange    == at least one suspended job in this shell
#
#    Command is added to the history file each time you hit enter,
#    so it's available to all shells (using 'history -a').


# Test connection type:
if [ -n "${SSH_CONNECTION}" ]; then
    CNX=${Green}        # Connected on remote machine, via ssh (good).
elif [[ "${DISPLAY%%:0*}" != "" ]]; then
    CNX=${ALERT}        # Connected on remote machine, not via ssh (bad).
else
    CNX=${BCyan}        # Connected on local machine.
fi

# Test user type:
if [[ ${USER} == "root" ]]; then
    SU=${Red}           # User is root.
elif [[ ${USER} != $(logname) ]]; then
    SU=${BRed}          # User is not login user.
else
    SU=${BCyan}         # User is normal (well ... most of us are).
fi



NCPU=$(grep -c 'processor' /proc/cpuinfo)    # Number of CPUs
SLOAD=$(( 100*${NCPU} ))        # Small load
MLOAD=$(( 200*${NCPU} ))        # Medium load
XLOAD=$(( 400*${NCPU} ))        # Xlarge load

# Returns system load as percentage, i.e., '40' rather than '0.40)'.
function load()
{
    local SYSLOAD=$(cut -d " " -f1 /proc/loadavg | tr -d '.')
    # System load of the current host.
    echo $((10#$SYSLOAD))       # Convert to decimal.
}

# Returns a color indicating system load.
function load_color()
{
    local SYSLOAD=$(load)
    if [ ${SYSLOAD} -gt ${XLOAD} ]; then
        echo -en ${ALERT}
    elif [ ${SYSLOAD} -gt ${MLOAD} ]; then
        echo -en ${Red}
    elif [ ${SYSLOAD} -gt ${SLOAD} ]; then
        echo -en ${BRed}
    else
        echo -en ${Green}
    fi
}

# Returns a color according to free disk space in $PWD.
function disk_color()
{
    if [ ! -w "${PWD}" ] ; then
        echo -en ${Red}
        # No 'write' privilege in the current directory.
    elif [ -s "${PWD}" ] ; then
        local used=$(command df -P "$PWD" |
                   awk 'END {print $5} {sub(/%/,"")}')
        if [ ${used} -gt 95 ]; then
            echo -en ${ALERT}           # Disk almost full (>95%).
        elif [ ${used} -gt 90 ]; then
            echo -en ${BRed}            # Free disk space almost gone.
        else
            echo -en ${Green}           # Free disk space is ok.
        fi
    else
        echo -en ${Cyan}
        # Current directory is size '0' (like /proc, /sys etc).
    fi
}

# Returns a color according to running/suspended jobs.
function job_color()
{
    if [ $(jobs -s | wc -l) -gt "0" ]; then
        echo -en ${BRed}
    elif [ $(jobs -r | wc -l) -gt "0" ] ; then
        echo -en ${BCyan}
    fi
}

# Adds some text in the terminal frame (if applicable).


# Now we construct the prompt.
PROMPT_COMMAND="history -a"
case ${TERM} in
  *term | rxvt | linux)
        PS1="\[\$(load_color)\][\A\[${NC}\] "
        # Time of day (with load info):
        PS1="\[\$(load_color)\][\A\[${NC}\] "
        # User@Host (with connection type info):
        PS1=${PS1}"\[${SU}\]\u\[${NC}\]@\[${CNX}\]\h\[${NC}\] "
        # PWD (with 'disk space' info):
        PS1=${PS1}"\[\$(disk_color)\]\W]\[${NC}\] "
        # Prompt (with 'job' info):
        PS1=${PS1}"\[\$(job_color)\]>\[${NC}\] "
        # Set title of current xterm:
        PS1=${PS1}"\[\e]0;[\u@\h] \w\a\]"
        ;;
    *)
        PS1="(\A \u@\h \W) > " # --> PS1="(\A \u@\h \w) > "
                               # --> Shows full pathname of current dir.
        ;;
esac



export TIMEFORMAT=$'\nreal %3R\tuser %3U\tsys %3S\tpcpu %P\n'
export HISTIGNORE="&:bg:fg:ll:h"
export HISTTIMEFORMAT="$(echo -e ${BCyan})[%d/%m %H:%M:%S]$(echo -e ${NC}) "
export HISTCONTROL=ignoredups
export HOSTFILE=$HOME/.hosts    # Put a list of remote hosts in ~/.hosts


#============================================================
#
#  ALIASES AND FUNCTIONS
#
#  Arguably, some functions defined here are quite big.
#  If you want to make this file smaller, these functions can
#+ be converted into scripts and removed from here.
#
#============================================================

#-------------------
# Personnal Aliases
#-------------------

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
# -> Prevents accidentally clobbering files.
alias mkdir='mkdir -p'

alias h='history'
alias j='jobs -l'
alias which='type -a'
alias ..='cd ..'

# Pretty-print of some PATH variables:
alias path='echo -e ${PATH//:/\\n}'
alias libpath='echo -e ${LD_LIBRARY_PATH//:/\\n}'


alias du='du -kh'    # Makes a more readable output.
alias df='df -kTh'

#-------------------------------------------------------------
# The 'ls' family (this assumes you use a recent GNU ls).
#-------------------------------------------------------------
# Add colors for filetype and  human-readable sizes by default on 'ls':
alias ls='ls -h --color'
alias lx='ls -lXB'         #  Sort by extension.
alias lk='ls -lSr'         #  Sort by size, biggest last.
alias lt='ls -ltr'         #  Sort by date, most recent last.
alias lc='ls -ltcr'        #  Sort by/show change time,most recent last.
alias lu='ls -ltur'        #  Sort by/show access time,most recent last.

# The ubiquitous 'll': directories first, with alphanumeric sorting:
alias ll="ls -lv --group-directories-first"
alias lm='ll |more'        #  Pipe through 'more'
alias lr='ll -R'           #  Recursive ls.
alias la='ll -A'           #  Show hidden files.
alias tree='tree -Csuh'    #  Nice alternative to 'recursive ls' ...


#-------------------------------------------------------------
# Tailoring 'less'
#-------------------------------------------------------------

alias more='less'
export PAGER=less
export LESSCHARSET='latin1'
export LESSOPEN='|/usr/bin/lesspipe.sh %s 2>&-'
                # Use this if lesspipe.sh exists.
export LESS='-i -N -w  -z-4 -g -e -M -X -F -R -P%t?f%f \
:stdin .?pb%pb\%:?lbLine %lb:?bbByte %bb:-...'

# LESS man page colors (makes Man pages more readable).
export LESS_TERMCAP_mb=$'\E[01;31m'
export LESS_TERMCAP_md=$'\E[01;31m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;32m'


#-------------------------------------------------------------
# Spelling typos - highly personnal and keyboard-dependent 🙂
#-------------------------------------------------------------

alias xs='cd'
alias vf='cd'
alias moer='more'
alias moew='more'
alias kk='ll'


#-------------------------------------------------------------
# A few fun ones
#-------------------------------------------------------------

# Adds some text in the terminal frame (if applicable).

function xtitle()
{
    case "$TERM" in
    *term* | rxvt)
        echo -en  "\e]0;$*\a" ;;
    *)  ;;
    esac
}


# Aliases that use xtitle
alias top='xtitle Processes on $HOST && top'
alias make='xtitle Making $(basename $PWD) ; make'

# .. and functions
function man()
{
    for i ; do
        xtitle The $(basename $1|tr -d .[:digit:]) manual
        command man -a "$i"
    done
}


#-------------------------------------------------------------
# Make the following commands run in background automatically:
#-------------------------------------------------------------

function te()  # wrapper around xemacs/gnuserv
{
    if [ "$(gnuclient -batch -eval t 2>&-)" == "t" ]; then
       gnuclient -q "$@";
    else
       ( xemacs "$@" &);
    fi
}

function soffice() { command soffice "$@" & }
function firefox() { command firefox "$@" & }
function xpdf() { command xpdf "$@" & }


#-------------------------------------------------------------
# File & strings related functions:
#-------------------------------------------------------------


# Find a file with a pattern in name:
function ff() { find . -type f -iname '*'"$*"'*' -ls ; }

# Find a file with pattern $1 in name and Execute $2 on it:
function fe() { find . -type f -iname '*'"${1:-}"'*' \
-exec ${2:-file} {} \;  ; }

#  Find a pattern in a set of files and highlight them:
#+ (needs a recent version of egrep).
function fstr()
{
    OPTIND=1
    local mycase=""
    local usage="fstr: find string in files.
Usage: fstr [-i] \"pattern\" [\"filename pattern\"] "
    while getopts :it opt
    do
        case "$opt" in
           i) mycase="-i " ;;
           *) echo "$usage"; return ;;
        esac
    done
    shift $(( $OPTIND - 1 ))
    if [ "$#" -lt 1 ]; then
        echo "$usage"
        return;
    fi
    find . -type f -name "${2:-*}" -print0 | \
xargs -0 egrep --color=always -sn ${case} "$1" 2>&- | more

}


function swap()
{ # Swap 2 filenames around, if they exist (from Uzi's bashrc).
    local TMPFILE=tmp.$$

    [ $# -ne 2 ] && echo "swap: 2 arguments needed" && return 1
    [ ! -e $1 ] && echo "swap: $1 does not exist" && return 1
    [ ! -e $2 ] && echo "swap: $2 does not exist" && return 1

    mv "$1" $TMPFILE
    mv "$2" "$1"
    mv $TMPFILE "$2"
}

function extract()      # Handy Extract Program
{
    if [ -f $1 ] ; then
        case $1 in
            *.tar.bz2)   tar xvjf $1     ;;
            *.tar.gz)    tar xvzf $1     ;;
            *.bz2)       bunzip2 $1      ;;
            *.rar)       unrar x $1      ;;
            *.gz)        gunzip $1       ;;
            *.tar)       tar xvf $1      ;;
            *.tbz2)      tar xvjf $1     ;;
            *.tgz)       tar xvzf $1     ;;
            *.zip)       unzip $1        ;;
            *.Z)         uncompress $1   ;;
            *.7z)        7z x $1         ;;
            *)           echo "'$1' cannot be extracted via >extract<" ;;
        esac
    else
        echo "'$1' is not a valid file!"
    fi
}


# Creates an archive (*.tar.gz) from given directory.
function maketar() { tar cvzf "${1%%/}.tar.gz"  "${1%%/}/"; }

# Create a ZIP archive of a file or folder.
function makezip() { zip -r "${1%%/}.zip" "$1" ; }

# Make your directories and files access rights sane.
function sanitize() { chmod -R u=rwX,g=rX,o= "$@" ;}

#-------------------------------------------------------------
# Process/system related functions:
#-------------------------------------------------------------


function my_ps() { ps $@ -u $USER -o pid,%cpu,%mem,bsdtime,command ; }
function pp() { my_ps f | awk '!/awk/ && $0~var' var=${1:-".*"} ; }


function killps()   # kill by process name
{
    local pid pname sig="-TERM"   # default signal
    if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
        echo "Usage: killps [-SIGNAL] pattern"
        return;
    fi
    if [ $# = 2 ]; then sig=$1 ; fi
    for pid in $(my_ps| awk '!/awk/ && $0~pat { print $1 }' pat=${!#} )
    do
        pname=$(my_ps | awk '$1~var { print $5 }' var=$pid )
        if ask "Kill process $pid <$pname> with signal $sig?"
            then kill $sig $pid
        fi
    done
}

function mydf()         # Pretty-print of 'df' output.
{                       # Inspired by 'dfc' utility.
    for fs ; do

        if [ ! -d $fs ]
        then
          echo -e $fs" :No such file or directory" ; continue
        fi

        local info=( $(command df -P $fs | awk 'END{ print $2,$3,$5 }') )
        local free=( $(command df -Pkh $fs | awk 'END{ print $4 }') )
        local nbstars=$(( 20 * ${info[1]} / ${info[0]} ))
        local out="["
        for ((j=0;j<20;j++)); do
            if [ ${j} -lt ${nbstars} ]; then
               out=$out"*"
            else
               out=$out"-"
            fi
        done
        out=${info[2]}" "$out"] ("$free" free on "$fs")"
        echo -e $out
    done
}


function my_ip() # Get IP adress on ethernet.
{
    MY_IP=$(/sbin/ifconfig eth0 | awk '/inet/ { print $2 } ' |
      sed -e s/addr://)
    echo ${MY_IP:-"Not connected"}
}

function ii()   # Get current host related info.
{
    echo -e "\nYou are logged on ${BRed}$HOST"
    echo -e "\n${BRed}Additionnal information:$NC " ; uname -a
    echo -e "\n${BRed}Users logged on:$NC " ; w -hs |
             cut -d " " -f1 | sort | uniq
    echo -e "\n${BRed}Current date :$NC " ; date
    echo -e "\n${BRed}Machine stats :$NC " ; uptime
    echo -e "\n${BRed}Memory stats :$NC " ; free
    echo -e "\n${BRed}Diskspace :$NC " ; mydf / $HOME
    echo -e "\n${BRed}Local IP Address :$NC" ; my_ip
    echo -e "\n${BRed}Open connections :$NC "; netstat -pan --inet;
    echo
}

#-------------------------------------------------------------
# Misc utilities:
#-------------------------------------------------------------

function repeat()       # Repeat n times command.
{
    local i max
    max=$1; shift;
    for ((i=1; i <= max ; i++)); do  # --> C-like syntax
        eval "$@";
    done
}


function ask()          # See 'killps' for example of use.
{
    echo -n "$@" '[y/n] ' ; read ans
    case "$ans" in
        y*|Y*) return 0 ;;
        *) return 1 ;;
    esac
}

function corename()   # Get name of app that created a corefile.
{
    for file ; do
        echo -n $file : ; gdb --core=$file --batch | head -1
    done
}



#=========================================================================
#
#  PROGRAMMABLE COMPLETION SECTION
#  Most are taken from the bash 2.05 documentation and from Ian McDonald's
# 'Bash completion' package (http://www.caliban.org/bash/#completion)
#  You will in fact need bash more recent then 3.0 for some features.
#
#  Note that most linux distributions now provide many completions
# 'out of the box' - however, you might need to make your own one day,
#  so I kept those here as examples.
#=========================================================================

if [ "${BASH_VERSION%.*}" \< "3.0" ]; then
    echo "You will need to upgrade to version 3.0 for full \
          programmable completion features"
    return
fi

shopt -s extglob        # Necessary.

complete -A hostname   rsh rcp telnet rlogin ftp ping disk
complete -A export     printenv
complete -A variable   export local readonly unset
complete -A enabled    builtin
complete -A alias      alias unalias
complete -A function   function
complete -A user       su mail finger

complete -A helptopic  help     # Currently same as builtins.
complete -A shopt      shopt
complete -A stopped -P '%' bg
complete -A job -P '%'     fg jobs disown

complete -A directory  mkdir rmdir
complete -A directory   -o default cd

# Compression
complete -f -o default -X '*.+(zip|ZIP)'  zip
complete -f -o default -X '!*.+(zip|ZIP)' unzip
complete -f -o default -X '*.+(z|Z)'      compress
complete -f -o default -X '!*.+(z|Z)'     uncompress
complete -f -o default -X '*.+(gz|GZ)'    gzip
complete -f -o default -X '!*.+(gz|GZ)'   gunzip
complete -f -o default -X '*.+(bz2|BZ2)'  bzip2
complete -f -o default -X '!*.+(bz2|BZ2)' bunzip2
complete -f -o default -X '!*.+(zip|ZIP|z|Z|gz|GZ|bz2|BZ2)' extract


# Documents - Postscript,pdf,dvi.....
complete -f -o default -X '!*.+(ps|PS)'  gs ghostview ps2pdf ps2ascii
complete -f -o default -X \
'!*.+(dvi|DVI)' dvips dvipdf xdvi dviselect dvitype
complete -f -o default -X '!*.+(pdf|PDF)' acroread pdf2ps
complete -f -o default -X '!*.@(@(?(e)ps|?(E)PS|pdf|PDF)?\
(.gz|.GZ|.bz2|.BZ2|.Z))' gv ggv
complete -f -o default -X '!*.texi*' makeinfo texi2dvi texi2html texi2pdf
complete -f -o default -X '!*.tex' tex latex slitex
complete -f -o default -X '!*.lyx' lyx
complete -f -o default -X '!*.+(htm*|HTM*)' lynx html2ps
complete -f -o default -X \
'!*.+(doc|DOC|xls|XLS|ppt|PPT|sx?|SX?|csv|CSV|od?|OD?|ott|OTT)' soffice

# Multimedia
complete -f -o default -X \
'!*.+(gif|GIF|jp*g|JP*G|bmp|BMP|xpm|XPM|png|PNG)' xv gimp ee gqview
complete -f -o default -X '!*.+(mp3|MP3)' mpg123 mpg321
complete -f -o default -X '!*.+(ogg|OGG)' ogg123
complete -f -o default -X \
'!*.@(mp[23]|MP[23]|ogg|OGG|wav|WAV|pls|\
m3u|xm|mod|s[3t]m|it|mtm|ult|flac)' xmms
complete -f -o default -X '!*.@(mp?(e)g|MP?(E)G|wma|avi|AVI|\
asf|vob|VOB|bin|dat|vcd|ps|pes|fli|viv|rm|ram|yuv|mov|MOV|qt|\
QT|wmv|mp3|MP3|ogg|OGG|ogm|OGM|mp4|MP4|wav|WAV|asx|ASX)' xine



complete -f -o default -X '!*.pl'  perl perl5


#  This is a 'universal' completion function - it works when commands have
#+ a so-called 'long options' mode , ie: 'ls --all' instead of 'ls -a'
#  Needs the '-o' option of grep
#+ (try the commented-out version if not available).

#  First, remove '=' from completion word separators
#+ (this will allow completions like 'ls --color=auto' to work correctly).

COMP_WORDBREAKS=${COMP_WORDBREAKS/=/}


_get_longopts()
{
  #$1 --help | sed  -e '/--/!d' -e 's/.*--\([^[:space:].,]*\).*/--\1/'| \
  #grep ^"$2" |sort -u ;
    $1 --help | grep -o -e "--[^[:space:].,]*" | grep -e "$2" |sort -u
}

_longopts()
{
    local cur
    cur=${COMP_WORDS[COMP_CWORD]}

    case "${cur:-*}" in
       -*)      ;;
        *)      return ;;
    esac

    case "$1" in
       \~*)     eval cmd="$1" ;;
         *)     cmd="$1" ;;
    esac
    COMPREPLY=( $(_get_longopts ${1} ${cur} ) )
}
complete  -o default -F _longopts configure bash
complete  -o default -F _longopts wget id info a2ps ls recode

_tar()
{
    local cur ext regex tar untar

    COMPREPLY=()
    cur=${COMP_WORDS[COMP_CWORD]}

    # If we want an option, return the possible long options.
    case "$cur" in
        -*)     COMPREPLY=( $(_get_longopts $1 $cur ) ); return 0;;
    esac

    if [ $COMP_CWORD -eq 1 ]; then
        COMPREPLY=( $( compgen -W 'c t x u r d A' -- $cur ) )
        return 0
    fi

    case "${COMP_WORDS[1]}" in
        ?(-)c*f)
            COMPREPLY=( $( compgen -f $cur ) )
            return 0
            ;;
        +([^Izjy])f)
            ext='tar'
            regex=$ext
            ;;
        *z*f)
            ext='tar.gz'
            regex='t\(ar\.\)\(gz\|Z\)'
            ;;
        *[Ijy]*f)
            ext='t?(ar.)bz?(2)'
            regex='t\(ar\.\)bz2\?'
            ;;
        *)
            COMPREPLY=( $( compgen -f $cur ) )
            return 0
            ;;

    esac

    if [[ "$COMP_LINE" == tar*.$ext' '* ]]; then
        # Complete on files in tar file.
        #
        # Get name of tar file from command line.
        tar=$( echo "$COMP_LINE" | \
                        sed -e 's|^.* \([^ ]*'$regex'\) .*$|\1|' )
        # Devise how to untar and list it.
        untar=t${COMP_WORDS[1]//[^Izjyf]/}

        COMPREPLY=( $( compgen -W "$( echo $( tar $untar $tar \
                                2>/dev/null ) )" -- "$cur" ) )
        return 0

    else
        # File completion on relevant files.
        COMPREPLY=( $( compgen -G $cur\*.$ext ) )

    fi

    return 0

}

complete -F _tar -o default tar

_make()
{
    local mdef makef makef_dir="." makef_inc gcmd cur prev i;
    COMPREPLY=();
    cur=${COMP_WORDS[COMP_CWORD]};
    prev=${COMP_WORDS[COMP_CWORD-1]};
    case "$prev" in
        -*f)
            COMPREPLY=($(compgen -f $cur ));
            return 0
            ;;
    esac;
    case "$cur" in
        -*)
            COMPREPLY=($(_get_longopts $1 $cur ));
            return 0
            ;;
    esac;

    # ... make reads
    #          GNUmakefile,
    #     then makefile
    #     then Makefile ...
    if [ -f ${makef_dir}/GNUmakefile ]; then
        makef=${makef_dir}/GNUmakefile
    elif [ -f ${makef_dir}/makefile ]; then
        makef=${makef_dir}/makefile
    elif [ -f ${makef_dir}/Makefile ]; then
        makef=${makef_dir}/Makefile
    else
       makef=${makef_dir}/*.mk         # Local convention.
    fi


    #  Before we scan for targets, see if a Makefile name was
    #+ specified with -f.
    for (( i=0; i < ${#COMP_WORDS[@]}; i++ )); do
        if [[ ${COMP_WORDS[i]} == -f ]]; then
            # eval for tilde expansion
            eval makef=${COMP_WORDS[i+1]}
            break
        fi
    done
    [ ! -f $makef ] && return 0

    # Deal with included Makefiles.
    makef_inc=$( grep -E '^-?include' $makef |
                 sed -e "s,^.* ,"$makef_dir"/," )
    for file in $makef_inc; do
        [ -f $file ] && makef="$makef $file"
    done


    #  If we have a partial word to complete, restrict completions
    #+ to matches of that word.
    if [ -n "$cur" ]; then gcmd='grep "^$cur"' ; else gcmd=cat ; fi

    COMPREPLY=( $( awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ \
                               {split($1,A,/ /);for(i in A)print A[i]}' \
                                $makef 2>/dev/null | eval $gcmd  ))

}

complete -F _make -X '+($*|*.[cho])' make gmake pmake




_killall()
{
    local cur prev
    COMPREPLY=()
    cur=${COMP_WORDS[COMP_CWORD]}

    #  Get a list of processes
    #+ (the first sed evaluation
    #+ takes care of swapped out processes, the second
    #+ takes care of getting the basename of the process).
    COMPREPLY=( $( ps -u $USER -o comm  | \
        sed -e '1,1d' -e 's#[]\[]##g' -e 's#^.*/##'| \
        awk '{if ($0 ~ /^'$cur'/) print $0}' ))

    return 0
}

complete -F _killall killall killps



# Local Variables:
# mode:shell-script
# sh-shell:bash
# End:
# From Andrzej Szelachowski's ~/.bash_profile:


#  Note that a variable may require special treatment
#+ if it will be exported.

DARKGRAY='\e[1;30m'
LIGHTRED='\e[1;31m'
GREEN='\e[32m'
YELLOW='\e[1;33m'
LIGHTBLUE='\e[1;34m'
NC='\e[m'

PCT="\`if [[ \$EUID -eq 0 ]]; then T='$LIGHTRED' ; else T='$LIGHTBLUE'; fi; 
echo \$T \`"

#  For "literal" command substitution to be assigned to a variable,
#+ use escapes and double quotes:
#+       PCT="\` ... \`" . . .
#  Otherwise, the value of PCT variable is assigned only once,
#+ when the variable is exported/read from .bash_profile,
#+ and it will not change afterwards even if the user ID changes.


PS1="\n$GREEN[\w] \n$DARKGRAY($PCT\t$DARKGRAY)-($PCT\u$DARKGRAY)-($PCT\!
$DARKGRAY)$YELLOW-> $NC"

#  Escape a variables whose value changes:
#        if [[ \$EUID -eq 0 ]],
#  Otherwise the value of the EUID variable will be assigned only once,
#+ as above.

#  When a variable is assigned, it should be called escaped:
#+       echo \$T,
#  Otherwise the value of the T variable is taken from the moment the PCT 
#+ variable is exported/read from .bash_profile.
#  So, in this example it would be null.

#  When a variable's value contains a semicolon it should be strong quoted:
#        T='$LIGHTRED',
#  Otherwise, the semicolon will be interpreted as a command separator.


#  Variables PCT and PS1 can be merged into a new PS1 variable:

PS1="\`if [[ \$EUID -eq 0 ]]; then PCT='$LIGHTRED';
else PCT='$LIGHTBLUE'; fi; 
echo '\n$GREEN[\w] \n$DARKGRAY('\$PCT'\t$DARKGRAY)-\
('\$PCT'\u$DARKGRAY)-('\$PCT'\!$DARKGRAY)$YELLOW-> $NC'\`"

# The trick is to use strong quoting for parts of old PS1 variable.

UNIX commands and tasks for Linux and BSD

Advanced Bash-Scripting Guide – External Filters, Programs and Commands

Basic

  • ls
  • cat
  • tac
  • rev
  • cp
  • mv
  • rm
  • rmdir
  • mkdir
  • chmod
  • chattr
  • ln
  • man
  • info

Complex

  • find
  • xargs
  • expr

Time and Date

  • date
  • zdump
  • time
  • touch
  • at
  • batch
  • cal
  • sleep
  • usleep
  • hwclock
  • clock

Text Processing

  • sort
  • tsort
  • uniq
  • expand
  • unexpand
  • cut
  • paste
  • join
  • head
  • tail
  • grep
  • look
  • sed
  • awk
  • wc
  • tr
  • fold
  • fmt
  • col
  • column
  • colrm
  • nl
  • pr
  • gettext
  • msgfmt
  • iconv
  • recode
  • TeX
  • gs
  • enscript
  • groff
  • tbl
  • eqn
  • lex
  • yacc

UNIX Toolbox: Differences between Linux/BSD/Windows

FreeBSD: Zeige alle Festplatten

[root@data /home/bachi]# atacontrol list
ATA channel 0:
    Master:      no device present
    Slave:       no device present
ATA channel 1:
    Master:      no device present
    Slave:       no device present
ATA channel 2:
    Master:  ad4 <Maxtor 33073H3/YAH814Y0> ATA/ATAPI revision 6
    Slave:       no device present
ATA channel 3:
    Master:  ad6 <Maxtor 6L300R0/BAJ41G20> ATA/ATAPI revision 7
    Slave:   ad7 <Maxtor 6L300R0/BAJ41G20> ATA/ATAPI revision 7
[root@data /home/bachi]# egrep 'ad[0-9]|cd[0-9]' /var/run/dmesg.boot
ad4: 29312MB <Maxtor 33073H3 YAH814Y0> at ata2-master UDMA100
ad6: 286188MB <Maxtor 6L300R0 BAJ41G20> at ata3-master UDMA100
ad7: 286188MB <Maxtor 6L300R0 BAJ41G20> at ata3-slave UDMA100
Trying to mount root from ufs:/dev/ad4s1a

FreeBSD Gateway

FreeBSD Handbook: Setting Up the Serial Console

Boot Config

###
### rc.conf Boot Config File
### by Andreas Bachmann
###

### CONSOLE ####################################################################
font8x14="NO"
font8x16="swiss-8x16"
font8x8="swiss-8x8"
inetd_enable="NO"
keymap="swissgerman.cp850"

### NETWORK ####################################################################
hostname="gateway.lan.bachi.net"
ifconfig_vr0="DHCP"
ifconfig_vr1="10.0.0.1 255.0.0.0"
### ifconfig_vr2="10.0.0.5 255.0.0.0"
gateway_enable="YES"

### FIREWALL ###################################################################
pf_enable="YES"
pf_rules="/etc/pf.conf"
pf_flags=""
pflog_enable="YES"
pflog_logfile="/var/log/pf.log"
pflog_flags=""

### DAEMONS ####################################################################
sendmail_enable="NONE"

dhcpd_enable="YES"
dhcpd_ifaces="vr1"

sshd_enable="YES"

snmpd_enable="YES"
snmpd_flags="-a"
snmpd_pidfile="/var/run/snmpd.pid"

ntpdate_enable="YES"
ntpdate_hosts="swisstime.ethz.ch"

NTP

server 0.ch.pool.ntp.org
server 1.ch.pool.ntp.org
server 2.ch.pool.ntp.org
server 3.ch.pool.ntp.org

Kernel Config

###
### BACHI-NET Kernel Configurations File
### by Andreas Bachmann
###

machine     i386
cpu         I586_CPU
ident       GATEWAY-CF

###############################################################################
# CPU OPTIONS
options     CPU_GEODE
device      cpufreq                         # CPU frequency control
options     HZ=1000                         # Smoother scheduling
options     FLOWTABLE                       # per-cpu routing cache

###############################################################################
# SCHEDULING
options     SCHED_ULE                       # new scheduler
options     PREEMPTION                      # Preemptive Scheduler

###############################################################################
# POSIX P1003.1B
options     P1003_1B_SEMAPHORES             # POSIX-style semaphores
options     _KPOSIX_PRIORITY_SCHEDULING     # POSIX P1003_1B real-time extensions

###############################################################################
# PARTITIONING
options     GEOM_PART_GPT                   # GUID Partition Tables.
options     GEOM_LABEL                      # Provides labelization

###############################################################################
# TRUSTEDBSD MAC FRAMEWORK
options     MAC                             # TrustedBSD MAC Framework

###############################################################################
# FILE SYSTEM
options     FFS                             # Berkeley Fast Filesystem
options     PROCFS                          # Process filesystem (requires PSEUDOFS)
options     PSEUDOFS                        # Pseudo-filesystem framework
options     SOFTUPDATES                     # Enable FFS soft updates support
options     UFS_ACL                         # Support for access control lists
options     UFS_DIRHASH                     # Improve performance on big directories
options     UFS_GJOURNAL                    # Enable gjournal-based UFS journaling
options     MD_ROOT                         # MD is a potential root device

###############################################################################
# CRYPTO SUBSYSTEM
device      crypto                          # core crypto support
device      cryptodev                       # /dev/crypto for access to h/w

###############################################################################
# SECURITY POLICY PARAMETERS
options     AUDIT                           # Security event auditing

###############################################################################
# COMPATIBILITY OPTIONS
options     COMPAT_43                       # Compatible with BSD 4.3 [KEEP THIS!]
options     COMPAT_FREEBSD4                 # Compatible with FreeBSD4
options     COMPAT_FREEBSD5                 # Compatible with FreeBSD5
options     COMPAT_FREEBSD6                 # Compatible with FreeBSD6
options     COMPAT_FREEBSD7                 # Compatible with FreeBSD7

options     SYSVSHM                         # SYSV-style shared memory
options     SYSVMSG                         # SYSV-style message queues
options     SYSVSEM                         # SYSV-style semaphores

###############################################################################
# BUS TYPES
device      eisa                            # Extended Industry Standard Architecture (EISA) Bus
device      pci                             # Peripheral Computer Interface (PCI) Bus
device      uart                            # Universal Asynchronous Receiver/Transmitter (UART) Bus
device      miibus                          # Media Independent Interface (MII) Bus

###############################################################################
# SYSTEM MANAGEMENT INTERFACE DEVICES
device      pmtimer

###############################################################################
# DISK DEVICES
device      md                              # Memory "disks"

###############################################################################
# ATA DEVICES
device      ata                             #
device      atadisk                         # ATA disk drives
device      atapicam                        # emulate ATAPI devices as SCSI ditto via CAM

###############################################################################
# SCSI OPTIONS AND DEVICES
device      scbus                           # Base SCSI Code
device      ch                              # SCSI media changers
device      da                              # SCSI direct access devices (aka disks)
device      sa                              # SCSI tapes
device      cd                              # SCSI CD-ROMs
device      pass                            # CAM passthrough driver

options     SCSI_DELAY=300                  # Delay (in ms) before probing SCSI

###############################################################################
# NETWORKING OPTIONS AND DEVICES
options     INET                            # InterNETworking

options     NETGRAPH                        # netgraph(4) system

options     ALTQ                            # Alternate queuing
options     ALTQ_CBQ                        # Class Bases Queueing
options     ALTQ_RED                        # Random Early Detection
options     ALTQ_RIO                        # RED In/Out
options     ALTQ_HFSC                       # Hierarchical Packet Scheduler
options     ALTQ_CDNR                       # Traffic conditioner
options     ALTQ_PRIQ                       # Priority Queueing
options     ALTQ_NOPCC                      # Required for SMP build

device      loop                            # Network loopback
device      ether                           # Ethernet support
device      bpf                             # Berkeley packet filter
device      bridge                          # Network bridge device

device      pf                              # PF OpenBSD packet-filter firewall
device      pflog                           # logging support interface for PF

device      vr                              # VIA Rhine, Rhine II

###############################################################################
# PERIPHERAL DEVICES
device      atkbdc                          # AT keyboard controller
device      atkbd
device      kbdmux                          # keyboard multiplexer
device      psm

options     KBD_INSTALL_CDEV                # Install a CDEV entry in /dev

###############################################################################
# GRAPHIC DEVICES AND OPTIONS
device      vga                             # VGA video card driver
device      agp                             # support several AGP chipsets
device      splash                          # Splash screen and screen saver support

###############################################################################
# SYSTEM CONSOLE DEVICES AND OPTIONS
device      sc                              # syscons console driver

###############################################################################
# MISCELLANEOUS DEVICES AND OPTIONS
device      random                          # Entropy device
device      pty                             # Pseudo-ttys (telnet etc)
device      snp                             # Snoop device
device      firmware                        # firmware assist module

###############################################################################
# UBS DEVICES AND OPTIONS

device      uhci                            # UHCI controller
device      ohci                            # OHCI controller
device      ehci                            # EHCI controller
device      usb                             # General USB code (mandatory for USB)

device      udbp                            # USB Double Bulk Pipe devices
device      uhid                            # Human Interface Device
device      ukbd                            # USB keyboard
device      ums                             # USB mouse
device      ulpt                            # USB printer

Bootloader Config

console="comconsole"

TTY Config

[...]
console none                            unknown off secure
#
ttyv0   "/usr/libexec/getty Pc"         cons25  off secure
# Virtual terminals
ttyv1   "/usr/libexec/getty Pc"         cons25  off secure
ttyv2   "/usr/libexec/getty Pc"         cons25  off  secure
ttyv3   "/usr/libexec/getty Pc"         cons25  off secure
ttyv4   "/usr/libexec/getty Pc"         cons25  off secure
ttyv5   "/usr/libexec/getty Pc"         cons25  off secure
ttyv6   "/usr/libexec/getty Pc"         cons25  off secure
ttyv7   "/usr/libexec/getty Pc"         cons25  off secure
ttyv8   "/usr/local/bin/xdm -nodaemon"  xterm   off secure
# Serial terminals
# The 'dialup' keyword identifies dialin lines to login, fingerd etc.
ttyu0   "/usr/libexec/getty std.9600"   vt100   on  secure
ttyu1   "/usr/libexec/getty std.9600"   dialup  off secure
ttyu2   "/usr/libexec/getty std.9600"   dialup  off secure
ttyu3   "/usr/libexec/getty std.9600"   dialup  off secure
# Dumb console
dcons   "/usr/libexec/getty std.9600"   vt100   off secure
# Pseudo terminals
ttyp0   none                    network
[...]

fstab Config

# Device                Mountpoint      FStype  Options         Dump    Pass#
/dev/ad0s1b             none            swap    sw              0       0
/dev/ad0s1a             /               ufs     rw              1       1
/dev/ad0s1d             /tmp            ufs     rw              2       2
/dev/ad0s1f             /usr            ufs     rw              2       2
/dev/ad0s1e             /var            ufs     rw              2       2

Disk Slices

[root@gateway /home/bachi]# df
Filesystem  1K-blocks   Used   Avail Capacity  Mounted on
/dev/ad0s1a    253678  27696  205688    12%    /
devfs               1      1       0   100%    /dev
/dev/ad0s1d    253678     12  233372     0%    /tmp
/dev/ad0s1f   2358280 997176 1172442    46%    /usr
/dev/ad0s1e    507630   9778  457242     2%    /var

[root@gateway /home/bachi]# fdisk
[...]
parameters extracted from in-core disklabel are:
cylinders=7964 heads=16 sectors/track=63 (1008 blks/cyl)
Media sector size is 512
Information from DOS bootblock is:
The data for partition 1 is:
sysid 165 (0xa5),(FreeBSD/NetBSD/386BSD)
    start 63, size 8016372 (3914 Meg), flag 80 (active)
        beg: cyl 0/ head 1/ sector 1;
        end: cyl 498/ head 254/ sector 63
[...]

PF Config

if_inet="vr0"                 # Internet
if_lan="vr1"                  # Intranet
torrent_client="10.0.0.251"
net_lan="10.0.0.0/8"

users = "{
    10.0.0.251,
    10.0.0.11,
    10.0.0.249,
    10.0.0.250,
    10.0.0.17
}"

nat on $if_inet from $net_lan to any -> ($if_inet)

#rdr on $if_inet proto tcp from any to $if_inet port { 6881, 6882, 8713 } -> $torrent_client
#rdr on $if_inet proto tcp from any to $if_inet port { 4000, 4001, 4002, 4080, 4662, 4666, 9335, 53357, 14890 } -> $torrent_client
#rdr on $if_inet proto tcp from any to $if_inet port { 80, 8080, 443 } -> $torrent_client
#rdr on $if_inet proto tcp from any to $if_inet port { 6000 }  -> $torrent_client

block all

pass in on $if_inet all
pass in on $if_lan from $users to any
pass out all

DHCPD Config

###
### GATEWAY DHCP Server Configuration
### by Andreas Bachmann
###

authoritative;
ddns-update-style ad-hoc;

default-lease-time                  600;
max-lease-time                      7200;

subnet 10.0.0.0 netmask 255.0.0.0 {
    option  subnet-mask             255.0.0.0;
    option  broadcast-address       10.255.255.255;
    option  domain-name-servers     195.134.157.20;
    option  routers                 10.0.0.1;

   range 10.0.0.10 10.0.0.254;
}