Author Archive

Developing Apps within Android’s 16MB Memory Limit

Friday, July 16th, 2010

One challenge to developing for the Android platform is how to squeeze everything into 16 megabytes of heap space.  App-phones with 16GB and 32GB are common, but that is solid state storage and not RAM.  For Android applications, the limit for each application is 16MB (24MB on newer Droid and Nexus One phones).

Images, audio, and video are memory-intensive items, and many apps have these features. There are tools to help monitor memory use (e.g. Eclipse MAT, Android DDMS), and these tools are good for diagnosing problems, but you still need to understand enough to be able to fix memory leaks.

Here are some ideas for reducing the memory footprint of your application:

Reduce image sizes:  Lower the width, height, pixel bit-depth, and compress your images as much as you can.  Of course when an image is uncompressed and loaded into a Bitmap object then it takes up more memory, but you can reduce the memory footprint by lowering the image quality (for example see: View.setDrawingCacheQuality and View.DRAWING_CACHE_QUALITY_LOW) or even disabling the cache on views containing images.

Lower audio and video bitrates: I don’t know this for a fact, but I would guess that a lower-bitrate audio stream may have a smaller memory requirement during playback.  For example a mono-48 kbit/second audio file would require decoded fewer samples per second than a stereo-192 kbit/second file. (Please comment to this post if you test this theory or know the answer.)

Destroy or reuse objects: When you can, re-use objects and make sure that old objects are fully-destroyed. when they are no used anymore.  Even better, never create objects in the first place if possible.  This is especially try for bitmap objects – be sure to call the Bitmap.recycle() method. Remember to clear callback methods of objects before destroying them, since otherwise an object may not be properly returned to the memory heap during a java garbage collection operation.

Use final and static:  Virtual methods take up more space (and are slower) than static methods.  Final variables and arrays are stored in code space and not the memory heap.  Granted the difference is very small compared with 16MB of space, but every little bit counts!

Separate applications for localization:  If you are developing apps for multiple languages, consider creating separate applications instead of including all the language-specific strings, images, audio files, and videos in a single application.

Rely on external storage:  If you know that there is smart-card memory available, use that to store data instead of in memory.

Revert to an earlier Android SDK: When we reverted our most-memory-challenged Android application from Android 2.2 to Android 1.5, we gained two important things: first, we are now compatible with almost all existing Android phones; and second we reduced our memory footprint by almost a megabyte.  This latter statement is extremely interesting, since it indicates that the Android framework is getting bloated by all the new features added between versions 1.5 and 2.2.

Matt Clark worked in academia, corporate research labs and several technology startup companies prior to GORGES. His expertise is software architecture, database development, and system administration. Matt brings GORGES over 25 years experience developing fast and robust software on a multitude of platforms and languages.

Distributed Dictionary Attack Solutions

Saturday, June 26th, 2010

We have had the misfortune of having attempted distributed dictionary attacks on our Linux servers.  A dictionary attack uses a long list of common usernames and passwords trying to find a way to gain a foothold and eventually root access of a password-protected server.

Our servers use utilities such as fail2ban or denyhosts that look for repeated failed login attempts, and once found they direct the firewall service to ban the originating IP addresses.  However this technique fails when the attack is distributed among thousands of compromised “zombie” computers that are doing the bidding of a malicious hacker.

Our log files correctly diagnosed each attempt from an individual IP address, but a new attempt was immediately started from a different IP address.  We were clearly looking at an attack coordinated from a single unknown source.

There are several ways to reduce or thwart these attacks, including:

  • never allow remote root logins (but attacks still occur on non-root-user names)
  • have a chroot jail shell in case an attack on a non-root account succeeds
  • changing SSH service to use a non-obvious port (such as port 5022 instead of 22)
  • deactivate password authentication and rely exclusively on authentication keys
  • restrict allowed IP address by country of origin
  • only allow certain IP addresses or ranges of addresses to have access

We chose to implement more than one of these solutions, and I wanted to share some techniques we used for our implementation.

For the last rule that only allows certain IP addresses, I wanted to start with a list of valid IP addresses used in the last month.  The following script extracts these IP numbers from our SSH log file, sorts them alphabetically, and then removes duplicates.  Note that this server uses Fedora – you may need to tweak it for other linux distributions.

root# fgrep "Accepted" /var/log/secure* | awk '{print $11}' | sort | uniq
166.77.6.4
205.232.34.1
67.255.5.155
...

The IP addresses from the above script should be added to the file /etc/hosts.allow in the following format:

# hosts.allow   This file contains access rules which are used to
#               allow or deny connections to network services that
#               either use the tcp_wrappers library or that have been
#               started through a tcp_wrappers-enabled xinetd.
#
#               See 'man 5 hosts_options' and 'man 5 hosts_access'
#               for information on rule syntax.
#               See 'man tcpd' for information on tcp_wrappers

# allow local addresses
all: 127.0.0.1
all: 192.168.1.*

# valid IP addresses gathered June 2010
all: 166.77.6.4
all: 205.232.34.1
all: 67.255.5.155
...

Now disallow all other IP addresses for SSH by editing the file /etc/hosts.deny:

# hosts.deny    This file contains access rules which are used to
#               deny connections to network services that either use
#               the tcp_wrappers library or that have been
#               started through a tcp_wrappers-enabled xinetd.
#
#               The rules in this file can also be set up in
#               /etc/hosts.allow with a 'deny' option instead.
#
#               See 'man 5 hosts_options' and 'man 5 hosts_access'
#               for information on rule syntax.
#               See 'man tcpd' for information on tcp_wrappers
#
# The portmap line is redundant, but it is left to remind you that
# the new secure portmap uses hosts.deny and hosts.allow.  In particular
# you should know that NFS uses portmap!

# deny SSH service except for IP numbers in /etc/hosts.allow file
sshd: all

Restart your SSH service, and your server should now be a bit more secure against distributed dictionary attacks:

root# service sshd restart

An Internet search using keywords from the other mentioned solutions above will teach you how to change SSH port, disallow password authentication, etc.

The distributed dictionary attack has been going on for five straight days. By my informal estimates, there have been about 30,000 attempts to break in on our coyglen server.

After weighing options, I decided to restrict access by IP number. I was a bit gun-shy after Friday night’s mistake of trying to restrict by country of origin and subsequent onsite hard-reboot.

Below I have pasted the unique usernames and IP addresses used for valid SSH logins on coyglen in the last 30 days. I used the IP#s to create a list of valid computers and added them to the /etc/hosts.allow file.

After restarting the SSH service, I am delighted to see many connection-refusal messages.

If a customer cannot get access using SSH or SFTP (note: insecure FTP is not supported on this server), then have them send you an e-mail message. We will open up their e-mail headers and look at the IP#, then add it to the allowed list.

I have not applied this solution to our other servers, but will if needed. If someone controls a “zombie” network, then it is trivial to direct attacks like this trying to find insecure hosting servers. I expect more of these to happen in the future.

Matt

[root@coyglen log]# fgrep “Accepted” secure* | awk ‘{print $9}’ | sort | uniq

