Firmware:Custom:Pending

NOTE: This page is simply a 'dump' for now…

A fair bit of stuff relates to Jffs

Startup Scripting

http://www.dd-wrt.com/wiki/index.php/Startup_Scripts

http://www.dd-wrt.com/wiki/index.php/Useful_Scripts

http://www.dd-wrt.com/wiki/index.php/Script_Execution

There are different directories FW searches for scripts, these are

* /etc/config/
* /tmp/etc/config/

Remember to change permissions on any script files using chmod to permit execution.

BootStrap

http://www.nslu2-linux.org/wiki/DS101/DS101BootStrap

  • Mounting the formatted usb drive in optware directory (/opt)…
  • Creating temporary directory for optware installation (/opt/tmp)…
  • Configuring startup script for optware applications (/usr/local/etc/rcS)…
  • Writing startup script for optware applications (/opt/startup)…
  • Adding optware applications to PATH, to facilitate command-line usage (/opt/bin)…
Extension Explanation
.startup will be executed on system startup, normally boot-time and before the firewall is configured.
.shutdown will be executed on system shutdown.

Execute scripts with a different extension

If you want to execute scripts with a different extension or those that are located in an other folder you can create this script

for I in `/bin/ls /XXX/etc/config/*.myextension`;do
   sh $I &
done

Of course you need to change the path (/XXX/etc/config) and the extension itself to match yours.

The command

sh /XXX/etc/config/*.myextension

will execute every script ending in .myextension found in the /XXX/etc/config directory.

By setting this as the rc_startup value, your *.myextension scripts will load every time the box boots.

Modifying $PATH at Startup

This will add whatever paths you want for $PATH and $LD_LIBRARY_PATH before the default system path. Change the paths to whatever you like. Have a good reason for doing this, it should be considered a hack until the feature is implemented permanently.

rm -f /tmp/newProfile
head -n1 /etc/profile | sed s!=!=/mmc/bin:/whatever/bin:! >> /tmp/newProfile
tail -n1 /etc/profile | sed s!=!=/mmc/lib:/whatever/lib:! >> /tmp/newProfile
mount --bind /tmp/newProfile /etc/profile

If you're adding /mmc/lib before the system library, in some circumstances you'll also need to do this on startup (after ensuring that the ldconfig on /mmc is up to date and happy):

mount --bind /mmc/etc/ld.so.conf /etc/ld.so.conf
mount --bind /mmc/etc/ld.so.cache /etc/ld.so.cache

Note: Only do this if you're receiving segmentation faults or your applications are failing to run, and even then only if you feel that this hack is imperative. Also note that if you're attempting this with Optware, the files are ld-opt.so.conf and ld-opt.so.cache

Another alternative to the above mentioned way of altering things is to simply copy /etc/profile to /XXX/etcteletype text, change PATH and LD_LIBRARY_PATH and bind the profile to the original location.

mkdir /XXX/etc
cp /etc/profile /XXX/etc/profile
cd /XXX/etc
vi profile (change everythings that suite your needs and save it with :x)

Afterward put the line below inside a startup script

mount --bind /XXX/etc/profile /etc/profile

Make sure you're familiar with what you're doing before attempting this, if you end up seeing a lot of segmentation faults when running things like ls, cat, cp, etc, than you'll want to either adjust the above commands, or else put those things into a script and run them manually when you enter your shell.

Log your startup

Requires XXXX. Save your startup commands to /XXXX/startup.sh

Example:

#!/bin/sh

cat /tmp/etc/passwd | sed s/^root:/password:/ > /tmp/etc/passwd
cp /XXXX/options.pptpd /tmp/pptpd/options.pptpd
rmdir /tmp/www; ln -s /XXXX/www /tmp

Make this file executable:

chmod +x /XXXX/startup.sh

Save the following line to startup:

/jffs/startup.sh > /tmp/startup.log 2>&1

Your standard and error output from the scripts will be viewable in /tmp/startup.log. /tmp is stored in volatile memory (RAM) and will be erased each startup showing only the current error or success messages.

TIP: It is not recommended to use XXXX for logs due to increased flash wear.

TIP: Use the echo command to label sections of your startup file and verbose command options for troubleshooting.

Use freedns.afraid.org as DDNS

Create a Jffs partition and copy this script as /jffs/etc/config/ddns.wanup

#!/bin/sh 
# Made by Marc-Antoine Ruel 2006
# Idea taken from http://freedns.afraid.org/forums/viewtopic.php?p=4161

# your update URL (replace by yours)
url=http://freedns.afraid.org/dynamic/update.php?abc...
# your internet interface 
inet_if=ppp0 
# curl utility 
curl='wget -q -O /dev/tty'
# cache file for IP address 
ip_cache=/tmp/ipaddr.cache 

old_ip=`cat $ip_cache` 
# echo old IP = $old_ip
current_ip=`ifconfig ${inet_if} | sed '/.*inet addr:/!d;s///;s/ .*//'` 
# echo New IP = $current_ip