cogentex

csg

csg2

dgreen

elimilice

gorges

gorges-blog

gorges-test

healthytest

myteambook

napoli

netway-dev

ngrown

paramount

pmpauthors

qbuilder

retweeter

root

royaltystat

sales.wwm

stablecom.sta

stlnps

userfinity

valmontgod

[root@coyglen log]# fgrep “Accepted” secure* | awk ‘{print $11}’ | sort | uniq

166.137.136.169

166.77.6.4

184.74.139.251

192.168.1.3

208.105.225.93

24.58.62.167

24.58.67.78

24.59.191.200

38.108.102.253

64.57.177.68

64.57.178.15

66.180.184.17

67.244.55.108

67.246.70.140

67.255.18.108

67.255.3.244

67.255.5.155

69.205.224.88

70.94.56.13

71.181.154.195

71.181.238.165

71.183.96.7

72.43.91.102

74.66.27.169

Matt Clark worked in academia, corporate research labs and several technology startup companies prior to GORGES. His expertise is software architecture, database development, and system administration. Matt brings GORGES over 25 years experience developing fast and robust software on a multitude of platforms and languages.

Android Two-Dimensional ScrollView

Wednesday, June 2nd, 2010

Recently, while developing mobile applications for the Android platform, we were pleasantly surprised to see how much the internal display classes work like Java’s Swing components.  The online Android documentation was good, and there were plenty of available example apps to help speed us along.

However there is a glaring limitation:  there are base classes for horizontal scrollviews and vertical scrollviews, but not one where one can scroll in two dimensions at the same time.

It would be a challenge to write a two-dimensional scrollview class from scratch.  Luckily for us, the entire Android platform is open-source, so we had access to both the vertical and horizontal scrollview source code.  After a few hours of work we had created a new TwoDScrollView class.

First, here is a disclaimer: this class has been “munged” together and is not bullet-proof for a true generalized solution.  For example the methods that handle sub-view focusing have not been tested, and there are some nuances about how to prioritize focused sub-views in two-dimensions.  I have a fully-stripped version of this class without sub-view focusing or key events that I’d be happy to share upon request.

Without further ado, here is the new TwoDScrollView class:

/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * Revised 5/19/2010 by GORGES
 * Now supports two-dimensional view scrolling
 * http://GORGES.us
 */

package us.gorges.my_package;

import java.util.List;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.FocusFinder;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Scroller;
import android.widget.TextView;

/**
 * Layout container for a view hierarchy that can be scrolled by the user,
 * allowing it to be larger than the physical display.  A TwoDScrollView
 * is a {@link FrameLayout}, meaning you should place one child in it
 * containing the entire contents to scroll; this child may itself be a layout
 * manager with a complex hierarchy of objects.  A child that is often used
 * is a {@link LinearLayout} in a vertical orientation, presenting a vertical
 * array of top-level items that the user can scroll through.
 *
 * <p>The {@link TextView} class also
 * takes care of its own scrolling, so does not require a TwoDScrollView, but
 * using the two together is possible to achieve the effect of a text view
 * within a larger container.
 */
public class TwoDScrollView extends FrameLayout {
 static final int ANIMATED_SCROLL_GAP = 250;
 static final float MAX_SCROLL_FACTOR = 0.5f;

 private long mLastScroll;

 private final Rect mTempRect = new Rect();
 private Scroller mScroller;

 /**
 * Flag to indicate that we are moving focus ourselves. This is so the
 * code that watches for focus changes initiated outside this TwoDScrollView
 * knows that it does not have to do anything.
 */
 private boolean mTwoDScrollViewMovedFocus;

 /**
 * Position of the last motion event.
 */
 private float mLastMotionY;
 private float mLastMotionX;

 /**
 * True when the layout has changed but the traversal has not come through yet.
 * Ideally the view hierarchy would keep track of this for us.
 */
 private boolean mIsLayoutDirty = true;

 /**
 * The child to give focus to in the event that a child has requested focus while the
 * layout is dirty. This prevents the scroll from being wrong if the child has not been
 * laid out before requesting focus.
 */
 private View mChildToScrollTo = null;

 /**
 * True if the user is currently dragging this TwoDScrollView around. This is
 * not the same as 'is being flinged', which can be checked by
 * mScroller.isFinished() (flinging begins when the user lifts his finger).
 */
 private boolean mIsBeingDragged = false;

 /**
 * Determines speed during touch scrolling
 */
 private VelocityTracker mVelocityTracker;

 /**
 * Whether arrow scrolling is animated.
 */
 private int mTouchSlop;
 private int mMinimumVelocity;
 private int mMaximumVelocity;

 public TwoDScrollView(Context context) {
   super(context);
   initTwoDScrollView();
 }

 public TwoDScrollView(Context context, AttributeSet attrs) {
   super(context, attrs);
   initTwoDScrollView();
 }

 public TwoDScrollView(Context context, AttributeSet attrs, int defStyle) {
   super(context, attrs, defStyle);
   initTwoDScrollView();
 }

 @Override
 protected float getTopFadingEdgeStrength() {
   if (getChildCount() == 0) {
     return 0.0f;
   }
   final int length = getVerticalFadingEdgeLength();
   if (getScrollY() < length) {
     return getScrollY() / (float) length;
   }
   return 1.0f;
 }

 @Override
 protected float getBottomFadingEdgeStrength() {
   if (getChildCount() == 0) {
     return 0.0f;
   }
   final int length = getVerticalFadingEdgeLength();
   final int bottomEdge = getHeight() - getPaddingBottom();
   final int span = getChildAt(0).getBottom() - getScrollY() - bottomEdge;
   if (span < length) {
     return span / (float) length;
   }
   return 1.0f;
 }

 @Override
 protected float getLeftFadingEdgeStrength() {
   if (getChildCount() == 0) {
     return 0.0f;
   }
   final int length = getHorizontalFadingEdgeLength();
   if (getScrollX() < length) {
     return getScrollX() / (float) length;
   }
   return 1.0f;
 }

 @Override
 protected float getRightFadingEdgeStrength() {
   if (getChildCount() == 0) {
     return 0.0f;
   }
   final int length = getHorizontalFadingEdgeLength();
   final int rightEdge = getWidth() - getPaddingRight();
   final int span = getChildAt(0).getRight() - getScrollX() - rightEdge;
   if (span < length) {
     return span / (float) length;
   }
   return 1.0f;
 }

 /**
 * @return The maximum amount this scroll view will scroll in response to
 *   an arrow event.
 */
 public int getMaxScrollAmountVertical() {
   return (int) (MAX_SCROLL_FACTOR * getHeight());
 }
 public int getMaxScrollAmountHorizontal() {
   return (int) (MAX_SCROLL_FACTOR * getWidth());
 }

 private void initTwoDScrollView() {
   mScroller = new Scroller(getContext());
   setFocusable(true);
   setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
   setWillNotDraw(false);
   final ViewConfiguration configuration = ViewConfiguration.get(getContext());
   mTouchSlop = configuration.getScaledTouchSlop();
   mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
   mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
 }

 @Override
 public void addView(View child) {
   if (getChildCount() > 0) {
     throw new IllegalStateException("TwoDScrollView can host only one direct child");
   }
   super.addView(child);
 }

 @Override
 public void addView(View child, int index) {
   if (getChildCount() > 0) {
     throw new IllegalStateException("TwoDScrollView can host only one direct child");
   }
   super.addView(child, index);
 }

 @Override
 public void addView(View child, ViewGroup.LayoutParams params) {
   if (getChildCount() > 0) {
     throw new IllegalStateException("TwoDScrollView can host only one direct child");
   }
   super.addView(child, params);
 }

 @Override
 public void addView(View child, int index, ViewGroup.LayoutParams params) {
   if (getChildCount() > 0) {
     throw new IllegalStateException("TwoDScrollView can host only one direct child");
   }
   super.addView(child, index, params);
 }

 /**
 * @return Returns true this TwoDScrollView can be scrolled
 */
 private boolean canScroll() {
   View child = getChildAt(0);
   if (child != null) {
     int childHeight = child.getHeight();
     int childWidth = child.getWidth();
     return (getHeight() < childHeight + getPaddingTop() + getPaddingBottom()) ||
            (getWidth() < childWidth + getPaddingLeft() + getPaddingRight());
   }
   return false;
 }

 @Override
 public boolean dispatchKeyEvent(KeyEvent event) {
   // Let the focused view and/or our descendants get the key first
   boolean handled = super.dispatchKeyEvent(event);
   if (handled) {
     return true;
   }
   return executeKeyEvent(event);
 }