if [ "$current_ip" != "$old_ip" ]; then
  $curl $url
  echo $current_ip > $ip_cache 
  echo Updated IP to $current_ip
fi

Don't forget to do

chmod +x /jffs/etc/config/ddns.wanup

Then you can execute it to verify that it works. A temporary file will be created in $ip_cache.

Block URLs with an Automatically Downloaded Host File

This was taken from mraneri from the Linksys forum.

logger WAN up script executing
sleep 5
test -s /tmp/dlhosts
if [ $? == 1 ] ; then
echo -e "#!/bin/sh\nwget -O - http://www.mvps.org/winhelp2002/hosts.txt | grep 127.0.0.1 | sed -e '2,\$s/127.0.0.1/0.0.0.0/g' -e 's/[[:space:]]*#.*$//' > /etc/hosts\nlogger DOWNLOADED http://www.mvps.org/winhelp2002/hosts.txt\nkillall -1 dnsmasq" > /tmp/dlhosts
chmod 777 /tmp/dlhosts
/tmp/dlhosts
fi
echo "45 23 * * 5 root /tmp/dlhosts" » /tmp/crontab

This script automatically downloads a host file from: "http://www.mvps.org/winhelp2002/hosts.txt" and redirects all the URLs in that file to 127.0.0.1.

All those URLs are common malware or advertisement sites so is better to block them.

You can also download the file, modify it with new URLs that you want to block or delete the ones you don't want to block and then upload to a web site and change the URL in the code to your custom one.

TIP: Be aware that the more URLs in the file the more RAM that you will be eating from your box.

Check the file size and your free memory to see if it will suit you. If not just erase some URLs…

Automatic Connection Repair (always_on.sh)

* Pings your default gateway every time and force a DHCP renew if no packets are received.
Usage: /path/to/always_on.sh &

#!/bin/sh
INTERVAL=10
PACKETS=1
UDHCPC="udhcpc -i vlan1 -p /var/run/udhcpc.pid -s /tmp/udhcpc"
IFACE=vlan1

ME=`basename $0`
RUNNING=`ps | awk '/'"$ME"'/ {++x}; END {print x+0}'`
if [ "$RUNNING" -gt 3 ]; then
   echo "Another instance of \"$ME\" is running"
   exit 1
fi

while sleep $INTERVAL
do
   TARGET=`ip route | awk '/default via/ {print $3}'`
   RET=`ping -c $PACKETS $TARGET 2> /dev/null | awk '/packets received/ {print $4}'`

   if [ "$RET" -ne "$PACKETS" ]; then
      echo "Ping failed, releasing IP address on $IFACE"
    #send a RELEASE signal
      kill -USR2 `cat /var/run/udhcpc.pid` 2> /dev/null
    #ensure udhcpc is not running
      killall udhcpc 2> /dev/null
      echo "Renewing IP address: $IFACE"
      $UDHCPC
      echo "Waiting 10 s..."
      sleep 10
   else
      echo "Network is up via $TARGET"
   fi
done

* The following version will work even on resource-starved Linksys WRT54G v8, which lacks most programs needed by the script above. To use it, just add this code to box startup script using the web interface.