 /**
 * You can call this function yourself to have the scroll view perform
 * scrolling from a key event, just as if the event had been dispatched to
 * it by the view hierarchy.
 *
 * @param event The key event to execute.
 * @return Return true if the event was handled, else false.
 */
 public boolean executeKeyEvent(KeyEvent event) {
   mTempRect.setEmpty();
   if (!canScroll()) {
     if (isFocused()) {
       View currentFocused = findFocus();
       if (currentFocused == this) currentFocused = null;
       View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_DOWN);
       return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_DOWN);
     }
     return false;
   }
   boolean handled = false;
   if (event.getAction() == KeyEvent.ACTION_DOWN) {
     switch (event.getKeyCode()) {
       case KeyEvent.KEYCODE_DPAD_UP:
         if (!event.isAltPressed()) {
           handled = arrowScroll(View.FOCUS_UP, false);
         } else {
           handled = fullScroll(View.FOCUS_UP, false);
         }
         break;
       case KeyEvent.KEYCODE_DPAD_DOWN:
         if (!event.isAltPressed()) {
           handled = arrowScroll(View.FOCUS_DOWN, false);
         } else {
           handled = fullScroll(View.FOCUS_DOWN, false);
         }
         break;
       case KeyEvent.KEYCODE_DPAD_LEFT:
         if (!event.isAltPressed()) {
           handled = arrowScroll(View.FOCUS_UP, true);
         } else {
           handled = fullScroll(View.FOCUS_UP, true);
         }
         break;
       case KeyEvent.KEYCODE_DPAD_RIGHT:
         if (!event.isAltPressed()) {
           handled = arrowScroll(View.FOCUS_DOWN, true);
         } else {
           handled = fullScroll(View.FOCUS_DOWN, true);
         }
         break;
     }
   }
   return handled;
 }

 @Override
 public boolean onInterceptTouchEvent(MotionEvent ev) {
   /*
   * This method JUST determines whether we want to intercept the motion.
   * If we return true, onMotionEvent will be called and we do the actual
   * scrolling there.
   *
   * Shortcut the most recurring case: the user is in the dragging
   * state and he is moving his finger.  We want to intercept this
   * motion.
   */
   final int action = ev.getAction();
   if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
     return true;
   }
   if (!canScroll()) {
     mIsBeingDragged = false;
     return false;
   }
   final float y = ev.getY();
   final float x = ev.getX();
   switch (action) {
     case MotionEvent.ACTION_MOVE:
       /*
       * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
       * whether the user has moved far enough from his original down touch.
       */
       /*
       * Locally do absolute value. mLastMotionY is set to the y value
       * of the down event.
       */
       final int yDiff = (int) Math.abs(y - mLastMotionY);
       final int xDiff = (int) Math.abs(x - mLastMotionX);
       if (yDiff > mTouchSlop || xDiff > mTouchSlop) {
         mIsBeingDragged = true;
       }
       break;

     case MotionEvent.ACTION_DOWN:
       /* Remember location of down touch */
       mLastMotionY = y;
       mLastMotionX = x;

       /*
       * If being flinged and user touches the screen, initiate drag;
       * otherwise don't.  mScroller.isFinished should be false when
       * being flinged.
       */
       mIsBeingDragged = !mScroller.isFinished();
       break;

     case MotionEvent.ACTION_CANCEL:
     case MotionEvent.ACTION_UP:
       /* Release the drag */
       mIsBeingDragged = false;
       break;
   }

   /*
   * The only time we want to intercept motion events is if we are in the
   * drag mode.
   */
   return mIsBeingDragged;
 }

 @Override
 public boolean onTouchEvent(MotionEvent ev) {

   if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
     // Don't handle edge touches immediately -- they may actually belong to one of our
     // descendants.
     return false;
   }

   if (!canScroll()) {
     return false;
   }

   if (mVelocityTracker == null) {
     mVelocityTracker = VelocityTracker.obtain();
   }
   mVelocityTracker.addMovement(ev);

   final int action = ev.getAction();
   final float y = ev.getY();
   final float x = ev.getX();

   switch (action) {
     case MotionEvent.ACTION_DOWN:
       /*
       * If being flinged and user touches, stop the fling. isFinished
       * will be false if being flinged.
       */
       if (!mScroller.isFinished()) {
         mScroller.abortAnimation();
       }

       // Remember where the motion event started
       mLastMotionY = y;
       mLastMotionX = x;
       break;
     case MotionEvent.ACTION_MOVE:
       // Scroll to follow the motion event
       int deltaX = (int) (mLastMotionX - x);
       int deltaY = (int) (mLastMotionY - y);
       mLastMotionX = x;
       mLastMotionY = y;

       if (deltaX < 0) {
         if (getScrollX() < 0) {
           deltaX = 0;
         }
       } else if (deltaX > 0) {
         final int rightEdge = getWidth() - getPaddingRight();
         final int availableToScroll = getChildAt(0).getRight() - getScrollX() - rightEdge;
         if (availableToScroll > 0) {
           deltaX = Math.min(availableToScroll, deltaX);
         } else {
           deltaX = 0;
         }
       }
       if (deltaY < 0) {
         if (getScrollY() < 0) {
           deltaY = 0;
         }
       } else if (deltaY > 0) {
         final int bottomEdge = getHeight() - getPaddingBottom();
         final int availableToScroll = getChildAt(0).getBottom() - getScrollY() - bottomEdge;
         if (availableToScroll > 0) {
           deltaY = Math.min(availableToScroll, deltaY);
         } else {
           deltaY = 0;
         }
       }
       if (deltaY != 0 || deltaX != 0)
         scrollBy(deltaX, deltaY);
       break;
     case MotionEvent.ACTION_UP:
         final VelocityTracker velocityTracker = mVelocityTracker;
         velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
         int initialXVelocity = (int) velocityTracker.getXVelocity();
         int initialYVelocity = (int) velocityTracker.getYVelocity();
         if ((Math.abs(initialXVelocity) + Math.abs(initialYVelocity) > mMinimumVelocity) && getChildCount() > 0) {
           fling(-initialXVelocity, -initialYVelocity);
         }
         if (mVelocityTracker != null) {
           mVelocityTracker.recycle();
           mVelocityTracker = null;
         }
   }
   return true;
 }

 /**
  * Finds the next focusable component that fits in this View's bounds
  * (excluding fading edges) pretending that this View's top is located at
  * the parameter top.
  *
  * @param topFocus           look for a candidate is the one at the top of the bounds
  *                           if topFocus is true, or at the bottom of the bounds if topFocus is
  *                           false
  * @param top                the top offset of the bounds in which a focusable must be
  *                           found (the fading edge is assumed to start at this position)
  * @param preferredFocusable the View that has highest priority and will be
  *                           returned if it is within my bounds (null is valid)
  * @return the next focusable component in the bounds or null if none can be
  *         found
  */
 private View findFocusableViewInMyBounds(final boolean topFocus, final int top, final boolean leftFocus, final int left, View preferredFocusable) {
   /*
   * The fading edge's transparent side should be considered for focus
   * since it's mostly visible, so we divide the actual fading edge length
   * by 2.
   */
   final int verticalFadingEdgeLength = getVerticalFadingEdgeLength() / 2;
   final int topWithoutFadingEdge = top + verticalFadingEdgeLength;
   final int bottomWithoutFadingEdge = top + getHeight() - verticalFadingEdgeLength;
   final int horizontalFadingEdgeLength = getHorizontalFadingEdgeLength() / 2;
   final int leftWithoutFadingEdge = left + horizontalFadingEdgeLength;
   final int rightWithoutFadingEdge = left + getWidth() - horizontalFadingEdgeLength;

   if ((preferredFocusable != null)
     && (preferredFocusable.getTop() < bottomWithoutFadingEdge)
     && (preferredFocusable.getBottom() > topWithoutFadingEdge)
     && (preferredFocusable.getLeft() < rightWithoutFadingEdge)
     && (preferredFocusable.getRight() > leftWithoutFadingEdge)) {
     return preferredFocusable;
   }
   return findFocusableViewInBounds(topFocus, topWithoutFadingEdge, bottomWithoutFadingEdge, leftFocus, leftWithoutFadingEdge, rightWithoutFadingEdge);
 }

 /**
 * Finds the next focusable component that fits in the specified bounds.
 * </p>
 *
 * @param topFocus look for a candidate is the one at the top of the bounds
 *                 if topFocus is true, or at the bottom of the bounds if topFocus is
 *                 false
 * @param top      the top offset of the bounds in which a focusable must be
 *                 found
 * @param bottom   the bottom offset of the bounds in which a focusable must
 *                 be found
 * @return the next focusable component in the bounds or null if none can
 *         be found
 */
 private View findFocusableViewInBounds(boolean topFocus, int top, int bottom, boolean leftFocus, int left, int right) {
   List<View> focusables = getFocusables(View.FOCUS_FORWARD);
   View focusCandidate = null;

   /*
   * A fully contained focusable is one where its top is below the bound's
   * top, and its bottom is above the bound's bottom. A partially
   * contained focusable is one where some part of it is within the
   * bounds, but it also has some part that is not within bounds.  A fully contained
   * focusable is preferred to a partially contained focusable.
   */
   boolean foundFullyContainedFocusable = false;

   int count = focusables.size();
   for (int i = 0; i < count; i++) {
     View view = focusables.get(i);
     int viewTop = view.getTop();
     int viewBottom = view.getBottom();
     int viewLeft = view.getLeft();
     int viewRight = view.getRight();

     if (top < viewBottom && viewTop < bottom && left < viewRight && viewLeft < right) {
       /*
       * the focusable is in the target area, it is a candidate for
       * focusing
       */
       final boolean viewIsFullyContained = (top < viewTop) && (viewBottom < bottom) && (left < viewLeft) && (viewRight < right);
       if (focusCandidate == null) {
         /* No candidate, take this one */
         focusCandidate = view;
         foundFullyContainedFocusable = viewIsFullyContained;
       } else {
         final boolean viewIsCloserToVerticalBoundary =
           (topFocus && viewTop < focusCandidate.getTop()) ||
           (!topFocus && viewBottom > focusCandidate.getBottom());
         final boolean viewIsCloserToHorizontalBoundary =
           (leftFocus && viewLeft < focusCandidate.getLeft()) ||
           (!leftFocus && viewRight > focusCandidate.getRight());
         if (foundFullyContainedFocusable) {
           if (viewIsFullyContained && viewIsCloserToVerticalBoundary && viewIsCloserToHorizontalBoundary) {
             /*
              * We're dealing with only fully contained views, so
              * it has to be closer to the boundary to beat our
              * candidate
              */
             focusCandidate = view;
           }
         } else {
           if (viewIsFullyContained) {
             /* Any fully contained view beats a partially contained view */
             focusCandidate = view;
             foundFullyContainedFocusable = true;
           } else if (viewIsCloserToVerticalBoundary && viewIsCloserToHorizontalBoundary) {
             /*
              * Partially contained view beats another partially
              * contained view if it's closer
              */
             focusCandidate = view;
           }
         }
       }
     }
   }
   return focusCandidate;
 }

 /**
  * <p>Handles scrolling in response to a "home/end" shortcut press. This
  * method will scroll the view to the top or bottom and give the focus
  * to the topmost/bottommost component in the new visible area. If no
  * component is a good candidate for focus, this scrollview reclaims the
  * focus.</p>
  *
  * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
  *                  to go the top of the view or
  *                  {@link android.view.View#FOCUS_DOWN} to go the bottom
  * @return true if the key event is consumed by this method, false otherwise
  */
 public boolean fullScroll(int direction, boolean horizontal) {
   if (!horizontal) {
     boolean down = direction == View.FOCUS_DOWN;
     int height = getHeight();
     mTempRect.top = 0;
     mTempRect.bottom = height;
     if (down) {
       int count = getChildCount();
       if (count > 0) {
         View view = getChildAt(count - 1);
         mTempRect.bottom = view.getBottom();
         mTempRect.top = mTempRect.bottom - height;
       }
     }
     return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom, 0, 0, 0);
   } else {
     boolean right = direction == View.FOCUS_DOWN;
     int width = getWidth();
     mTempRect.left = 0;
     mTempRect.right = width;
     if (right) {
       int count = getChildCount();
       if (count > 0) {
         View view = getChildAt(count - 1);
         mTempRect.right = view.getBottom();
         mTempRect.left = mTempRect.right - width;
       }
     }
     return scrollAndFocus(0, 0, 0, direction, mTempRect.top, mTempRect.bottom);
   }
 }

 /**
  * <p>Scrolls the view to make the area defined by <code>top</code> and
  * <code>bottom</code> visible. This method attempts to give the focus
  * to a component visible in this area. If no component can be focused in
  * the new visible area, the focus is reclaimed by this scrollview.</p>
  *
  * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
  *                  to go upward
  *                  {@link android.view.View#FOCUS_DOWN} to downward
  * @param top       the top offset of the new area to be made visible
  * @param bottom    the bottom offset of the new area to be made visible
  * @return true if the key event is consumed by this method, false otherwise
  */
 private boolean scrollAndFocus(int directionY, int top, int bottom, int directionX, int left, int right) {
   boolean handled = true;
   int height = getHeight();
   int containerTop = getScrollY();
   int containerBottom = containerTop + height;
   boolean up = directionY == View.FOCUS_UP;
   int width = getWidth();
   int containerLeft = getScrollX();
   int containerRight = containerLeft + width;
   boolean leftwards = directionX == View.FOCUS_UP;
   View newFocused = findFocusableViewInBounds(up, top, bottom, leftwards, left, right);
   if (newFocused == null) {
     newFocused = this;
   }
   if ((top >= containerTop && bottom <= containerBottom) || (left >= containerLeft && right <= containerRight)) {
     handled = false;
   } else {
     int deltaY = up ? (top - containerTop) : (bottom - containerBottom);
     int deltaX = leftwards ? (left - containerLeft) : (right - containerRight);
     doScroll(deltaX, deltaY);
   }
   if (newFocused != findFocus() && newFocused.requestFocus(directionY)) {
     mTwoDScrollViewMovedFocus = true;
     mTwoDScrollViewMovedFocus = false;
   }
   return handled;
 }

 /**
  * Handle scrolling in response to an up or down arrow click.
  *
  * @param direction The direction corresponding to the arrow key that was
  *                  pressed
  * @return True if we consumed the event, false otherwise
  */
 public boolean arrowScroll(int direction, boolean horizontal) {
   View currentFocused = findFocus();
   if (currentFocused == this) currentFocused = null;
   View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
   final int maxJump = horizontal ? getMaxScrollAmountHorizontal() : getMaxScrollAmountVertical();

   if (!horizontal) {
     if (nextFocused != null) {
       nextFocused.getDrawingRect(mTempRect);
       offsetDescendantRectToMyCoords(nextFocused, mTempRect);
       int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
       doScroll(0, scrollDelta);
       nextFocused.requestFocus(direction);
     } else {
       // no new focus
       int scrollDelta = maxJump;
       if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) {
         scrollDelta = getScrollY();
       } else if (direction == View.FOCUS_DOWN) {
         if (getChildCount() > 0) {
           int daBottom = getChildAt(0).getBottom();
           int screenBottom = getScrollY() + getHeight();
           if (daBottom - screenBottom < maxJump) {
             scrollDelta = daBottom - screenBottom;
           }
         }
       }
       if (scrollDelta == 0) {
         return false;
       }
       doScroll(0, direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta);
     }
   } else {
     if (nextFocused != null) {
       nextFocused.getDrawingRect(mTempRect);
       offsetDescendantRectToMyCoords(nextFocused, mTempRect);
       int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
       doScroll(scrollDelta, 0);
       nextFocused.requestFocus(direction);
     } else {
       // no new focus
       int scrollDelta = maxJump;
       if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) {
         scrollDelta = getScrollY();
       } else if (direction == View.FOCUS_DOWN) {
         if (getChildCount() > 0) {
           int daBottom = getChildAt(0).getBottom();
           int screenBottom = getScrollY() + getHeight();
           if (daBottom - screenBottom < maxJump) {
             scrollDelta = daBottom - screenBottom;
           }
         }
       }
       if (scrollDelta == 0) {
         return false;
       }
       doScroll(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta, 0);
     }
   }
   return true;
 }

 /**
  * Smooth scroll by a Y delta
  *
  * @param delta the number of pixels to scroll by on the Y axis
  */
 private void doScroll(int deltaX, int deltaY) {
   if (deltaX != 0 || deltaY != 0) {
     smoothScrollBy(deltaX, deltaY);
   }
 }

 /**
  * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
  *
  * @param dx the number of pixels to scroll by on the X axis
  * @param dy the number of pixels to scroll by on the Y axis
  */
 public final void smoothScrollBy(int dx, int dy) {
   long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
   if (duration > ANIMATED_SCROLL_GAP) {
     mScroller.startScroll(getScrollX(), getScrollY(), dx, dy);
     awakenScrollBars(mScroller.getDuration());
     invalidate();
   } else {
     if (!mScroller.isFinished()) {
       mScroller.abortAnimation();
     }
     scrollBy(dx, dy);
   }
   mLastScroll = AnimationUtils.currentAnimationTimeMillis();
 }

 /**
  * Like {@link #scrollTo}, but scroll smoothly instead of immediately.
  *
  * @param x the position where to scroll on the X axis
  * @param y the position where to scroll on the Y axis
  */
 public final void smoothScrollTo(int x, int y) {
   smoothScrollBy(x - getScrollX(), y - getScrollY());
 }

 /**
  * <p>The scroll range of a scroll view is the overall height of all of its
  * children.</p>
  */
 @Override
 protected int computeVerticalScrollRange() {
   int count = getChildCount();
   return count == 0 ? getHeight() : (getChildAt(0)).getBottom();
 }
 @Override
 protected int computeHorizontalScrollRange() {
   int count = getChildCount();
   return count == 0 ? getWidth() : (getChildAt(0)).getRight();
 }

 @Override
 protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
   ViewGroup.LayoutParams lp = child.getLayoutParams();
   int childWidthMeasureSpec;
   int childHeightMeasureSpec;

   childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft() + getPaddingRight(), lp.width);
   childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);

   child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
 }

 @Override
 protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
   final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
   final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
   getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin + widthUsed, lp.width);
   final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);

   child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
 }

 @Override
 public void computeScroll() {
   if (mScroller.computeScrollOffset()) {
     // This is called at drawing time by ViewGroup.  We don't want to
     // re-show the scrollbars at this point, which scrollTo will do,
     // so we replicate most of scrollTo here.
     //
     //         It's a little odd to call onScrollChanged from inside the drawing.
     //
     //         It is, except when you remember that computeScroll() is used to
     //         animate scrolling. So unless we want to defer the onScrollChanged()
     //         until the end of the animated scrolling, we don't really have a
     //         choice here.
     //
     //         I agree.  The alternative, which I think would be worse, is to post
     //         something and tell the subclasses later.  This is bad because there
     //         will be a window where mScrollX/Y is different from what the app
     //         thinks it is.
     //
     int oldX = getScrollX();
     int oldY = getScrollY();
     int x = mScroller.getCurrX();
     int y = mScroller.getCurrY();
     if (getChildCount() > 0) {
       View child = getChildAt(0);
       scrollTo(clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(), child.getWidth()),
       clamp(y, getHeight() - getPaddingBottom() - getPaddingTop(), child.getHeight()));
     } else {
       scrollTo(x, y);
     }
     if (oldX != getScrollX() || oldY != getScrollY()) {
       onScrollChanged(getScrollX(), getScrollY(), oldX, oldY);
     }

     // Keep on drawing until the animation has finished.
     postInvalidate();
   }
 }

 /**
  * Scrolls the view to the given child.
  *
  * @param child the View to scroll to
  */
 private void scrollToChild(View child) {
   child.getDrawingRect(mTempRect);
   /* Offset from child's local coordinates to TwoDScrollView coordinates */
   offsetDescendantRectToMyCoords(child, mTempRect);
   int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
   if (scrollDelta != 0) {
     scrollBy(0, scrollDelta);
   }
 }

 /**
  * If rect is off screen, scroll just enough to get it (or at least the
  * first screen size chunk of it) on screen.
  *
  * @param rect      The rectangle.
  * @param immediate True to scroll immediately without animation
  * @return true if scrolling was performed
  */
 private boolean scrollToChildRect(Rect rect, boolean immediate) {
   final int delta = computeScrollDeltaToGetChildRectOnScreen(rect);
   final boolean scroll = delta != 0;
   if (scroll) {
     if (immediate) {
       scrollBy(0, delta);
     } else {
       smoothScrollBy(0, delta);
     }
   }
   return scroll;
 }

 /**
  * Compute the amount to scroll in the Y direction in order to get
  * a rectangle completely on the screen (or, if taller than the screen,
  * at least the first screen size chunk of it).
  *
  * @param rect The rect.
  * @return The scroll delta.
  */
 protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
   if (getChildCount() == 0) return 0;
   int height = getHeight();
   int screenTop = getScrollY();
   int screenBottom = screenTop + height;
   int fadingEdge = getVerticalFadingEdgeLength();
   // leave room for top fading edge as long as rect isn't at very top
   if (rect.top > 0) {
     screenTop += fadingEdge;
   }

   // leave room for bottom fading edge as long as rect isn't at very bottom
   if (rect.bottom < getChildAt(0).getHeight()) {
     screenBottom -= fadingEdge;
   }
   int scrollYDelta = 0;
   if (rect.bottom > screenBottom && rect.top > screenTop) {
     // need to move down to get it in view: move down just enough so
     // that the entire rectangle is in view (or at least the first
     // screen size chunk).
     if (rect.height() > height) {
       // just enough to get screen size chunk on
       scrollYDelta += (rect.top - screenTop);
     } else {
       // get entire rect at bottom of screen
       scrollYDelta += (rect.bottom - screenBottom);
     }

     // make sure we aren't scrolling beyond the end of our content
     int bottom = getChildAt(0).getBottom();
     int distanceToBottom = bottom - screenBottom;
     scrollYDelta = Math.min(scrollYDelta, distanceToBottom);

   } else if (rect.top < screenTop && rect.bottom < screenBottom) {
     // need to move up to get it in view: move up just enough so that
     // entire rectangle is in view (or at least the first screen
     // size chunk of it).

     if (rect.height() > height) {
       // screen size chunk
       scrollYDelta -= (screenBottom - rect.bottom);
     } else {
       // entire rect at top
       scrollYDelta -= (screenTop - rect.top);
     }

     // make sure we aren't scrolling any further than the top our content
     scrollYDelta = Math.max(scrollYDelta, -getScrollY());
   }
   return scrollYDelta;
 }

 @Override
 public void requestChildFocus(View child, View focused) {
   if (!mTwoDScrollViewMovedFocus) {
     if (!mIsLayoutDirty) {
       scrollToChild(focused);
     } else {
       // The child may not be laid out yet, we can't compute the scroll yet
       mChildToScrollTo = focused;
     }
   }
   super.requestChildFocus(child, focused);
 }

 /**
  * When looking for focus in children of a scroll view, need to be a little
  * more careful not to give focus to something that is scrolled off screen.
  *
  * This is more expensive than the default {@link android.view.ViewGroup}
  * implementation, otherwise this behavior might have been made the default.
  */
 @Override
 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
   // convert from forward / backward notation to up / down / left / right
   // (ugh).
   if (direction == View.FOCUS_FORWARD) {
     direction = View.FOCUS_DOWN;
   } else if (direction == View.FOCUS_BACKWARD) {
     direction = View.FOCUS_UP;
   }

   final View nextFocus = previouslyFocusedRect == null ?
   FocusFinder.getInstance().findNextFocus(this, null, direction) :
   FocusFinder.getInstance().findNextFocusFromRect(this,
   previouslyFocusedRect, direction);

   if (nextFocus == null) {
     return false;
   }

   return nextFocus.requestFocus(direction, previouslyFocusedRect);
 }

 @Override
 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
   // offset into coordinate space of this scroll view
   rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY());
   return scrollToChildRect(rectangle, immediate);
 }

 @Override
 public void requestLayout() {
   mIsLayoutDirty = true;
   super.requestLayout();
 }

 @Override
 protected void onLayout(boolean changed, int l, int t, int r, int b) {
   super.onLayout(changed, l, t, r, b);
   mIsLayoutDirty = false;
   // Give a child focus if it needs it
   if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
     scrollToChild(mChildToScrollTo);
   }
   mChildToScrollTo = null;

   // Calling this with the present values causes it to re-clam them
   scrollTo(getScrollX(), getScrollY());
 }

 @Override
 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
   super.onSizeChanged(w, h, oldw, oldh);

   View currentFocused = findFocus();
   if (null == currentFocused || this == currentFocused)
     return;

   // If the currently-focused view was visible on the screen when the
   // screen was at the old height, then scroll the screen to make that
   // view visible with the new screen height.
   currentFocused.getDrawingRect(mTempRect);
   offsetDescendantRectToMyCoords(currentFocused, mTempRect);
   int scrollDeltaX = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
   int scrollDeltaY = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
   doScroll(scrollDeltaX, scrollDeltaY);
 }

 /**
  * Return true if child is an descendant of parent, (or equal to the parent).
  */
 private boolean isViewDescendantOf(View child, View parent) {
   if (child == parent) {
     return true;
   }

   final ViewParent theParent = child.getParent();
   return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
 }

 /**
  * Fling the scroll view
  *
  * @param velocityY The initial velocity in the Y direction. Positive
  *                  numbers mean that the finger/curor is moving down the screen,
  *                  which means we want to scroll towards the top.
  */
 public void fling(int velocityX, int velocityY) {
   if (getChildCount() > 0) {
     int height = getHeight() - getPaddingBottom() - getPaddingTop();
     int bottom = getChildAt(0).getHeight();
     int width = getWidth() - getPaddingRight() - getPaddingLeft();
     int right = getChildAt(0).getWidth();

     mScroller.fling(getScrollX(), getScrollY(), velocityX, velocityY, 0, right - width, 0, bottom - height);

     final boolean movingDown = velocityY > 0;
     final boolean movingRight = velocityX > 0;

     View newFocused = findFocusableViewInMyBounds(movingRight, mScroller.getFinalX(), movingDown, mScroller.getFinalY(), findFocus());
     if (newFocused == null) {
       newFocused = this;
     }

     if (newFocused != findFocus() && newFocused.requestFocus(movingDown ? View.FOCUS_DOWN : View.FOCUS_UP)) {
       mTwoDScrollViewMovedFocus = true;
       mTwoDScrollViewMovedFocus = false;
     }

     awakenScrollBars(mScroller.getDuration());
     invalidate();
   }
 }

 /**
  * {@inheritDoc}
  *
  * <p>This version also clamps the scrolling to the bounds of our child.
  */
 public void scrollTo(int x, int y) {
   // we rely on the fact the View.scrollBy calls scrollTo.
   if (getChildCount() > 0) {
     View child = getChildAt(0);
     x = clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(), child.getWidth());
     y = clamp(y, getHeight() - getPaddingBottom() - getPaddingTop(), child.getHeight());
     if (x != getScrollX() || y != getScrollY()) {
       super.scrollTo(x, y);
     }
   }
 }

 private int clamp(int n, int my, int child) {
   if (my >= child || n < 0) {
     /* my >= child is this case:
      *                    |--------------- me ---------------|
      *     |------ child ------|
      * or
      *     |--------------- me ---------------|
      *            |------ child ------|
      * or
      *     |--------------- me ---------------|
      *                                  |------ child ------|
      *
      * n < 0 is this case:
      *     |------ me ------|
      *                    |-------- child --------|
      *     |-- mScrollX --|
      */
     return 0;
   }
   if ((my+n) > child) {
     /* this case:
      *                    |------ me ------|
      *     |------ child ------|
      *     |-- mScrollX --|
      */
     return child-my;
   }
   return n;
 }
}
<pre>