INTERVAL=10
while true; do
  while [ \! $gw ]; do
    sleep 30
    route -n >/tmp/routes
    while read dest gw foo; do
      if [ $dest = "0.0.0.0" ]; then
        break
      fi
    done
    </tmp/routes
  done
  logger "auto-repair: default gateway is $gw"
  while ping -qc 2 $gw >/dev/null ; do
    sleep $INTERVAL
  done
  logger "auto-repair: gateway down, restarting WAN"
  kill -USR1 `cat /var/run/udhcpc.pid`
  unset gw
done &

Web Server Wake-up

* Wakes up your web server when the router receives a request from the internet.

Please note: syslogd needs to be on, logging enabled, with log level set high, and "accepted" on.

Following the example script, replace target and MAC values with those of your LAN web server's network information and for "$WOL -i xxx.xxx.xxx.255", replace xxx.xxx.xxx.255 with your LAN network broadcast address.

#!/bin/sh

INTERVAL=5
NUMP=3
OLD=""
WOL=/usr/sbin/wol
TARGET=192.168.1.100
MAC=00:00:00:00:00:00
LOGFILE="/tmp/www/wol.log"

while sleep $INTERVAL;do
  NEW=`awk '/ACCEPT/ && /DST='"$TARGET"'/ && /DPT=80/ {print $3}' /var/log/messages | tail -1`
  SRC=`awk -F'[=| ]' '/ACCEPT/ && /DST='"$TARGET"'/ && /DPT=80/ {print $13}' /var/log/messages | tail -1`
  LINE=`awk '/ACCEPT/ && /DST='"$TARGET"'/ && /DPT=80/' /var/log/messages`
  if [ "$NEW" != "" -a "$NEW" != "$OLD" ]; then
    echo "$SRC $LINE"  >> $LOGFILE
    RET=`ping -c $NUMP $TARGET 2> /dev/null | awk '/packets received/ {print $4}'`
    if [ "$RET" -ne "$NUMP" ]; then
      echo "$SRC causes WOL at" `date`  >> $LOGFILE
      $WOL -i 192.168.1.255 -p 7 $MAC  >> $LOGFILE
      sleep 5
    fi
    OLD=$NEW
  fi
done

Backup settings and restore them

Credit to hardwarewizard and frater

#!/bin/sh
#########################################################
#   Script Requirements
#
#   Files:
#      vars_to_skip
#      vars_preferred
#
#   Programs:
#      curl
#########################################################

#########################################################
# setup variables
#
# DATE         - Date
# MAC         - Mac address
# FILE         - File Name Prefix
# CUR_DIR      - Current Directory
# transfer      - FTP Transfer ON/OFF (Default is OFF)
# FOLDER      - Location where backup scripts are stored
# VARFILE      - Location & Name of Temp File
# TO_ALL      - Location & Name of script File with all nvram variables
# TO_INCLUDE   - Location & Name of script File with essential nvram variables
# TO_EXCLUDE   - Location & Name of script File with dangerous nvram variables
# TO_PREFERRED   - Location & Name of script File with preferred nvram variables
#
#########################################################

DATE=`date +%m%d%Y`
MAC=`nvram get lan_hwaddr | tr -d ":"`
FILE=${MAC}.${DATE}
CUR_DIR=`dirname $0`
transfer=0
FOLDER=/opt/vars/backups
VARFILE=/opt/tmp/all_vars
TO_ALL=${FOLDER}/${MAC}.${DATE}.all.sh
TO_INCLUDE=${FOLDER}/${MAC}.${DATE}.essential.sh
TO_EXCLUDE=${FOLDER}/${MAC}.${DATE}.dangerous.sh
TO_PREFERRED=${FOLDER}/${MAC}.${DATE}.preferred.sh

#########################################################
#FTP Login information change to your info
#########################################################

FTPS=ftp://192.168.1.100/backups
USERPASS=user:pass