In hindsight I think I know why two-dimensioning scrolling is not inherently included:  it is a memory hog.  There is an emphasis for beautiful graphics in the framework to achieve the best user experience; examples of this emphasis are true-color (24-bit) pixels, alpha transparency channel support, smooth scrolling, and display caching.  However the Android system restricts an application to 16MB of heap memory.  This limit is met quickly for a large cached two-dimensional scrolled view – note that 2,000 by 2,000 pixels times 4 bytes/pixel is 16MB.

Matt Clark worked in academia, corporate research labs and several technology startup companies prior to GORGES. His expertise is software architecture, database development, and system administration. Matt brings GORGES over 25 years experience developing fast and robust software on a multitude of platforms and languages.

Asterisk and Cisco VOIP Phones

Saturday, April 3rd, 2010

A few years ago we needed an office phone system.  Having a limited budget and being a tech-head, I decided to deploy Asterisk, an open-source PBX solution.  The outlays were minimal since we only needed a telephony card (Digium TDM400P), several VOIP  phones (GrandStream 2000 – hello, eBay!), and an old PC.  We chose to install Trixbox, which is based on Asterisk and promotes itself as easier to install than Asterisk.

After perhaps too much futzing, we ended up with a small business phone system without any monthly PBX charges other than the analog phone lines from the phone company.  We had an automated phone directory, the phones worked as intercoms, voice mail turned into attached WAV sound files send as e-mail.  I was able to add phone extensions easily.  I love Asterisk!