#########################################################
# read command line switches
#
#   example command lines
#
#   ./backupvars.sh -t
#
#   The above command with use the user and password and
#   server information embedded in this script.
#   (See FTP Login information above)
#
#
#   ./backupvars.sh -t -u user:pass -f ftp://192.168.1.100/backups
#
#   The above command with use the user and password and
#   server information from the command line
#
#########################################################

while getopts tu:f: name
do
  case $name in
  t)   transfer=1;;
  u)   USERPASS="$OPTARG";;
  f)   FTPS="$OPTARG";;
  ?)   printf "Usage: %s: [-t] [-u username:password] [-f ftpserver]\n" $0
       exit 2;;
  esac
done
shift $(($OPTIND - 1))

#########################################################
#create NVRAM variale list and write to /opt/tmp/all_vars
#########################################################

nvram show 2>/dev/null | egrep '^[A-Za-z][A-Za-z0-9_\.\-]*=' | awk -F = '{print $1}' | sort -r -u >${VARFILE}

#########################################################
# Write header to restore scripts
#########################################################

echo -e "#!/bin/sh\n#\necho \"Write variables\"\n" | tee -i ${TO_EXCLUDE} | tee -i ${TO_PREFERRED} | tee -i  ${TO_ALL} > ${TO_INCLUDE}

#########################################################
# scan NVRAM variable list and send variable to proper
# restore script
#########################################################

cat ${VARFILE} | while read var
do
  pref=0
  if echo "${var}" | grep -q -f "${CUR_DIR}/vars_to_skip" ; then
    bfile=$TO_EXCLUDE
  else
    bfile=$TO_INCLUDE
    pref=`echo "${var}" | grep -cf "${CUR_DIR}/vars_preferred"`
  fi

  # get the data out of the variable
  data=`nvram get ${var}`
  # write the var to the file and use \ for special chars: (\$`")
  echo -en "nvram set ${var}=\"" | tee -ia ${TO_ALL} >> ${bfile}
  echo -n "${data}" |  sed -e 's/[$`"\]/\\&/g' | tee -ia  ${TO_ALL} >> ${bfile}
  echo -e "\"" | tee -ia  ${TO_ALL} >> ${bfile}
  if [ ! ${pref} == 0 ]; then
    echo -en "nvram set ${var}=\"" >> ${TO_PREFERRED}
    echo -n "${data}" |  sed -e 's/[$`"\]/\\&/g' >> ${TO_PREFERRED}
    echo -e "\"" >> ${TO_PREFERRED}
  fi
done

#########################################################
# cleanup remove /opt/tmp/all_vars
# uncomment to remove file
#########################################################

# rm ${VARFILE}

#########################################################
# Write footer to restore script
#########################################################

echo -e "\n# Commit variables\necho \"Save variables to nvram\"\nnvram commit"  | tee -ia  ${TO_ALL} | tee -ia  ${TO_PREFERRED} | tee -ia  ${TO_EXCLUDE} >> ${TO_INCLUDE}

#########################################################
# Change permissions on restore scripts to make them
# executable
#########################################################

chmod +x ${TO_INCLUDE}
chmod +x ${TO_PREFERRED}
chmod +x ${TO_EXCLUDE}
chmod +x ${TO_ALL}

#########################################################
# Compress restore scripts and send them to ftp server
#########################################################

if [ ${transfer} -ne 0 ] ; then
  tar cpf - -C / "${TO_INCLUDE}" 2>/dev/null | gzip -c |  /opt/bin/curl -s -u ${USERPASS} "${FTPS}/${FILE}.essential.sh.tgz" -T -
  tar cpf - -C / "${TO_PREFERRED}" 2>/dev/null | gzip -c |  /opt/bin/curl -s -u ${USERPASS} "${FTPS}/${FILE}.preferred.sh.tgz" -T -
  tar cpf - -C / "${TO_EXCLUDE}" 2>/dev/null | gzip -c |  /opt/bin/curl -s -u ${USERPASS} "${FTPS}/${FILE}.dangerous.sh.tgz" -T -
  tar cpf - -C / "${TO_ALL}" 2>/dev/null | gzip -c |  /opt/bin/curl -s -u ${USERPASS} "${FTPS}/${FILE}.all.sh.tgz" -T -