Perhaps the success went to my head, since I set my sights on a fancy conference room phone for our growing business.  I bought a used Cisco Polycom CP-7935 phone for 1/3rd the price of a new device.  I’ll admit it – I’m an amateur at telephony and didn’t know the difference between SIP and SCCP.  It turns out that Trixbox only supports SIP extensions by default, and this conference room phone requires SCCP channel protocol.

So finally I am coming to the purpose of this post – simple instructions on to hook up a Cisco VOIP phone (that only uses SCCP protocol) to Trixbox version 2.8.  The following instructions were gleaned from some Google searches, and I am summarizing them since no one had simple steps online for the most-recent Trixbox version.

First we need to install some packages and retrieve the most-recent version of an SCCP solution from SourceForge.  Do the following commands signed in as root user on your Trixbox server:

# yum install asterisk16-devel gcc subversion
# cd /usr/local/
# wget http://sourceforge.net/projects/chan-sccp-b/files/chan-sccp-b/v2-based_20090602/chan_sccp-b_20090602.tar.gz/download
# tar xvfz chan_sccp-b_20090602.tar.gz
# cd /usr/local/chan_sccp-b_20090602
# make

If you perform the above steps, you will see that the make operation will not work without modifying some source code.  Thanks to a posting (http://lostentropy.com/2009/09/28/making-chan_sccp-build-with-asterisk-1-6/) I learned that I have to change a reference to a constant from CS_AST_CONTROL_T38 to CS_AST_CONTROL_T38_PARAMETERS.  Make this change to the file /usr/local/chan_sccp-b_20090602/sccp_pbx.c on line 587 using your favorite text editor.

# make
# make install
# amportal restart

Now comes the hard part.  The CP-7935 gets its provisioning file from a TFTP server.  Reset the CP-7935 to its default factor settings.  Next use the device menu to set the TFTP server to your Trixbox IP address (follow steps in the manual from the Cisco website).  The Trixbox should have its TFTP service activated by default; for my server the TFTP directory on the server is /tftpboot/.

Monitor the TFTP log file (/var/log/atftp.log) while you reboot the CP-7935.  You should see a request in the format “SEP#.cnf.xml” in the log file, where the “#” is the MAC address of the CP-7935.  Now create the following file /tftpboot/SEP#.cnf.xml (mine is /tftpboot/SEP00e0752442c5.cnf.xml) with this content and replacing the TRIXBOX_IP_ADDRESS with your Trixbox server address:

<Default>
<callManagerGroup>
<members>
<member priority="0">
<callManager>
<ports>
<ethernetPhonePort>2000</ethernetPhonePort>
<mgcpPorts>
<listen>2427</listen>
<keepAlive>2428</keepAlive>
</mgcpPorts>
</ports>
<processNodeName>TRIXBOX_IP_ADDRESS</processNodeName>
</callManager>
</member>
</members>
</callManagerGroup>
<authenticationURL></authenticationURL>
<loadInformation</loadInformation>
<directoryURL></directoryURL>
<idleURL></idleURL>
<informationURL></informationURL>
<messagesURL></messagesURL>
<servicesURL></servicesURL>
<versionStamp>{Apr 03 2010 12:00:00}</versionStamp>
</Default>

The last configuration entry tag for <versionStamp> is important since it is used by the device to determine if the settings have changed.  Update this versionStamp value to a later date to force the device to reload the settings in the file.

Next we need to write the SCCP configuration file that Asterisk reads. First make a backup of the existing file, and then we will replace it with one tailored for our solution.

# mv /etc/asterisk/sccp.conf /etc/asterisk/sccp.conf.bak

Here are the new contents for the file /etc/asterisk/sccp.conf, and remember to replace the all-capital letter phrases but the specifics of your setup, for example TRIXBOX_SERVER_IP_ADDRESS is replace by the IP address of your trixbox, and the SEP00e0752442c5 with the string “SEP” and the MAC address of your Cisco phone.  Our phone model is 7935, so you will also need to change this to your phone type.

[general]
servername = trixbox
keepalive = 60
debug = 1
context = from-internal
dateFormat = M/D/YA
bindaddr = TRIXBOX_SERVER_IP_ADDRESS
port = 2000
disallow=all
;allow=alaw
allow=ulaw
firstdigittimeout = 16
digittimeout = 8
digittimeoutchar = #
autoanswer_ring_time = 1
autoanswer_tone = 0x32
remotehangup_tone = 0x32
transfer_tone = 0
callwaiting_tone = 0x2d
musicclass=default
language=en
deny=0.0.0.0/0.0.0.0
permit=TRIXBOX_SERVER_IP_ADDRESS/255.255.255.0
localnet = 192.168.93.0/255.255.255.0
dnd = on
rtptos = 184
echocancel = on
silencesuppression = off
trustphoneip = no
tos = 0x68
private = on
mwilamp = on
mwioncall = on
blindtransferindication = ring
cfwdall = on
cfwdbusy = on
[devices]
type = 7935
autologin = CONFERENCE_PHONE_EXTENSION
description = Phone7935
keepalive = 60
transfer = on
park = on
cfwdall = on
cfwdbusy = on
dtmfmode = outband
imageversion = P00308000100
deny=0.0.0.0/0.0.0.0
permit=192.168.93.3/255.255.255.255
dnd = on
trustphoneip = no
private = on
mwilamp = on
mwioncall = on
device => SEP00e0752442c5
[lines]
id = CONFERENCE_PHONE_EXTENSION
pin = 1234
label = CONFERENCE_PHONE_EXTENSION
description = Conference Room
context = from-internal
incominglimit = 3
transfer = on
cid_name = Conference Room
cid_num = CONFERENCE_PHONE_EXTENSION
trnsfvm = 1
secondary_dialtone_digits = 9
secondary_dialtone_tone = 0x22
musicclass=default
language=en
rtptos = 184
echocancel = on
silencesuppression = on
line => CONFERENCE_PHONE_EXTENSION

We’re almost done.  Now restart the asterisk service:

# amportal restart

Finally create an extension in the Trixbox administrator interface, and make sure it matches the value of the CONFERENCE_ROOM_EXTENSION in the sccp.conf file above (we used “30″).  Do a hardware reboot of the conference room phone.

Missing from this posting is any explanation about firmware and provisioning.  Cisco sells firmware upgrades to their devices, and we bet that the existing firmware on the used conference phone device was sufficient.  Our bet paid off.

In summary, this solution may still take a few hours of work for your particular Cisco phone.  The payoff is grand – our office Trixbox solution saves us money daily by not having to lease or maintain an expensive private PBX system.

Matt Clark worked in academia, corporate research labs and several technology startup companies prior to GORGES. His expertise is software architecture, database development, and system administration. Matt brings GORGES over 25 years experience developing fast and robust software on a multitude of platforms and languages.

What Hosting Do I Need?

Tuesday, September 15th, 2009

Choosing a hosting service is important, and there are many choices to make.  Here are some tips to help you make your selection.

The first step is to determine your business requirements.  The criteria should be reliability (or uptime), performance, support, and cost.  Try to estimate the cost of downtime, because that value should factor in your hosting decision.  If a day of downtime costs you thousands of dollars, then reliability is very important.

The cheapest hosting is to purchase an account on a shared server.  Your domain is one of perhaps hundreds or even thousands that vie for the server CPU, memory, and bandwidth.  If your site is slow, it may be difficult or even impossible to diagnose why since the fault may be with another domain on the same server.

The next level up is a virtual private server (VPS).  In reality you are still sharing the server with other customers, but there are separations between these relatively-independent operating systems so they affect each other less if problems on one arise.  The term “cloud computing” is really just another name for using virtual private servers, although often the cloud computing control panels make it easy and fast to add and remove VPS units as your domain needs change.

If you want the whole server to yourself, then you can hosting on a dedicated server.  This is all about control – there are no other customers to contend with if you are the only one using the server.  Note that you may need an experienced system administrator to help if you are setting up your own dedicated server.

If your domain outgrows a dedicated server, then you have graduated to a cluster solution.  You will have new challenges regarding sharing session management and your database between multiple servers.  It should also be mentioned that cloud computing supports clustering with their VPS machines, which is cheaper than a custom-built clustered solution.

At Gorges, we offer shared-server and dedicated-server hosting solutions to our software development clients.  We have two co-location facilities that we use in Ithaca, New York, and our servers are monitored constantly.  Since we do our own hosting, we can add software packages or customize the server configuration as-needed for our clients.

Matt Clark worked in academia, corporate research labs and several technology startup companies prior to GORGES. His expertise is software architecture, database development, and system administration. Matt brings GORGES over 25 years experience developing fast and robust software on a multitude of platforms and languages.

Securing Linux Web Servers

Monday, July 20th, 2009

We are often asked by our software development and hosting customers how we secure our servers.  We have several layers of security protection, and this blog posting will mention some that we implement.

A firewall is used to only allow traffic to the outside world on a few of the TCP/UDP ports.  We obviously have to allow web and e-mail users access to the server, but almost all other ports can be closed to prevent intrusion attempts.  On our newest servers we even prevent FTP and Telnet access, since those protocols rely on unencrypted packets which are easier to intercept and hijack.

Every day we have perhaps dozens of “dicitionary” attacks that try to gain e-mail or user account access.  A dictionary attack picks a user (for example “root” or “john”) and then goes through a long, long list of possible passwords.  We use two packages Fail2Ban and DenyHosts that monitor our log files looking for dictionary attacks; if found, the originating computer is banned from accessing our servers.

When we develop online shopping solutions, we choose to not store credit card numbers online.  We securely pass this information to the credit card processing vendor, and then we only record the order information and the payment confirmation number.  For some web sites with user accounts, we encrypt the user account passwords, therefore gaining access to our user password list would still not result in someone gaining access to their online account.

Some of our hosting customers are concerned about unencrypted web traffic.  We occasionally add a feature that automatically forwards a web page inquiry from non-SSL to SSL mode, which means it forward to a page starting with “https://” thus all traffic is encrypted between our server and each web browser client.

We also have logging records and constant monitoring to help us detect intrusion attempts and help us implement even better security measures.  “Tripwire” software can also alert us when certain files are modified.

Do these basic measures above make us impervious to hackers?  Alas, no.  On two occasions in the last five years we have had hackers penetrate one of our servers.  However no damage was done and we patched those specific holes quickly.  Security is a cat-and-mouse game, and we strive to stay one step ahead.

Matt Clark worked in academia, corporate research labs and several technology startup companies prior to GORGES. His expertise is software architecture, database development, and system administration. Matt brings GORGES over 25 years experience developing fast and robust software on a multitude of platforms and languages.