fi

The vars_to_skip file

DD_BOARD
^board
browser_method
^cfe
ct_modules
custom_shutdown_command
^def_
^default_
dist_type
dl_ram_addr
early_startup_command
^et0
^et1
^ezc
generate_key
gozila_action
gpio
^hardware
^is_
^kernel_
lan_default
^lan_hw
^lan_ifname
landevs
manual_boot_nv
misc_io_mode
need_commit
^os_
overclocking
pa0maxpwr
phyid_num
pmon_ver
pppd_pppifname
pppoe_ifname
pppoe_wan_ifname
primary_ifname
probe_blacklist
regulation_domain
rescue
reset_
scratch
sdram
^sh_
^skip
sshd_dss_host_key
sshd_rsa_host_key
startup_command
^wan_default
^wan_hw
^wan_if
^wan_vport
^wandevs
web_hook_libraries
^wifi_
wl0.1_hwaddr
wl0.2_hwaddr
wl0.3_hwaddr
wl0_hwaddr
wl0_ifname
wl0_radioids
^wl_
^wlan_

The vars_preferred file.

This is the file you add your vars to that you want to backup.

daylight_time
time_zone

Haserl UNIX bash-like shell or Lua [1]

is a small cgi wrapper that allows "PHP" style cgi programming, but uses a UNIX bash-like shell or Lua as the programming language. It is very small, so it can be used in embedded environments, or where something like PHP is too big.

It combines three features into a small cgi engine:

It parses POST and GET requests, placing form-elements as name=value pairs into the environment for the CGI script to use.

This is somewhat like the uncgi wrapper.

It opens a shell, and translates all text into printable state- ments. All text within <% … %> constructs are passed verbatim to the shell. This is somewhat like writing PHP scripts.

It can optionally be installed to drop its permissions to the owner of the script, giving it some of the security features of suexec or cgiwrapper.

Simple Command

#!/usr/local/bin/haserl
                  content-type: text/plain
 
                  <%# This is a sample "env" script %>
                  <% env %>

Prints the results of the env command as a mime-type "text/plain" document. This is the haserl version of the common printenv cgi.

Looping with dynamic output

#!/usr/local/bin/haserl
                  Content-type: text/html
 
                  <html>
                  <body>
                  <table border=1><tr>
                  <% for a in Red Blue Yellow Cyan; do %>
                       <td bgcolor="<% echo -n "$a" %>"><% echo -n "$a" %></td>
                       <% done %>
                  </tr></table>
                  </body>
                  </html>

Sends a mime-type "text/html" document to the client, with an html table of with elements labeled with the background color.

/opt/etc/init.d:

Currently, startup scripts for added packages are placed into the /opt/etc/init.d directory prefixed by an "S" and a number. This suggestion would change the startup process to be more like svr4. Instead of placing the S* scripts into /etc/opt/init.d, the unprefixed scripts would be placed there, and a S* prefixed link to each script would be placed into a new directrory named, /opt/etc/rc.d.

This change makes it simple to modify what services get run when the slug starts. Only the links in /etc/opt/rc.d need to be changed to change the behavior of the slug. Proper runlevel support could be added later if needed.

/etc/init.d # ls -C

S50inetd mount.rcS rcS rcS1 syslog.rcS

/etc/init.d/rcS1

  1. Start all init scripts in /etc/init.d
  2. executing them in numerical order.

references:

[1] - haserl manpage for 0.9.24

BootUtils

BootUtils is a collection of utilities to facilitate booting of Linux 2.6-based systems.

http://freshmeat.net/projects/bootutils

Pivot_Root

pivot_root moves the root file system of the current process to the directory put_old and makes new_root the new root file system.

http://linux.die.net/man/8/pivot_root

The main difference is that pivot_root is intended to switch the complete system over to a new root directory and remove dependencies on the old one, so that you would be able to unmount the original root directory and proceed as if it had never been in use.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License