Browse Source

Started Porting Direwolf to ESP32 Plaform

curiousmuch 5 years ago
parent
commit
e3bf0f178c
12 changed files with 5669 additions and 1 deletions
  1. 2713 0
      main/ax25_pad.c
  2. 446 0
      main/ax25_pad.h
  3. 909 0
      main/ax25_pad2.c
  4. 54 0
      main/ax25_pad2.h
  5. 66 0
      main/direwolf.h
  6. 126 0
      main/fcs_calc.c
  7. 11 0
      main/fcs_calc.h
  8. 1048 0
      main/latlong.c
  9. 24 0
      main/latlong.h
  10. 22 1
      main/main.c
  11. 128 0
      main/strlcat.c
  12. 122 0
      main/strlcpy.c

+ 2713 - 0
main/ax25_pad.c

@@ -0,0 +1,2713 @@
+//
+//    This file is part of Dire Wolf, an amateur radio packet TNC.
+//
+//    Copyright (C) 2011 , 2013, 2014, 2015  John Langner, WB2OSZ
+//
+//    This program is free software: you can redistribute it and/or modify
+//    it under the terms of the GNU General Public License as published by
+//    the Free Software Foundation, either version 2 of the License, or
+//    (at your option) any later version.
+//
+//    This program is distributed in the hope that it will be useful,
+//    but WITHOUT ANY WARRANTY; without even the implied warranty of
+//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//    GNU General Public License for more details.
+//
+//    You should have received a copy of the GNU General Public License
+//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+//
+
+
+/*------------------------------------------------------------------
+ *
+ * Name:	ax25_pad
+ *
+ * Purpose:	Packet assembler and disasembler.
+ *
+ *		This was written when I was only concerned about APRS which
+ *		uses only UI frames.  ax25_pad2.c, added years later, has
+ *		functions for dealing with other types of frames.
+ *
+ *   		We can obtain AX.25 packets from different sources:
+ *		
+ *		(a) from an HDLC frame.
+ *		(b) from text representation.
+ *		(c) built up piece by piece.
+ *
+ *		We also want to use a packet in different ways:
+ *
+ *		(a) transmit as an HDLC frame.
+ *		(b) print in human-readable text.
+ *		(c) take it apart piece by piece.
+ *
+ *		Looking at the more general case, we also want to modify
+ *		an existing packet.  For instance an APRS repeater might 
+ *		want to change "WIDE2-2" to "WIDE2-1" and retransmit it.
+ *
+ *
+ * Description:	
+ *
+ *
+ *	APRS uses only UI frames.
+ *	Each starts with 2-10 addressses (14-70 octets):
+ *
+ *	* Destination Address  (note: opposite order in printed format)
+ *
+ *	* Source Address
+ *
+ *	* 0-8 Digipeater Addresses  (Could there ever be more as a result of
+ *					digipeaters inserting their own call for
+ *					the tracing feature?
+ *					NO.  The limit is 8 when transmitting AX.25 over the
+ *					radio.
+ *					Communication with an IGate server could
+ *					have a longer VIA path but that is only in text form,
+ *					not as an AX.25 frame.)
+ *
+ *	Each address is composed of:
+ *
+ *	* 6 upper case letters or digits, blank padded.
+ *		These are shifted left one bit, leaving the LSB always 0.
+ *
+ *	* a 7th octet containing the SSID and flags.
+ *		The LSB is always 0 except for the last octet of the address field.
+ *
+ *	The final octet of the Destination has the form:
+ *
+ *		C R R SSID 0, where,
+ *
+ *			C = command/response = 1
+ *			R R = Reserved = 1 1
+ *			SSID = substation ID
+ *			0 = zero
+ *
+ *		The AX.25 spec states that the RR bits should be 11 if not used.
+ *		There are a couple documents talking about possible uses for APRS.
+ *		I'm ignoring them for now.
+ *		http://www.aprs.org/aprs12/preemptive-digipeating.txt
+ *		http://www.aprs.org/aprs12/RR-bits.txt
+ *
+ *		I don't recall why I originally intended to set the source/destination C bits both to 1.
+ *		Reviewing this 5 years later, after spending more time delving into the
+ *		AX.25 spec, I think it should be 1 for destination and 0 for source.
+ *		In practice you see all four combinations being used by APRS stations
+ *		and no one really cares about these two bits.
+ *
+ *	The final octet of the Source has the form:
+ *
+ *		C R R SSID 0, where,
+ *
+ *			C = command/response = 1    (originally, now I think it should be 0 for source.)
+ *						(Haven't gone back to check to see what code actually does.)
+ *			R R = Reserved = 1 1
+ *			SSID = substation ID
+ *			0 = zero (or 1 if no repeaters)
+ *
+ *	The final octet of each repeater has the form:
+ *
+ *		H R R SSID 0, where,
+ *
+ *			H = has-been-repeated = 0 initially.  
+ *				Set to 1 after this address has been used.
+ *			R R = Reserved = 1 1
+ *			SSID = substation ID
+ *			0 = zero (or 1 if last repeater in list)
+ *
+ *		A digipeater would repeat this frame if it finds its address
+ *		with the "H" bit set to 0 and all earlier repeater addresses
+ *		have the "H" bit set to 1.  
+ *		The "H" bit would be set to 1 in the repeated frame.
+ *
+ *	In standard monitoring format, an asterisk is displayed after the last
+ *	digipeater with the "H" bit set.  That indicates who you are hearing
+ *	over the radio.
+ *	(That is if digipeaters update the via path properly.  Some don't so
+ *	we don't know who we are hearing.  This is discussed in the User Guide.)
+ *	No asterisk means the source is being heard directly.
+ *
+ *	Example, if we can hear all stations involved,
+ *
+ *		SRC>DST,RPT1,RPT2,RPT3:		-- we heard SRC
+ *		SRC>DST,RPT1*,RPT2,RPT3:	-- we heard RPT1
+ *		SRC>DST,RPT1,RPT2*,RPT3:	-- we heard RPT2
+ *		SRC>DST,RPT1,RPT2,RPT3*:	-- we heard RPT3
+ *
+ *	
+ *	Next we have:
+ *
+ *	* One byte Control Field 	- APRS uses 3 for UI frame
+ *					   The more general AX.25 frame can have two.
+ *
+ *	* One byte Protocol ID 		- APRS uses 0xf0 for no layer 3
+ *
+ *	Finally the Information Field of 1-256 bytes.
+ *
+ *	And, of course, the 2 byte CRC.
+ *
+ * 	The descriptions above, for the C, H, and RR bits, are for APRS usage.
+ *	When operating as a KISS TNC we just pass everything along and don't
+ *	interpret or change them.
+ *
+ *
+ * Constructors: ax25_init		- Clear everything.
+ *		ax25_from_text		- Tear apart a text string
+ *		ax25_from_frame		- Tear apart an AX.25 frame.  
+ *					  Must be called before any other function.
+ *
+ * Get methods:	....			- Extract destination, source, or digipeater
+ *					  address from frame.
+ *
+ * Assumptions:	CRC has already been verified to be correct.
+ *
+ *------------------------------------------------------------------*/
+
+#define AX25_PAD_C		/* this will affect behavior of ax25_pad.h */
+
+#include "direwolf.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <stdio.h>
+#include <ctype.h>
+
+#include "regex.h"
+
+
+#if __WIN32__
+char *strtok_r(char *str, const char *delim, char **saveptr);
+#endif
+
+
+//#include "textcolor.h"
+#include "ax25_pad.h"
+#include "fcs_calc.h"
+
+/*
+ * Accumulate statistics.
+ * If new_count gets much larger than delete_count plus the size of 
+ * the transmit queue we have a memory leak.
+ */
+
+static volatile int new_count = 0;
+static volatile int delete_count = 0;
+static volatile int last_seq_num = 0;
+
+#if AX25MEMDEBUG
+
+int ax25memdebug = 0;
+
+
+void ax25memdebug_set(void) 
+{
+	ax25memdebug = 1;
+}
+
+int ax25memdebug_get (void)
+{
+	return (ax25memdebug);
+}
+
+int ax25memdebug_seq (packet_t this_p)
+{
+	return (this_p->seq);
+}
+
+
+#endif
+
+
+
+#define CLEAR_LAST_ADDR_FLAG  this_p->frame_data[this_p->num_addr*7-1] &= ~ SSID_LAST_MASK
+#define SET_LAST_ADDR_FLAG  this_p->frame_data[this_p->num_addr*7-1] |= SSID_LAST_MASK
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_new
+ * 
+ * Purpose:	Allocate memory for a new packet object.
+ *
+ * Returns:	Identifier for a new packet object.
+ *		In the current implementation this happens to be a pointer.
+ *
+ *------------------------------------------------------------------------------*/
+
+
+packet_t ax25_new (void)
+{
+	struct packet_s *this_p;
+
+
+#if DEBUG 
+        printf ("ax25_new(): before alloc, new=%d, delete=%d\n", new_count, delete_count);
+#endif
+
+	last_seq_num++;
+	new_count++;
+
+/*
+ * check for memory leak.
+ */
+
+// version 1.4 push up the threshold.   We could have considerably more with connected mode.
+
+	//if (new_count > delete_count + 100) {
+	if (new_count > delete_count + 256) {
+
+
+	  printf ("Report to WB2OSZ - Memory leak for packet objects.  new=%d, delete=%d\n", new_count, delete_count);
+#if AX25MEMDEBUG
+	  // Force on debug option to gather evidence.
+	  ax25memdebug_set();
+#endif
+	}
+
+	this_p = calloc(sizeof (struct packet_s), (size_t)1);
+
+	if (this_p == NULL) {
+	  printf ("ERROR - can't allocate memory in ax25_new.\n");
+	}
+
+	assert (this_p != NULL);
+
+	this_p->magic1 = MAGIC;
+	this_p->seq = last_seq_num;
+	this_p->magic2 = MAGIC;
+	this_p->num_addr = (-1);
+
+	return (this_p);
+}
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_delete
+ * 
+ * Purpose:	Destroy a packet object, freeing up memory it was using.
+ *
+ *------------------------------------------------------------------------------*/
+
+#if AX25MEMDEBUG
+void ax25_delete_debug (packet_t this_p, char *src_file, int src_line)
+#else
+void ax25_delete (packet_t this_p)
+#endif
+{
+#if DEBUG
+        printf ("ax25_delete(): before free, new=%d, delete=%d\n", new_count, delete_count);
+#endif
+
+	if (this_p == NULL) {
+	  printf ("ERROR - NULL pointer passed to ax25_delete.\n");
+	  return;
+	}
+
+
+	delete_count++;
+
+#if AX25MEMDEBUG	
+	if (ax25memdebug) {
+	  printf ("ax25_delete, seq=%d, called from %s %d, new_count=%d, delete_count=%d\n", this_p->seq, src_file, src_line, new_count, delete_count);
+	}
+#endif
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+	
+	this_p->magic1 = 0;
+	this_p->magic1 = 0;
+
+	//memset (this_p, 0, sizeof (struct packet_s));
+	free (this_p);
+}
+
+
+		
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_from_text
+ * 
+ * Purpose:	Parse a frame in human-readable monitoring format and change
+ *		to internal representation.
+ *
+ * Input:	monitor	- "TNC-2" monitor format for packet.  i.e.
+ *				source>dest[,repeater1,repeater2,...]:information
+ *
+ *			The information part can have non-printable characters
+ *			in the form of <0xff>.  This will be converted to single
+ *			bytes.  e.g.  <0x0d> is carriage return.
+ *			In version 1.4H we will allow nul characters which means
+ *			we have to maintain a length rather than using strlen().
+ *			I maintain that it violates the spec but want to handle it
+ *			because it does happen and we want to preserve it when
+ *			acting as an IGate rather than corrupting it.
+ *
+ *		strict	- True to enforce rules for packets sent over the air.
+ *			  False to be more lenient for packets from IGate server.
+ *
+ *			  Messages from an IGate server can have longer 
+ *		 	  addresses after qAC.  Up to 9 observed so far. 
+ *
+ *			  We can just truncate the name because we will only
+ *			  end up discarding it.    TODO:  check on this.
+ *
+ * Returns:	Pointer to new packet object in the current implementation.
+ *
+ * Outputs:	Use the "get" functions to retrieve information in different ways.
+ *
+ *------------------------------------------------------------------------------*/
+
+#if AX25MEMDEBUG
+packet_t ax25_from_text_debug (char *monitor, int strict, char *src_file, int src_line)
+#else
+packet_t ax25_from_text (char *monitor, int strict)
+#endif
+{
+
+/*
+ * Tearing it apart is destructive so make our own copy first.
+ */
+	char stuff[512];
+
+	char *pinfo;
+	char *pa;
+	char *saveptr;		/* Used with strtok_r because strtok is not thread safe. */
+
+	int ssid_temp, heard_temp;
+	char atemp[AX25_MAX_ADDR_LEN];
+
+	char info_part[AX25_MAX_INFO_LEN+1];
+	int info_len;
+
+	packet_t this_p = ax25_new ();
+
+#if AX25MEMDEBUG	
+	if (ax25memdebug) {
+	  printf ("ax25_from_text, seq=%d, called from %s %d\n", this_p->seq, src_file, src_line);
+	}
+#endif
+
+	/* Is it possible to have a nul character (zero byte) in the */
+	/* information field of an AX.25 frame? */
+	/* At this point, we have a normal C string. */
+	/* It is possible that will convert <0x00> to a nul character later. */
+	/* There we need to maintain a separate length and not use normal C string functions. */
+
+	strlcpy (stuff, monitor, sizeof(stuff));
+
+
+/*
+ * Initialize the packet structure with two addresses and control/pid
+ * for APRS.
+ */
+	memset (this_p->frame_data + AX25_DESTINATION*7, ' ' << 1, 6);
+	this_p->frame_data[AX25_DESTINATION*7+6] = SSID_H_MASK | SSID_RR_MASK;
+ 
+	memset (this_p->frame_data + AX25_SOURCE*7, ' ' << 1, 6);
+	this_p->frame_data[AX25_SOURCE*7+6] = SSID_H_MASK | SSID_RR_MASK | SSID_LAST_MASK;
+
+	this_p->frame_data[14] = AX25_UI_FRAME;
+	this_p->frame_data[15] = AX25_PID_NO_LAYER_3;
+
+	this_p->frame_len = 7 + 7 + 1 + 1;
+	this_p->num_addr = (-1);
+	assert (ax25_get_num_addr(this_p) == 2);
+
+
+/*
+ * Separate the addresses from the rest.
+ */
+	pinfo = strchr (stuff, ':');
+
+	if (pinfo == NULL) {
+	  ax25_delete (this_p);
+	  return (NULL);
+	}
+
+	*pinfo = '\0';
+	pinfo++;
+
+/*
+ * Separate the addresses.
+ * Note that source and destination order is swappped.
+ */
+
+/*
+ * Source address.
+ * Don't use traditional strtok because it is not thread safe.
+ */
+	pa = strtok_r (stuff, ">", &saveptr);
+	if (pa == NULL) {
+	  printf ("Failed to create packet from text.  No source address\n");
+	  ax25_delete (this_p);
+	  return (NULL);
+	}
+
+	if ( ! ax25_parse_addr (AX25_SOURCE, pa, strict, atemp, &ssid_temp, &heard_temp)) {
+	  printf ("Failed to create packet from text.  Bad source address\n");
+	  ax25_delete (this_p);
+	  return (NULL);
+	}
+
+	ax25_set_addr (this_p, AX25_SOURCE, atemp);
+	ax25_set_h (this_p, AX25_SOURCE);	// c/r in this position
+	ax25_set_ssid (this_p, AX25_SOURCE, ssid_temp);
+
+/*
+ * Destination address.
+ */
+ 
+	pa = strtok_r (NULL, ",", &saveptr);
+	if (pa == NULL) {
+	  printf ("Failed to create packet from text.  No destination address\n");
+	  ax25_delete (this_p);
+	  return (NULL);
+	}
+
+	if ( ! ax25_parse_addr (AX25_DESTINATION, pa, strict, atemp, &ssid_temp, &heard_temp)) {
+	  printf ("Failed to create packet from text.  Bad destination address\n");
+	  ax25_delete (this_p);
+	  return (NULL);
+	}
+
+	ax25_set_addr (this_p, AX25_DESTINATION, atemp);
+	ax25_set_h (this_p, AX25_DESTINATION);	// c/r in this position
+	ax25_set_ssid (this_p, AX25_DESTINATION, ssid_temp);
+
+/*
+ * VIA path.
+ */
+	while (( pa = strtok_r (NULL, ",", &saveptr)) != NULL && this_p->num_addr < AX25_MAX_ADDRS ) {
+
+	  int k;
+
+	  k = this_p->num_addr;
+
+	  if ( ! ax25_parse_addr (k, pa, strict, atemp, &ssid_temp, &heard_temp)) {
+	    printf ("Failed to create packet from text.  Bad digipeater address\n");
+	    ax25_delete (this_p);
+	    return (NULL);
+	  }
+
+	  ax25_set_addr (this_p, k, atemp);
+	  ax25_set_ssid (this_p, k, ssid_temp);
+
+	  // Does it have an "*" at the end? 
+	  // TODO: Complain if more than one "*".
+	  // Could also check for all has been repeated bits are adjacent.
+	
+          if (heard_temp) {
+	    for ( ; k >= AX25_REPEATER_1; k--) {
+	      ax25_set_h (this_p, k);
+	    }
+	  }
+        }
+
+
+/*
+ * Finally, process the information part.
+ *
+ * Translate hexadecimal values like <0xff> to single bytes.
+ * MIC-E format uses 5 different non-printing characters.
+ * We might want to manually generate UTF-8 characters such as degree.
+ */
+
+//#define DEBUG14H 1
+
+#if DEBUG14H
+	printf ("BEFORE: %s\nSAFE:   ", pinfo);
+	ax25_safe_print (pinfo, -1, 0);
+	printf ("\n");
+#endif
+
+	info_len = 0;
+	while (*pinfo != '\0' && info_len < AX25_MAX_INFO_LEN) {
+
+	  if (strlen(pinfo) >= 6 &&
+		pinfo[0] == '<' &&
+		pinfo[1] == '0' &&
+		pinfo[2] == 'x' &&
+		isxdigit( (uint) pinfo[3]) &&//#include "strlcpy.c"
+
+		isxdigit( (uint) pinfo[4]) &&
+		pinfo[5] == '>') {
+
+	    char *p;
+
+	    info_part[info_len] = strtol (pinfo + 3, &p, 16);
+	    info_len++;
+	    pinfo += 6;
+	  }
+	  else {
+	    info_part[info_len] = *pinfo;
+	    info_len++;
+	    pinfo++;
+	  }
+	}
+	info_part[info_len] = '\0';
+
+#if DEBUG14H
+	printf ("AFTER:  %s\nSAFE:   ", info_part);
+	ax25_safe_print (info_part, info_len, 0);
+	printf ("\n");
+#endif
+
+/*
+ * Append the info part.  
+ */
+	memcpy ((char*)(this_p->frame_data+this_p->frame_len), info_part, info_len);
+	this_p->frame_len += info_len;
+
+	return (this_p);
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_from_frame
+ * 
+ * Purpose:	Split apart an HDLC frame to components.
+ *
+ * Inputs:	fbuf	- Pointer to beginning of frame.
+ *
+ *		flen	- Length excluding the two FCS bytes.
+ *
+ *		alevel	- Audio level of received signal.  
+ *			  Maximum range 0 - 100.
+ *			  -1 might be used when not applicable.
+ *
+ * Returns:	Pointer to new packet object or NULL if error.
+ *
+ * Outputs:	Use the "get" functions to retrieve information in different ways.
+ *
+ *------------------------------------------------------------------------------*/
+
+#if AX25MEMDEBUG
+packet_t ax25_from_frame_debug (unsigned char *fbuf, int flen, alevel_t alevel, char *src_file, int src_line)
+#else
+packet_t ax25_from_frame (unsigned char *fbuf, int flen, alevel_t alevel)
+#endif
+{
+	packet_t this_p;
+
+
+/*
+ * First make sure we have an acceptable length:
+ *
+ *	We are not concerned with the FCS (CRC) because someone else checked it.
+ *
+ * Is is possible to have zero length for info?  
+ *
+ * In the original version, assuming APRS, the answer was no.
+ * We always had at least 3 octets after the address part:
+ * control, protocol, and first byte of info part for data type.
+ *
+ * In later versions, this restriction was relaxed so other
+ * variations of AX.25 could be used.  Now the minimum length
+ * is 7+7 for addresses plus 1 for control.
+ *
+ */
+
+
+	if (flen < AX25_MIN_PACKET_LEN || flen > AX25_MAX_PACKET_LEN)
+	{
+	  printf ("Frame length %d not in allowable range of %d to %d.\n", flen, AX25_MIN_PACKET_LEN, AX25_MAX_PACKET_LEN);
+	  return (NULL);
+	}
+
+	this_p = ax25_new ();
+
+#if AX25MEMDEBUG	
+	if (ax25memdebug) {
+	  printf ("ax25_from_frame, seq=%d, called from %s %d\n", this_p->seq, src_file, src_line);
+	}
+#endif
+
+/* Copy the whole thing intact. */
+
+	memcpy (this_p->frame_data, fbuf, flen);
+	this_p->frame_data[flen] = 0;
+	this_p->frame_len = flen;
+
+/* Find number of addresses. */
+	
+	this_p->num_addr = (-1);
+	(void) ax25_get_num_addr (this_p);
+
+	return (this_p);
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_dup
+ * 
+ * Purpose:	Make a copy of given packet object.
+ *
+ * Inputs:	copy_from	- Existing packet object.
+ *
+ * Returns:	Pointer to new packet object or NULL if error.
+ *
+ *
+ *------------------------------------------------------------------------------*/
+
+
+#if AX25MEMDEBUG
+packet_t ax25_dup_debug (packet_t copy_from, char *src_file, int src_line)
+#else
+packet_t ax25_dup (packet_t copy_from)
+#endif
+{
+	int save_seq;
+	packet_t this_p;
+
+	
+	this_p = ax25_new ();
+	assert (this_p != NULL);
+
+	save_seq = this_p->seq;
+
+	memcpy (this_p, copy_from, sizeof (struct packet_s));
+	this_p->seq = save_seq;
+
+#if AX25MEMDEBUG
+	if (ax25memdebug) {	
+	  printf ("ax25_dup, seq=%d, called from %s %d, clone of seq %d\n", this_p->seq, src_file, src_line, copy_from->seq);
+	}
+#endif
+
+	return (this_p);
+
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_parse_addr
+ * 
+ * Purpose:	Parse address with optional ssid.
+ *
+ * Inputs:	position	- AX25_DESTINATION, AX25_SOURCE, AX25_REPEATER_1...
+ *				  Used for more specific error message.  -1 if not used.
+ *
+ *		in_addr		- Input such as "WB2OSZ-15*"
+ *
+ * 		strict		- 1 (true) for strict checking (6 characters, no lower case,
+ *				  SSID must be in range of 0 to 15).
+ *				  Strict is appropriate for packets sent
+ *				  over the radio.  Communication with IGate
+ *				  allows lower case (e.g. "qAR") and two 
+ *				  alphanumeric characters for the SSID.
+ *				  We also get messages like this from a server.
+ *					KB1POR>APU25N,TCPIP*,qAC,T2NUENGLD:...
+ *
+ *				  2 (extra true) will complain if * is found at end.
+ *
+ * Outputs:	out_addr	- Address without any SSID.
+ *				  Must be at least AX25_MAX_ADDR_LEN bytes.
+ *
+ *		out_ssid	- Numeric value of SSID.
+ *
+ *		out_heard	- True if "*" found.
+ *
+ * Returns:	True (1) if OK, false (0) if any error.
+ *		When 0, out_addr, out_ssid, and out_heard are unpredictable.
+ *
+ *
+ *------------------------------------------------------------------------------*/
+
+static const char *position_name[1 + AX25_MAX_ADDRS] = {
+	"", "Destination ", "Source ",
+	"Digi1 ", "Digi2 ", "Digi3 ", "Digi4 ",
+	"Digi5 ", "Digi6 ", "Digi7 ", "Digi8 " };
+
+int ax25_parse_addr (int position, char *in_addr, int strict, char *out_addr, int *out_ssid, int *out_heard)
+{
+	char *p;
+	char sstr[8];		/* Should be 1 or 2 digits for SSID. */
+	int i, j, k;
+	int maxlen;
+
+	*out_addr = '\0';
+	*out_ssid = 0;
+	*out_heard = 0;
+
+	if (position < -1) position = -1;
+	if (position > AX25_REPEATER_8) position = AX25_REPEATER_8;
+	position++;	/* Adjust for position_name above. */
+
+
+	if (strict && strlen(in_addr) >= 2 && strncmp(in_addr, "qA", 2) == 0) {
+
+	  printf ("%sAddress \"%s\" is a \"q-construct\" used for communicating with\n", position_name[position], in_addr);
+	  printf ("APRS Internet Servers.  It should never appear when going over the radio.\n");
+	}
+
+	//printf ("ax25_parse_addr in: %s\n", in_addr);
+
+
+	maxlen = strict ? 6 : (AX25_MAX_ADDR_LEN-1);
+	p = in_addr;
+	i = 0;
+	for (p = in_addr; *p != '\0' && *p != '-' && *p != '*'; p++) {
+	  if (i >= maxlen) {
+	    printf ("%sAddress is too long. \"%s\" has more than %d characters.\n", position_name[position], in_addr, maxlen);
+	    return 0;
+	  }
+	  if ( ! isalnum((uint)*p)) {
+	    printf ("%sAddress, \"%s\" contains character other than letter or digit in character position %d.\n", position_name[position], in_addr, (int)(long)(p-in_addr)+1);
+	    return 0;
+	  }
+
+	  out_addr[i++] = *p;
+	  out_addr[i] = '\0';
+
+#if DECAMAIN	// Hack when running in decode_aprs utility.
+		// Exempt the "qA..." case because it was already mentioned.
+
+	  if (strict && islower(*p) && strncmp(in_addr, "qA", 2) != 0) {
+	    printf ("%sAddress has lower case letters. \"%s\" must be all upper case.\n", position_name[position], in_addr);
+	  }
+#else
+	  if (strict && islower((uint)*p)) {
+	    printf ("%sAddress has lower case letters. \"%s\" must be all upper case.\n", position_name[position], in_addr);
+	    return 0;
+	  }
+#endif
+	}
+	
+	j = 0;
+	sstr[j] = '\0';
+	if (*p == '-') {
+	  for (p++; isalnum((int)*p); p++) {
+	    if (j >= 2) {
+	      printf ("%sSSID is too long. SSID part of \"%s\" has more than 2 characters.\n", position_name[position], in_addr);
+	      return 0;
+	    }
+	    sstr[j++] = *p;
+	    sstr[j] = '\0';
+	    if (strict && ! isdigit((uint)*p)) {
+	      printf ("%sSSID must be digits. \"%s\" has letters in SSID.\n", position_name[position], in_addr);
+	      return 0;
+	    }
+	  }
+	  k = atoi(sstr);
+	  if (k < 0 || k > 15) {
+	    printf ("%sSSID out of range. SSID of \"%s\" not in range of 0 to 15.\n", position_name[position], in_addr);
+	    return 0;
+	  }
+	  *out_ssid = k;
+	}
+
+	if (*p == '*') {
+	  *out_heard = 1;
+	  p++;
+	  if (strict == 2) {
+	    printf ("\"*\" is not allowed at end of address \"%s\" here.\n", in_addr);
+	    return 0;
+	  }
+	}
+
+	if (*p != '\0') {
+	  printf ("Invalid character \"%c\" found in %saddress \"%s\".\n", *p, position_name[position], in_addr);
+	  return 0;
+	}
+
+	//printf ("ax25_parse_addr out: %s %d %d\n", out_addr, *out_ssid, *out_heard);
+
+	return (1);
+
+} /* end ax25_parse_addr */
+
+
+/*-------------------------------------------------------------------
+ *
+ * Name:        ax25_check_addresses
+ *
+ * Purpose:     Check addresses of given packet and print message if any issues.
+ *		We call this when receiving and transmitting.
+ *
+ * Inputs:	pp	- packet object pointer.
+ *
+ * Errors:	Print error message.
+ *
+ * Returns:	1 for all valid.  0 if not.
+ *
+ * Examples:	I was surprised to get this from an APRS-IS server with
+ *		a lower case source address.
+ *
+ *			n1otx>APRS,TCPIP*,qAC,THIRD:@141335z4227.48N/07111.73W_348/005g014t044r000p000h60b10075.wview_5_20_2
+ *
+ *		I haven't gotten to the bottom of this yet but it sounds
+ *		like "q constructs" are somehow getting on to the air when
+ *		they should only appear in conversations with IGate servers.
+ *
+ *			https://groups.yahoo.com/neo/groups/direwolf_packet/conversations/topics/678
+ *
+ *			WB0VGI-7>APDW12,W0YC-5*,qAR,AE0RF-10:}N0DZQ-10>APWW10,TCPIP,WB0VGI-7*:;145.230MN*080306z4607.62N/09230.58WrKE0ACL/R 145.230- T146.2 (Pine County ARES)	
+ *
+ * Typical result:
+ *
+ *			Digipeater WIDE2 (probably N3LEE-4) audio level = 28(10/6)   [NONE]   __|||||||
+ *			[0.5] VE2DJE-9>P_0_P?,VE2PCQ-3,K1DF-7,N3LEE-4,WIDE2*:'{S+l <0x1c>>/
+ *			Invalid character "_" in MIC-E destination/latitude.
+ *			Invalid character "_" in MIC-E destination/latitude.
+ *			Invalid character "?" in MIC-E destination/latitude.
+ *			Invalid MIC-E N/S encoding in 4th character of destination.
+ *			Invalid MIC-E E/W encoding in 6th character of destination.
+ *			MIC-E, normal car (side view), Unknown manufacturer, Returning
+ *			N 00 00.0000, E 005 55.1500, 0 MPH
+ *			Invalid character "_" found in Destination address "P_0_P?".
+ *
+ *			*** The origin and journey of this packet should receive some scrutiny. ***
+ *
+ *--------------------------------------------------------------------*/
+
+int ax25_check_addresses (packet_t pp)
+{
+	int n;
+	char addr[AX25_MAX_ADDR_LEN];
+	char ignore1[AX25_MAX_ADDR_LEN];
+	int ignore2, ignore3;
+	int all_ok = 1;
+
+	for (n = 0; n < ax25_get_num_addr(pp); n++) {
+	  ax25_get_addr_with_ssid (pp, n, addr);
+	  all_ok &= ax25_parse_addr (n, addr, 1, ignore1, &ignore2, &ignore3);
+	}
+
+	if (! all_ok) {
+	  printf ("\n");
+	  printf ("*** The origin and journey of this packet should receive some scrutiny. ***\n");
+	  printf ("\n");
+	}
+
+	return (all_ok);
+} /* end ax25_check_addresses */
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_unwrap_third_party
+ * 
+ * Purpose:	Unwrap a third party messge from the header.
+ *
+ * Inputs:	copy_from	- Existing packet object.
+ *
+ * Returns:	Pointer to new packet object or NULL if error.
+ *
+ * Example:	Input:		A>B,C:}D>E,F:info
+ *		Output:		D>E,F:info
+ *
+ *------------------------------------------------------------------------------*/
+
+packet_t ax25_unwrap_third_party (packet_t from_pp)
+{
+	unsigned char *info_p;
+	packet_t result_pp;
+
+	if (ax25_get_dti(from_pp) != '}') {
+	  printf ("Internal error: ax25_unwrap_third_party: wrong data type.\n");
+	  return (NULL);
+	}
+
+	(void) ax25_get_info (from_pp, &info_p);
+
+	// Want strict because addresses should conform to AX.25 here.
+	// That's not the case for something from an Internet Server.
+
+	result_pp = ax25_from_text((char *)info_p + 1, 1);
+
+	return (result_pp);
+}
+
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_set_addr
+ * 
+ * Purpose:	Add or change an address.
+ *
+ * Inputs:	n	- Index of address.   Use the symbols 
+ *			  AX25_DESTINATION, AX25_SOURCE, AX25_REPEATER1, etc.
+ *
+ *			  Must be either an existing address or one greater
+ *			  than the final which causes a new one to be added.
+ *
+ *		ad	- Address with optional dash and substation id.
+ *
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * TODO:  	ax25_from_text could use this.
+ *
+ * Returns:	None.
+ *		
+ *------------------------------------------------------------------------------*/
+
+void ax25_set_addr (packet_t this_p, int n, char *ad)
+{
+	int ssid_temp, heard_temp;
+	char atemp[AX25_MAX_ADDR_LEN];
+	int i;
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+	assert (n >= 0 && n < AX25_MAX_ADDRS);
+
+	//printf ("ax25_set_addr (%d, %s) num_addr=%d\n", n, ad, this_p->num_addr);
+
+	if (n >= 0 && n < this_p->num_addr) {
+
+	  //printf ("ax25_set_addr , existing case\n");
+/* 
+ * Set existing address position. 
+ */
+
+	  // Why aren't we setting 'strict' here?
+	  // Messages from IGate have q-constructs.
+	  // We use this to parse it and later remove unwanted parts.
+
+	  ax25_parse_addr (n, ad, 0, atemp, &ssid_temp, &heard_temp);
+
+	  memset (this_p->frame_data + n*7, ' ' << 1, 6);
+
+	  for (i=0; i<6 && atemp[i] != '\0'; i++) {
+	    this_p->frame_data[n*7+i] = atemp[i] << 1;
+	  }
+	  ax25_set_ssid (this_p, n, ssid_temp);
+	}
+	else if (n == this_p->num_addr) {		
+
+	  //printf ("ax25_set_addr , appending case\n");
+/* 
+ * One beyond last position, process as insert.
+ */
+
+	  ax25_insert_addr (this_p, n, ad);
+	}
+	else { 
+	  printf ("Internal error, ax25_set_addr, bad position %d for '%s'\n", n, ad);
+	}
+
+	//printf ("------\n");
+	//printf ("dump after ax25_set_addr (%d, %s)\n", n, ad);
+	//ax25_hex_dump (this_p);
+	//printf ("------\n");
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_insert_addr
+ * 
+ * Purpose:	Insert address at specified position, shifting others up one
+ *		position.
+ *		This is used when a digipeater wants to insert its own call
+ *		for tracing purposes.
+ *		For example:
+ *			W1ABC>TEST,WIDE3-3
+ *		Would become:
+ *			W1ABC>TEST,WB2OSZ-1*,WIDE3-2
+ *
+ * Inputs:	n	- Index of address.   Use the symbols 
+ *			  AX25_DESTINATION, AX25_SOURCE, AX25_REPEATER1, etc.
+ *
+ *		ad	- Address with optional dash and substation id.
+ *
+ * Bugs:	Little validity or bounds checking is performed.  Be careful.
+ *		  
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Returns:	None.
+ *		
+ *
+ *------------------------------------------------------------------------------*/
+
+void ax25_insert_addr (packet_t this_p, int n, char *ad)
+{
+	int ssid_temp, heard_temp;
+	char atemp[AX25_MAX_ADDR_LEN];
+	int i;
+	int expect;
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+	assert (n >= AX25_REPEATER_1 && n < AX25_MAX_ADDRS);
+
+	//printf ("ax25_insert_addr (%d, %s)\n", n, ad);
+
+	/* Don't do it if we already have the maximum number. */
+	/* Should probably return success/fail code but currently the caller doesn't care. */
+
+	if ( this_p->num_addr >= AX25_MAX_ADDRS) {
+	  return;
+	}
+
+	CLEAR_LAST_ADDR_FLAG;
+
+	this_p->num_addr++;
+
+	memmove (this_p->frame_data + (n+1)*7, this_p->frame_data + n*7, this_p->frame_len - (n*7));
+	memset (this_p->frame_data + n*7, ' ' << 1, 6);
+	this_p->frame_len += 7;
+	this_p->frame_data[n*7+6] = SSID_RR_MASK;
+
+	SET_LAST_ADDR_FLAG;
+
+	// Why aren't we setting 'strict' here?
+	// Messages from IGate have q-constructs.
+	// We use this to parse it and later remove unwanted parts.
+
+	ax25_parse_addr (n, ad, 0, atemp, &ssid_temp, &heard_temp);
+	memset (this_p->frame_data + n*7, ' ' << 1, 6);
+	for (i=0; i<6 && atemp[i] != '\0'; i++) {
+	  this_p->frame_data[n*7+i] = atemp[i] << 1;
+	}
+	
+	ax25_set_ssid (this_p, n, ssid_temp);
+
+	// Sanity check after messing with number of addresses.
+
+	expect = this_p->num_addr;
+	this_p->num_addr = (-1);
+	if (expect != ax25_get_num_addr (this_p)) {
+	  printf ("Internal error ax25_remove_addr expect %d, actual %d\n", expect, this_p->num_addr);
+	}
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_remove_addr
+ * 
+ * Purpose:	Remove address at specified position, shifting others down one position.
+ *		This is used when we want to remove something from the digipeater list.
+ *
+ * Inputs:	n	- Index of address.   Use the symbols 
+ *			  AX25_REPEATER1, AX25_REPEATER2, etc.
+ *
+ * Bugs:	Little validity or bounds checking is performed.  Be careful.
+ *		  
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Returns:	None.
+ *		
+ *
+ *------------------------------------------------------------------------------*/
+
+void ax25_remove_addr (packet_t this_p, int n)
+{
+	int expect; 
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+	assert (n >= AX25_REPEATER_1 && n < AX25_MAX_ADDRS);
+
+	/* Shift those beyond to fill this position. */
+
+	CLEAR_LAST_ADDR_FLAG;
+
+	this_p->num_addr--;
+
+	memmove (this_p->frame_data + n*7, this_p->frame_data + (n+1)*7, this_p->frame_len - ((n+1)*7));
+	this_p->frame_len -= 7;
+	SET_LAST_ADDR_FLAG;
+
+	// Sanity check after messing with number of addresses.
+
+	expect = this_p->num_addr;
+	this_p->num_addr = (-1);
+	if (expect != ax25_get_num_addr (this_p)) {
+	  printf ("Internal error ax25_remove_addr expect %d, actual %d\n", expect, this_p->num_addr);
+	}
+
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_get_num_addr
+ * 
+ * Purpose:	Return number of addresses in current packet.
+ *
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Returns:	Number of addresses in the current packet.
+ *		Should be in the range of 2 .. AX25_MAX_ADDRS.
+ *
+ * Version 0.9:	Could be zero for a non AX.25 frame in KISS mode.
+ *
+ *------------------------------------------------------------------------------*/
+
+int ax25_get_num_addr (packet_t this_p)
+{
+	//unsigned char *pf;
+	int a;
+	int addr_bytes;
+
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+/* Use cached value if already set. */
+
+	if (this_p->num_addr >= 0) {
+	  return (this_p->num_addr);
+	}
+
+/* Otherwise, determine the number ofaddresses. */
+
+	this_p->num_addr = 0;		/* Number of addresses extracted. */
+	
+	addr_bytes = 0;
+	for (a = 0; a < this_p->frame_len && addr_bytes == 0; a++) {
+	  if (this_p->frame_data[a] & SSID_LAST_MASK) {
+	    addr_bytes = a + 1;
+	  }
+	}
+
+	if (addr_bytes % 7 == 0) {
+	  int addrs = addr_bytes / 7;
+	  if (addrs >= AX25_MIN_ADDRS && addrs <= AX25_MAX_ADDRS) {
+	    this_p->num_addr = addrs;
+	  }
+	}
+	
+	return (this_p->num_addr);
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_get_num_repeaters
+ * 
+ * Purpose:	Return number of repeater addresses in current packet.
+ *
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Returns:	Number of addresses in the current packet - 2.
+ *		Should be in the range of 0 .. AX25_MAX_ADDRS - 2.
+ *
+ *------------------------------------------------------------------------------*/
+
+int ax25_get_num_repeaters (packet_t this_p)
+{
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	if (this_p->num_addr >= 2) {
+	  return (this_p->num_addr - 2);
+	}
+
+	return (0);
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_get_addr_with_ssid
+ * 
+ * Purpose:	Return specified address with any SSID in current packet.
+ *
+ * Inputs:	n	- Index of address.   Use the symbols 
+ *			  AX25_DESTINATION, AX25_SOURCE, AX25_REPEATER1, etc.
+ *
+ * Outputs:	station - String representation of the station, including the SSID.
+ *			e.g.  "WB2OSZ-15"
+ *			  Usually variables will be AX25_MAX_ADDR_LEN bytes
+ *			  but 10 would be adequate.
+ *
+ * Bugs:	No bounds checking is performed.  Be careful.
+ *		  
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Returns:	Character string in usual human readable format,
+ *		
+ *
+ *------------------------------------------------------------------------------*/
+
+void ax25_get_addr_with_ssid (packet_t this_p, int n, char *station)
+{	
+	int ssid;
+	char sstr[8];		/* Should be 1 or 2 digits for SSID. */
+	int i;
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+
+	if (n < 0) {
+	  printf ("Internal error detected in ax25_get_addr_with_ssid, %s, line %d.\n", __FILE__, __LINE__);
+	  printf ("Address index, %d, is less than zero.\n", n);
+	  strlcpy (station, "??????", 10);
+	  return;
+	}
+
+	if (n >= this_p->num_addr) {
+	  printf ("Internal error detected in ax25_get_addr_with_ssid, %s, line %d.\n", __FILE__, __LINE__);
+	  printf ("Address index, %d, is too large for number of addresses, %d.\n", n, this_p->num_addr);
+	  strlcpy (station, "??????", 10);
+	  return;
+	}
+
+	// At one time this would stop at the first space, on the assumption we would have only trailing spaces.
+	// Then there was a forum discussion where someone encountered the address " WIDE2" with a leading space.
+	// In that case, we would have returned a zero length string here.
+	// Now we return exactly what is in the address field and trim trailing spaces.
+	// This will provide better information for troubleshooting.
+
+	for (i=0; i<6; i++) {
+	  station[i] = (this_p->frame_data[n*7+i] >> 1) & 0x7f;
+	}
+	station[6] = '\0';
+
+	for (i=5; i>=0; i--) {
+	  if (station[i] == ' ')
+	    station[i] = '\0';
+	  else
+	    break;
+	}
+
+	ssid = ax25_get_ssid (this_p, n);
+	if (ssid != 0) {
+	  snprintf (sstr, sizeof(sstr), "-%d", ssid);
+	  strlcat (station, sstr, 10);
+	}
+
+} /* end ax25_get_addr_with_ssid */
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_get_addr_no_ssid
+ * 
+ * Purpose:	Return specified address WITHOUT any SSID.
+ *
+ * Inputs:	n	- Index of address.   Use the symbols 
+ *			  AX25_DESTINATION, AX25_SOURCE, AX25_REPEATER1, etc.
+ *
+ * Outputs:	station - String representation of the station, WITHOUT the SSID.
+ *			e.g.  "WB2OSZ"
+ *			  Usually variables will be AX25_MAX_ADDR_LEN bytes
+ *			  but 7 would be adequate.
+ *
+ * Bugs:	No bounds checking is performed.  Be careful.
+ *		  
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Returns:	Character string in usual human readable format,
+ *		
+ *
+ *------------------------------------------------------------------------------*/
+
+void ax25_get_addr_no_ssid (packet_t this_p, int n, char *station)
+{	
+	int i;
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+
+	if (n < 0) {
+	  printf ("Internal error detected in ax25_get_addr_no_ssid, %s, line %d.\n", __FILE__, __LINE__);
+	  printf ("Address index, %d, is less than zero.\n", n);
+	  strlcpy (station, "??????", 7);
+	  return;
+	}
+
+	if (n >= this_p->num_addr) {
+	  printf ("Internal error detected in ax25_get_no_with_ssid, %s, line %d.\n", __FILE__, __LINE__);
+	  printf ("Address index, %d, is too large for number of addresses, %d.\n", n, this_p->num_addr);
+	  strlcpy (station, "??????", 7);
+	  return;
+	}
+
+	// At one time this would stop at the first space, on the assumption we would have only trailing spaces.
+	// Then there was a forum discussion where someone encountered the address " WIDE2" with a leading space.
+	// In that case, we would have returned a zero length string here.
+	// Now we return exactly what is in the address field and trim trailing spaces.
+	// This will provide better information for troubleshooting.
+
+	for (i=0; i<6; i++) {
+	  station[i] = (this_p->frame_data[n*7+i] >> 1) & 0x7f;
+	}
+	station[6] = '\0';
+
+	for (i=5; i>=0; i--) {
+	  if (station[i] == ' ')
+	    station[i] = '\0';
+	  else
+	    break;
+	}
+
+} /* end ax25_get_addr_no_ssid */
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_get_ssid
+ * 
+ * Purpose:	Return SSID of specified address in current packet.
+ *
+ * Inputs:	n	- Index of address.   Use the symbols 
+ *			  AX25_DESTINATION, AX25_SOURCE, AX25_REPEATER1, etc.
+ *
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Returns:	Substation id, as integer 0 .. 15.
+ *
+ *------------------------------------------------------------------------------*/
+
+int ax25_get_ssid (packet_t this_p, int n)
+{
+	
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+	
+	if (n >= 0 && n < this_p->num_addr) {
+	  return ((this_p->frame_data[n*7+6] & SSID_SSID_MASK) >> SSID_SSID_SHIFT);
+	}
+	else {
+	  printf ("Internal error: ax25_get_ssid(%d), num_addr=%d\n", n, this_p->num_addr);
+	  return (0);
+	}
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_set_ssid
+ * 
+ * Purpose:	Set the SSID of specified address in current packet.
+ *
+ * Inputs:	n	- Index of address.   Use the symbols 
+ *			  AX25_DESTINATION, AX25_SOURCE, AX25_REPEATER1, etc.
+ *
+ *		ssid	- New SSID.  Must be in range of 0 to 15.
+ *
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Bugs:	Rewrite to keep call and SSID separate internally.
+ *
+ *------------------------------------------------------------------------------*/
+
+void ax25_set_ssid (packet_t this_p, int n, int ssid)
+{
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+
+	if (n >= 0 && n < this_p->num_addr) {
+	  this_p->frame_data[n*7+6] =   (this_p->frame_data[n*7+6] & ~ SSID_SSID_MASK) |
+		((ssid << SSID_SSID_SHIFT) & SSID_SSID_MASK) ;
+	}
+	else {
+	  printf ("Internal error: ax25_set_ssid(%d,%d), num_addr=%d\n", n, ssid, this_p->num_addr);
+	}
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_get_h
+ * 
+ * Purpose:	Return "has been repeated" flag of specified address in current packet.
+ *
+ * Inputs:	n	- Index of address.   Use the symbols 
+ *			  AX25_DESTINATION, AX25_SOURCE, AX25_REPEATER1, etc.
+ *
+ * Bugs:	No bounds checking is performed.  Be careful.
+ *		  
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Returns:	True or false.
+ *
+ *------------------------------------------------------------------------------*/
+
+int ax25_get_h (packet_t this_p, int n)
+{
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+	assert (n >= 0 && n < this_p->num_addr);
+
+	if (n >= 0 && n < this_p->num_addr) {
+	  return ((this_p->frame_data[n*7+6] & SSID_H_MASK) >> SSID_H_SHIFT);
+	}
+	else {
+	  printf ("Internal error: ax25_get_h(%d), num_addr=%d\n", n, this_p->num_addr);
+	  return (0);
+	}
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_set_h
+ * 
+ * Purpose:	Set the "has been repeated" flag of specified address in current packet.
+ *
+ * Inputs:	n	- Index of address.   Use the symbols 
+ *			 Should be in range of AX25_REPEATER_1 .. AX25_REPEATER_8.
+ *
+ * Bugs:	No bounds checking is performed.  Be careful.
+ *		  
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Returns:	None
+ *
+ *------------------------------------------------------------------------------*/
+
+void ax25_set_h (packet_t this_p, int n)
+{
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	if (n >= 0 && n < this_p->num_addr) {
+	  this_p->frame_data[n*7+6] |= SSID_H_MASK;
+	}
+	else {
+	  printf ("Internal error: ax25_set_hd(%d), num_addr=%d\n", n, this_p->num_addr);
+	}
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_get_heard
+ * 
+ * Purpose:	Return index of the station that we heard.
+ *		
+ * Inputs:	none
+ *
+ *		  
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Returns:	If any of the digipeaters have the has-been-repeated bit set, 
+ *		return the index of the last one.  Otherwise return index for source.
+ *
+ *------------------------------------------------------------------------------*/
+
+int ax25_get_heard(packet_t this_p)
+{
+	int i;
+	int result;
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	result = AX25_SOURCE;
+
+	for (i = AX25_REPEATER_1; i < ax25_get_num_addr(this_p); i++) {
+	
+	  if (ax25_get_h(this_p,i)) {
+	    result = i;
+	  }
+	}
+	return (result);
+}
+
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_get_first_not_repeated
+ * 
+ * Purpose:	Return index of the first repeater that does NOT have the 
+ *		"has been repeated" flag set or -1 if none.
+ *
+ * Inputs:	none
+ *
+ *		  
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Returns:	In range of X25_REPEATER_1 .. X25_REPEATER_8 or -1 if none.
+ *
+ *------------------------------------------------------------------------------*/
+
+int ax25_get_first_not_repeated(packet_t this_p)
+{
+	int i;
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	for (i = AX25_REPEATER_1; i < ax25_get_num_addr(this_p); i++) {
+	
+	  if ( ! ax25_get_h(this_p,i)) {
+	    return (i);
+	  }
+	}
+	return (-1);
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_get_rr
+ *
+ * Purpose:	Return the two reserved "RR" bits in the specified address field.
+ *
+ * Inputs:	pp	- Packet object.
+ *
+ *		n	- Index of address.   Use the symbols
+ *			  AX25_DESTINATION, AX25_SOURCE, AX25_REPEATER1, etc.
+ *
+ * Returns:	0, 1, 2, or 3.
+ *
+ *------------------------------------------------------------------------------*/
+
+int ax25_get_rr (packet_t this_p, int n)
+{
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+	assert (n >= 0 && n < this_p->num_addr);
+
+	if (n >= 0 && n < this_p->num_addr) {
+	  return ((this_p->frame_data[n*7+6] & SSID_RR_MASK) >> SSID_RR_SHIFT);
+	}
+	else {
+	  printf ("Internal error: ax25_get_rr(%d), num_addr=%d\n", n, this_p->num_addr);
+	  return (0);
+	}
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_get_info
+ * 
+ * Purpose:	Obtain Information part of current packet.
+ *
+ * Inputs:	this_p	- Packet object pointer.
+ *
+ * Outputs:	paddr	- Starting address of information part is returned here.
+ *
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Returns:	Number of octets in the Information part.
+ *		Should be in the range of AX25_MIN_INFO_LEN .. AX25_MAX_INFO_LEN.
+ *
+ *------------------------------------------------------------------------------*/
+
+int ax25_get_info (packet_t this_p, unsigned char **paddr)
+{
+	unsigned char *info_ptr;
+	int info_len;
+
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	if (this_p->num_addr >= 2) {
+
+	  /* AX.25 */
+
+	  info_ptr = this_p->frame_data + ax25_get_info_offset(this_p);
+	  info_len = ax25_get_num_info(this_p);
+	}
+	else {
+
+	  /* Not AX.25.  Treat Whole packet as info. */
+
+	  info_ptr = this_p->frame_data;
+	  info_len = this_p->frame_len;
+	}
+
+	/* Add nul character in case caller treats as printable string. */
+	
+	assert (info_len >= 0);
+
+	info_ptr[info_len] = '\0';
+
+	*paddr = info_ptr;
+	return (info_len);
+
+} /* end ax25_get_info */
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_cut_at_crlf
+ *
+ * Purpose:	Truncate the information part at the first CR or LF.
+ *		This is used for the RF>IS IGate function.
+ *		CR/LF is used as record separator so we must remove it
+ *		before packaging up packet to sending to server.
+ *
+ * Inputs:	this_p	- Packet object pointer.
+ *
+ * Outputs:	Packet is modified in place.
+ *
+ * Returns:	Number of characters removed from the end.
+ *		0 if not changed.
+ *
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ *------------------------------------------------------------------------------*/
+
+int ax25_cut_at_crlf (packet_t this_p)
+{
+	unsigned char *info_ptr;
+	int info_len;
+	int j;
+
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	info_len = ax25_get_info (this_p, &info_ptr);
+
+	// Can't use strchr because there is potential of nul character.
+
+	for (j = 0; j < info_len; j++) {
+
+	  if (info_ptr[j] == '\r' || info_ptr[j] == '\n') {
+
+	    int chop = info_len - j;
+
+	    this_p->frame_len -= chop;
+	    return (chop);
+	  }
+	}
+
+	return (0);
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_get_dti
+ * 
+ * Purpose:	Get Data Type Identifier from Information part.
+ *
+ * Inputs:	None.
+ *
+ * Assumption:	ax25_from_text or ax25_from_frame was called first.
+ *
+ * Returns:	First byte from the information part.
+ *
+ *------------------------------------------------------------------------------*/
+
+int ax25_get_dti (packet_t this_p)
+{
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	if (this_p->num_addr >= 2) {
+	  return (this_p->frame_data[ax25_get_info_offset(this_p)]);
+	}
+	return (' ');
+}
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_set_nextp
+ * 
+ * Purpose:	Set next packet object in queue.
+ *
+ * Inputs:	this_p		- Current packet object.
+ *
+ *		next_p		- pointer to next one
+ *
+ * Description:	This is used to build a linked list for a queue.
+ *
+ *------------------------------------------------------------------------------*/
+
+void ax25_set_nextp (packet_t this_p, packet_t next_p)
+{
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+	
+	this_p->nextp = next_p;
+}
+
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_get_nextp
+ * 
+ * Purpose:	Obtain next packet object in queue.
+ *
+ * Inputs:	Packet object.
+ *
+ * Returns:	Following object in queue or NULL.
+ *
+ *------------------------------------------------------------------------------*/
+
+packet_t ax25_get_nextp (packet_t this_p)
+{
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	return (this_p->nextp);
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_set_release_time
+ *
+ * Purpose:	Set release time
+ *
+ * Inputs:	this_p		- Current packet object.
+ *
+ *		release_time	- Time as returned by dtime_now().
+ *
+ *------------------------------------------------------------------------------*/
+
+void ax25_set_release_time (packet_t this_p, double release_time)
+{
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+	
+	this_p->release_time = release_time;
+}
+
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_get_release_time
+ *
+ * Purpose:	Get release time.
+ *
+ *------------------------------------------------------------------------------*/
+
+double ax25_get_release_time (packet_t this_p)
+{
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	return (this_p->release_time);
+}
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_set_modulo
+ *
+ * Purpose:	Set modulo value for I and S frame sequence numbers.
+ *
+ *------------------------------------------------------------------------------*/
+
+void ax25_set_modulo (packet_t this_p, int modulo)
+{
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	this_p->modulo = modulo;
+}
+
+
+
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ax25_format_addrs
+ *
+ * Purpose:	Format all the addresses suitable for printing.
+ *
+ *		The AX.25 spec refers to this as "Source Path Header" - "TNC-2" Format
+ *
+ * Inputs:	Current packet.
+ *		
+ * Outputs:	result	- All addresses combined into a single string of the form:
+ *
+ *				"Source > Destination [ , repeater ... ] :"
+ *
+ *			An asterisk is displayed after the last digipeater 
+ *			with the "H" bit set.  e.g.  If we hear RPT2, 
+ *
+ *			SRC>DST,RPT1,RPT2*,RPT3:
+ *
+ *			No asterisk means the source is being heard directly.
+ *			Needs to be 101 characters to avoid overflowing.
+ *			(Up to 100 characters + \0)
+ *
+ * Errors:	No error checking so caller needs to be careful.
+ *
+ *
+ *------------------------------------------------------------------*/
+
+// TODO: max len for result.  buffer overflow?
+
+void ax25_format_addrs (packet_t this_p, char *result)
+{
+	int i;
+	int heard;
+	char stemp[AX25_MAX_ADDR_LEN];
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+	*result = '\0';
+
+	/* New in 0.9. */
+	/* Don't get upset if no addresses.  */
+	/* This will allow packets that do not comply to AX.25 format. */
+
+	if (this_p->num_addr == 0) {
+	  return;
+	}
+
+	ax25_get_addr_with_ssid (this_p, AX25_SOURCE, stemp);
+	strcat (result, stemp);
+	strcat (result, ">");
+
+	ax25_get_addr_with_ssid (this_p, AX25_DESTINATION, stemp);
+	strcat (result, stemp);
+
+	heard = ax25_get_heard(this_p);
+
+	for (i=(int)AX25_REPEATER_1; i<this_p->num_addr; i++) {
+	  ax25_get_addr_with_ssid (this_p, i, stemp);
+	  strcat (result, ",");
+	  strcat (result, stemp);
+	  if (i == heard) {
+	    strcat (result, "*");
+	  }
+	}
+	
+	strcat (result, ":");
+}
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ax25_format_via_path
+ *
+ * Purpose:	Format via path addresses suitable for printing.
+ *
+ * Inputs:	Current packet.
+ *
+ *		result_size	- Number of bytes available for result.
+ *				  We can have up to 8 addresses x 9 characters
+ *				  plus 7 commas, possible *, and nul = 81 minimum.
+ *
+ * Outputs:	result	- Digipeater field addresses combined into a single string of the form:
+ *
+ *				"repeater, repeater ..."
+ *
+ *			An asterisk is displayed after the last digipeater
+ *			with the "H" bit set.  e.g.  If we hear RPT2,
+ *
+ *			RPT1,RPT2*,RPT3
+ *
+ *			No asterisk means the source is being heard directly.
+ *
+ *------------------------------------------------------------------*/
+
+void ax25_format_via_path (packet_t this_p, char *result, size_t result_size)
+{
+	int i;
+	int heard;
+	char stemp[AX25_MAX_ADDR_LEN];
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+	*result = '\0';
+
+	/* Don't get upset if no addresses.  */
+	/* This will allow packets that do not comply to AX.25 format. */
+
+	if (this_p->num_addr == 0) {
+	  return;
+	}
+
+	heard = ax25_get_heard(this_p);
+
+	for (i=(int)AX25_REPEATER_1; i<this_p->num_addr; i++) {
+	  if (i > (int)AX25_REPEATER_1) {
+	    strlcat (result, ",", result_size);
+	  }
+	  ax25_get_addr_with_ssid (this_p, i, stemp);
+	  strlcat (result, stemp, result_size);
+	  if (i == heard) {
+	    strlcat (result, "*", result_size);
+	  }
+	}
+
+} /* end ax25_format_via_path */
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ax25_pack
+ *
+ * Purpose:	Put all the pieces into format ready for transmission.
+ *
+ * Inputs:	this_p	- pointer to packet object.
+ *		
+ * Outputs:	result		- Frame buffer, AX25_MAX_PACKET_LEN bytes.
+ *				Should also have two extra for FCS to be
+ *				added later.
+ *
+ * Returns:	Number of octets in the frame buffer.  
+ *		Does NOT include the extra 2 for FCS.
+ *
+ * Errors:	Returns -1.
+ *
+ *------------------------------------------------------------------*/
+
+int ax25_pack (packet_t this_p, unsigned char result[AX25_MAX_PACKET_LEN]) 
+{
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	assert (this_p->frame_len >= 0 && this_p->frame_len <= AX25_MAX_PACKET_LEN);
+
+	memcpy (result, this_p->frame_data, this_p->frame_len);
+
+	return (this_p->frame_len);
+}
+
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ax25_frame_type
+ *
+ * Purpose:	Extract the type of frame.
+ *		This is derived from the control byte(s) but
+ *		is an enumerated type for easier handling.
+ *
+ * Inputs:	this_p	- pointer to packet object.
+ *		
+ * Outputs:	desc	- Text description such as "I frame" or
+ *			  "U frame SABME".   
+ *			  Supply 40 bytes to be safe.
+ *
+ *		cr	- Command or response?
+ *
+ *		pf	- P/F - Poll/Final or -1 if not applicable
+ *
+ *		nr	- N(R) - receive sequence or -1 if not applicable.
+ *
+ *		ns	- N(S) - send sequence or -1 if not applicable.
+ *	
+ * Returns:	Frame type from  enum ax25_frame_type_e.
+ *
+ *------------------------------------------------------------------*/
+
+// TODO: need someway to ensure caller allocated enough space.
+// Should pass in as parameter.
+#define DESC_SIZ 40
+
+
+ax25_frame_type_t ax25_frame_type (packet_t this_p, cmdres_t *cr, char *desc, int *pf, int *nr, int *ns) 
+{
+	int c;		// U frames are always one control byte.
+	int c2 = 0;	// I & S frames can have second Control byte.
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	strlcpy (desc, "????", DESC_SIZ);
+	*cr = cr_11;
+	*pf = -1;
+	*nr = -1;
+	*ns = -1;
+
+	c = ax25_get_control(this_p);
+	if (c < 0) {
+	  strlcpy (desc, "Not AX.25", DESC_SIZ);
+	  return (frame_not_AX25);
+	}
+
+/*
+ * TERRIBLE HACK :-(  for display purposes.
+ *
+ * I and S frames can have 1 or 2 control bytes but there is
+ * no good way to determine this without dipping into the data
+ * link state machine.  Can we guess?
+ *
+ * S frames have no protocol id or information so if there is one
+ * more byte beyond the control field, we could assume there are
+ * two control bytes.
+ *
+ * For I frames, the protocol id will usually be 0xf0.  If we find
+ * that as the first byte of the information field, it is probably
+ * the pid and not part of the information.  Ditto for segments 0x08.
+ * Not fool proof but good enough for troubleshooting text out.
+ *
+ * If we have a link to the peer station, this will be set properly
+ * before it needs to be used for other reasons.
+ *
+ * Setting one of the RR bits (find reference!) is sounding better and better.
+ * It's in common usage so I should lobby to get that in the official protocol spec.
+ */
+
+	if (this_p->modulo == 0 && (c & 3) == 1 && ax25_get_c2(this_p) != -1) {
+	  this_p->modulo = modulo_128;
+	}
+	else if (this_p->modulo == 0 && (c & 1) == 0 && this_p->frame_data[ax25_get_info_offset(this_p)] == 0xF0) {
+	  this_p->modulo = modulo_128;
+	}
+	else if (this_p->modulo == 0 && (c & 1) == 0 && this_p->frame_data[ax25_get_info_offset(this_p)] == 0x08) {	// same for segments
+	  this_p->modulo = modulo_128;
+	}
+
+
+	if (this_p->modulo == modulo_128) {
+	  c2 = ax25_get_c2 (this_p);
+	}
+
+	int dst_c = this_p->frame_data[AX25_DESTINATION * 7 + 6] & SSID_H_MASK;
+	int src_c = this_p->frame_data[AX25_SOURCE * 7 + 6] & SSID_H_MASK;
+
+	char cr_text[8];
+	char pf_text[8];
+
+	if (dst_c) {
+	  if (src_c) { *cr = cr_11;  strcpy(cr_text,"cc=11"); strcpy(pf_text,"p/f"); }
+	  else       { *cr = cr_cmd; strcpy(cr_text,"cmd");   strcpy(pf_text,"p"); }
+	}
+	else {
+	  if (src_c) { *cr = cr_res; strcpy(cr_text,"res");   strcpy(pf_text,"f"); }
+	  else       { *cr = cr_00;  strcpy(cr_text,"cc=00"); strcpy(pf_text,"p/f"); }
+	}
+
+	if ((c & 1) == 0) {
+
+// Information 			rrr p sss 0		or	sssssss 0  rrrrrrr p
+
+	  if (this_p->modulo == modulo_128) {
+	    *ns = (c >> 1) & 0x7f;
+	    *pf = c2 & 1;
+	    *nr = (c2 >> 1) & 0x7f;
+	  }
+	  else {
+	    *ns = (c >> 1) & 7;
+	    *pf = (c >> 4) & 1;
+	    *nr = (c >> 5) & 7;
+	  }
+
+	  //snprintf (desc, DESC_SIZ, "I %s, n(s)=%d, n(r)=%d, %s=%d", cr_text, *ns, *nr, pf_text, *pf);
+	  snprintf (desc, DESC_SIZ, "I %s, n(s)=%d, n(r)=%d, %s=%d, pid=0x%02x", cr_text, *ns, *nr, pf_text, *pf, ax25_get_pid(this_p));
+	  return (frame_type_I);
+	}
+	else if ((c & 2) == 0) {
+
+// Supervisory			rrr p/f ss 0 1		or	0000 ss 0 1  rrrrrrr p/f
+
+	  if (this_p->modulo == modulo_128) {
+	    *pf = c2 & 1;
+	    *nr = (c2 >> 1) & 0x7f;
+	  }
+	  else {
+	    *pf = (c >> 4) & 1;
+	    *nr = (c >> 5) & 7;
+	  }
+
+ 
+	  switch ((c >> 2) & 3) {
+	    case 0: snprintf (desc, DESC_SIZ, "RR %s, n(r)=%d, %s=%d", cr_text, *nr, pf_text, *pf);   return (frame_type_S_RR);   break;
+	    case 1: snprintf (desc, DESC_SIZ, "RNR %s, n(r)=%d, %s=%d", cr_text, *nr, pf_text, *pf);  return (frame_type_S_RNR);  break;
+	    case 2: snprintf (desc, DESC_SIZ, "REJ %s, n(r)=%d, %s=%d", cr_text, *nr, pf_text, *pf);  return (frame_type_S_REJ);  break;
+	    case 3: snprintf (desc, DESC_SIZ, "SREJ %s, n(r)=%d, %s=%d", cr_text, *nr, pf_text, *pf); return (frame_type_S_SREJ); break;
+	 } 
+	}
+	else {
+
+// Unnumbered			mmm p/f mm 1 1
+
+	  *pf = (c >> 4) & 1;
+	  
+	  switch (c & 0xef) {
+	
+	    case 0x6f: snprintf (desc, DESC_SIZ, "SABME %s, %s=%d",	cr_text, pf_text, *pf);  return (frame_type_U_SABME); break;
+	    case 0x2f: snprintf (desc, DESC_SIZ, "SABM %s, %s=%d", 	cr_text, pf_text, *pf);  return (frame_type_U_SABM);  break;
+	    case 0x43: snprintf (desc, DESC_SIZ, "DISC %s, %s=%d", 	cr_text, pf_text, *pf);  return (frame_type_U_DISC);  break;
+	    case 0x0f: snprintf (desc, DESC_SIZ, "DM %s, %s=%d", 	cr_text, pf_text, *pf);  return (frame_type_U_DM);    break;
+	    case 0x63: snprintf (desc, DESC_SIZ, "UA %s, %s=%d", 	cr_text, pf_text, *pf);  return (frame_type_U_UA);    break;
+	    case 0x87: snprintf (desc, DESC_SIZ, "FRMR %s, %s=%d", 	cr_text, pf_text, *pf);  return (frame_type_U_FRMR);  break;
+	    case 0x03: snprintf (desc, DESC_SIZ, "UI %s, %s=%d", 	cr_text, pf_text, *pf);  return (frame_type_U_UI);    break;
+	    case 0xaf: snprintf (desc, DESC_SIZ, "XID %s, %s=%d", 	cr_text, pf_text, *pf);  return (frame_type_U_XID);   break;
+	    case 0xe3: snprintf (desc, DESC_SIZ, "TEST %s, %s=%d", 	cr_text, pf_text, *pf);  return (frame_type_U_TEST);  break;
+	    default:   snprintf (desc, DESC_SIZ, "U other???");        				 return (frame_type_U);       break;
+	  }
+	}
+
+	// Should be unreachable but compiler doesn't realize that.
+	// Here only to suppress "warning: control reaches end of non-void function"
+
+	return (frame_not_AX25);
+
+} /* end ax25_frame_type */
+
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ax25_hex_dump
+ *
+ * Purpose:	Print out packet in hexadecimal for debugging.
+ *
+ * Inputs:	fptr		- Pointer to frame data.
+ *
+ *		flen		- Frame length, bytes.  Does not include CRC.
+ *		
+ *------------------------------------------------------------------*/
+
+static void hex_dump (unsigned char *p, int len) 
+{
+	int n, i, offset;
+
+	offset = 0;
+	while (len > 0) {
+	  n = len < 16 ? len : 16; 
+	  printf ("  %03x: ", offset);
+	  for (i=0; i<n; i++) {
+	    printf (" %02x", p[i]);
+	  }
+	  for (i=n; i<16; i++) {
+	    printf ("   ");
+	  }
+	  printf ("  ");
+	  for (i=0; i<n; i++) {
+	    printf ("%c", isprint(p[i]) ? p[i] : '.');
+	  }
+	  printf ("\n");
+	  p += 16;
+	  offset += 16;
+	  len -= 16;
+	}
+}
+
+/* Text description of control octet. */
+// FIXME:  this is wrong.  It doesn't handle modulo 128.
+
+// TODO: use ax25_frame_type() instead.
+
+static void ctrl_to_text (int c, char *out, size_t outsiz)
+{
+	if      ((c & 1) == 0)       { snprintf (out, outsiz, "I frame: n(r)=%d, p=%d, n(s)=%d",  (c>>5)&7, (c>>4)&1, (c>>1)&7); }
+	else if ((c & 0xf) == 0x01)  { snprintf (out, outsiz, "S frame RR: n(r)=%d, p/f=%d",  (c>>5)&7, (c>>4)&1); }
+	else if ((c & 0xf) == 0x05)  { snprintf (out, outsiz, "S frame RNR: n(r)=%d, p/f=%d",  (c>>5)&7, (c>>4)&1); }
+	else if ((c & 0xf) == 0x09)  { snprintf (out, outsiz, "S frame REJ: n(r)=%d, p/f=%d",  (c>>5)&7, (c>>4)&1); }
+	else if ((c & 0xf) == 0x0D)  { snprintf (out, outsiz, "S frame sREJ: n(r)=%d, p/f=%d",  (c>>5)&7, (c>>4)&1); }
+	else if ((c & 0xef) == 0x6f) { snprintf (out, outsiz, "U frame SABME: p=%d", (c>>4)&1); }
+	else if ((c & 0xef) == 0x2f) { snprintf (out, outsiz, "U frame SABM: p=%d", (c>>4)&1); }
+	else if ((c & 0xef) == 0x43) { snprintf (out, outsiz, "U frame DISC: p=%d", (c>>4)&1); }
+	else if ((c & 0xef) == 0x0f) { snprintf (out, outsiz, "U frame DM: f=%d", (c>>4)&1); }
+	else if ((c & 0xef) == 0x63) { snprintf (out, outsiz, "U frame UA: f=%d", (c>>4)&1); }
+	else if ((c & 0xef) == 0x87) { snprintf (out, outsiz, "U frame FRMR: f=%d", (c>>4)&1); }
+	else if ((c & 0xef) == 0x03) { snprintf (out, outsiz, "U frame UI: p/f=%d", (c>>4)&1); }
+	else if ((c & 0xef) == 0xAF) { snprintf (out, outsiz, "U frame XID: p/f=%d", (c>>4)&1); }
+	else if ((c & 0xef) == 0xe3) { snprintf (out, outsiz, "U frame TEST: p/f=%d", (c>>4)&1); }
+	else                         { snprintf (out, outsiz, "Unknown frame type for control = 0x%02x", c); }
+}
+
+/* Text description of protocol id octet. */
+
+#define PID_TEXT_SIZE 80
+
+static void pid_to_text (int p, char out[PID_TEXT_SIZE])
+{
+
+	if      ((p & 0x30) == 0x10) { snprintf (out, PID_TEXT_SIZE, "AX.25 layer 3 implemented."); }
+	else if ((p & 0x30) == 0x20) { snprintf (out, PID_TEXT_SIZE, "AX.25 layer 3 implemented."); }
+	else if (p == 0x01)          { snprintf (out, PID_TEXT_SIZE, "ISO 8208/CCITT X.25 PLP"); }
+	else if (p == 0x06)          { snprintf (out, PID_TEXT_SIZE, "Compressed TCP/IP packet. Van Jacobson (RFC 1144)"); }
+	else if (p == 0x07)          { snprintf (out, PID_TEXT_SIZE, "Uncompressed TCP/IP packet. Van Jacobson (RFC 1144)"); }
+	else if (p == 0x08)          { snprintf (out, PID_TEXT_SIZE, "Segmentation fragment"); }
+	else if (p == 0xC3)          { snprintf (out, PID_TEXT_SIZE, "TEXNET datagram protocol"); }
+	else if (p == 0xC4)          { snprintf (out, PID_TEXT_SIZE, "Link Quality Protocol"); }
+	else if (p == 0xCA)          { snprintf (out, PID_TEXT_SIZE, "Appletalk"); }
+	else if (p == 0xCB)          { snprintf (out, PID_TEXT_SIZE, "Appletalk ARP"); }
+	else if (p == 0xCC)          { snprintf (out, PID_TEXT_SIZE, "ARPA Internet Protocol"); }
+	else if (p == 0xCD)          { snprintf (out, PID_TEXT_SIZE, "ARPA Address resolution"); }
+	else if (p == 0xCE)          { snprintf (out, PID_TEXT_SIZE, "FlexNet"); }
+	else if (p == 0xCF)          { snprintf (out, PID_TEXT_SIZE, "NET/ROM"); }
+	else if (p == 0xF0)          { snprintf (out, PID_TEXT_SIZE, "No layer 3 protocol implemented."); }
+	else if (p == 0xFF)          { snprintf (out, PID_TEXT_SIZE, "Escape character. Next octet contains more Level 3 protocol information."); }
+	else                         { snprintf (out, PID_TEXT_SIZE, "Unknown protocol id = 0x%02x", p); }
+}
+
+
+
+void ax25_hex_dump (packet_t this_p) 
+{
+	int n;
+	unsigned char *fptr = this_p->frame_data;
+	int flen = this_p->frame_len;
+
+
+	
+	if (this_p->num_addr >= AX25_MIN_ADDRS && this_p->num_addr <= AX25_MAX_ADDRS) {
+	  int c, p;
+	  char cp_text[120];
+	  char l_text[20];
+
+	  c = fptr[this_p->num_addr*7];
+	  p = fptr[this_p->num_addr*7+1];
+
+	  ctrl_to_text (c, cp_text, sizeof(cp_text)); // TODO: use ax25_frame_type() instead.
+
+	  if ( (c & 0x01) == 0 ||				/* I   xxxx xxx0 */
+	     	c == 0x03 || c == 0x13) {			/* UI  000x 0011 */
+
+	    char pid_text[PID_TEXT_SIZE];
+
+	    pid_to_text (p, pid_text);
+
+	    strlcat (cp_text, ", ", sizeof(cp_text));
+	    strlcat (cp_text, pid_text, sizeof(cp_text));
+
+	  }
+
+	  snprintf (l_text, sizeof(l_text), ", length = %d", flen);
+	  strlcat (cp_text, l_text, sizeof(cp_text));
+
+	  printf ("%s\n", cp_text);
+	}
+
+
+	printf (" dest    %c%c%c%c%c%c %2d c/r=%d res=%d last=%d\n",
+				fptr[0]>>1, fptr[1]>>1, fptr[2]>>1, fptr[3]>>1, fptr[4]>>1, fptr[5]>>1,
+				(fptr[6]&SSID_SSID_MASK)>>SSID_SSID_SHIFT,
+				(fptr[6]&SSID_H_MASK)>>SSID_H_SHIFT, 
+				(fptr[6]&SSID_RR_MASK)>>SSID_RR_SHIFT,
+				fptr[6]&SSID_LAST_MASK);
+
+	printf (" source  %c%c%c%c%c%c %2d c/r=%d res=%d last=%d\n",
+				fptr[7]>>1, fptr[8]>>1, fptr[9]>>1, fptr[10]>>1, fptr[11]>>1, fptr[12]>>1,
+				(fptr[13]&SSID_SSID_MASK)>>SSID_SSID_SHIFT,
+				(fptr[13]&SSID_H_MASK)>>SSID_H_SHIFT, 
+				(fptr[13]&SSID_RR_MASK)>>SSID_RR_SHIFT,
+				fptr[13]&SSID_LAST_MASK);
+
+	for (n=2; n<this_p->num_addr; n++) {	
+
+	  printf (" digi %d  %c%c%c%c%c%c %2d   h=%d res=%d last=%d\n",
+				n - 1,
+				fptr[n*7+0]>>1, fptr[n*7+1]>>1, fptr[n*7+2]>>1, fptr[n*7+3]>>1, fptr[n*7+4]>>1, fptr[n*7+5]>>1,
+				(fptr[n*7+6]&SSID_SSID_MASK)>>SSID_SSID_SHIFT,
+				(fptr[n*7+6]&SSID_H_MASK)>>SSID_H_SHIFT, 
+				(fptr[n*7+6]&SSID_RR_MASK)>>SSID_RR_SHIFT,
+				fptr[n*7+6]&SSID_LAST_MASK);
+
+	}
+
+	hex_dump (fptr, flen);
+
+} /* end ax25_hex_dump */
+
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ax25_is_aprs
+ *
+ * Purpose:	Is this packet APRS format?
+ *
+ * Inputs:	this_p	- pointer to packet object.
+ *		
+ * Returns:	True if this frame has the proper control
+ *		octets for an APRS packet.
+ *			control		3 for UI frame
+ *			protocol id	0xf0 for no layer 3
+ *
+ *
+ * Description:	Dire Wolf should be able to act as a KISS TNC for
+ *		any type of AX.25 activity.  However, there are other
+ *		places where we want to process only APRS.
+ *		(e.g. digipeating and IGate.)
+ *
+ *------------------------------------------------------------------*/
+
+
+int ax25_is_aprs (packet_t this_p) 
+{
+	int ctrl, pid, is_aprs;
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	if (this_p->frame_len == 0) return(0);
+
+	ctrl = ax25_get_control(this_p);
+	pid = ax25_get_pid(this_p);
+
+	is_aprs = this_p->num_addr >= 2 && ctrl == AX25_UI_FRAME && pid == AX25_PID_NO_LAYER_3;
+
+#if 0 
+        printf ("ax25_is_aprs(): ctrl=%02x, pid=%02x, is_aprs=%d\n", ctrl, pid, is_aprs);
+#endif
+	return (is_aprs);
+}
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ax25_is_null_frame
+ *
+ * Purpose:	Is this packet structure empty?
+ *
+ * Inputs:	this_p	- pointer to packet object.
+ *
+ * Returns:	True if frame data length is 0.
+ *
+ * Description:	This is used when we want to wake up the
+ *		transmit queue processing thread but don't
+ *		want to transmit a frame.
+ *
+ *------------------------------------------------------------------*/
+
+
+int ax25_is_null_frame (packet_t this_p)
+{
+	int is_null;
+
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	is_null = this_p->frame_len == 0;
+
+#if 0
+        printf ("ax25_is_null_frame(): is_null=%d\n", is_null);
+#endif
+	return (is_null);
+}
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ax25_get_control
+ 		ax25_get_c2
+ *
+ * Purpose:	Get Control field from packet.
+ *
+ * Inputs:	this_p	- pointer to packet object.
+ *		
+ * Returns:	APRS uses AX25_UI_FRAME.
+ *		This could also be used in other situations.
+ *
+ *------------------------------------------------------------------*/
+
+
+int ax25_get_control (packet_t this_p) 
+{
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	if (this_p->frame_len == 0) return(-1);
+
+	if (this_p->num_addr >= 2) {
+	  return (this_p->frame_data[ax25_get_control_offset(this_p)]);
+	}
+	return (-1);
+}
+
+int ax25_get_c2 (packet_t this_p) 
+{
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	if (this_p->frame_len == 0) return(-1);
+
+	if (this_p->num_addr >= 2) {
+	  int offset2 = ax25_get_control_offset(this_p)+1;
+
+	  if (offset2 < this_p->frame_len) {
+	    return (this_p->frame_data[offset2]);
+	  }
+	  else {
+	    return (-1);	/* attempt to go beyond the end of frame. */
+	  }
+	}
+	return (-1);		/* not AX.25 */
+}
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ax25_get_pid
+ *
+ * Purpose:	Get protocol ID from packet.
+ *
+ * Inputs:	this_p	- pointer to packet object.
+ *		
+ * Returns:	APRS uses 0xf0 for no layer 3.
+ *		This could also be used in other situations.
+ *
+ * AX.25:	"The Protocol Identifier (PID) field appears in information
+ *		 frames (I and UI) only. It identifies which kind of
+ *		 Layer 3 protocol, if any, is in use."
+ *
+ *------------------------------------------------------------------*/
+
+
+int ax25_get_pid (packet_t this_p) 
+{
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	// TODO: handle 2 control byte case.
+	// TODO: sanity check: is it I or UI frame?
+
+	if (this_p->frame_len == 0) return(-1);
+
+	if (this_p->num_addr >= 2) {
+	  return (this_p->frame_data[ax25_get_pid_offset(this_p)]);
+	}
+	return (-1);
+}
+
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ax25_get_frame_len
+ *
+ * Purpose:	Get length of frame.
+ *
+ * Inputs:	this_p	- pointer to packet object.
+ *		
+ * Returns:	Number of octets in the frame buffer.  
+ *		Does NOT include the extra 2 for FCS.
+ *
+ *------------------------------------------------------------------*/
+
+int ax25_get_frame_len (packet_t this_p) 
+{
+	assert (this_p->magic1 == MAGIC);
+	assert (this_p->magic2 == MAGIC);
+
+	assert (this_p->frame_len >= 0 && this_p->frame_len <= AX25_MAX_PACKET_LEN);
+
+	return (this_p->frame_len);
+
+} /* end ax25_get_frame_len */
+
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_dedupe_crc 
+ * 
+ * Purpose:	Calculate a checksum for the packet source, destination, and
+ *		information but NOT the digipeaters.
+ *		This is used for duplicate detection in the digipeater 
+ *		and IGate algorithms.
+ *
+ * Input:	pp	- Pointer to packet object.
+ *		
+ * Returns:	Value which will be the same for a duplicate but very unlikely 
+ *		to match a non-duplicate packet.
+ *
+ * Description:	For detecting duplicates, we need to look
+ *			+ source station
+ *			+ destination 
+ *			+ information field
+ *		but NOT the changing list of digipeaters.
+ *
+ *		Typically, only a checksum is kept to reduce memory 
+ *		requirements and amount of compution for comparisons.
+ *		There is a very very small probability that two unrelated 
+ *		packets will result in the same checksum, and the
+ *		undesired dropping of the packet.
+ *
+ *		There is a 1 / 65536 chance of getting a false positive match
+ *		which is good enough for this application.
+ *		We could reduce that with a 32 bit CRC instead of reusing
+ *		code from the AX.25 frame CRC calculation.
+ *
+ * Version 1.3:	We exclude any trailing CR/LF at the end of the info part
+ *		so we can detect duplicates that are received only over the
+ *		air and those which have gone thru an IGate where the process
+ *		removes any trailing CR/LF.   Example:
+ *
+ *		Original via RF only:
+ *		W1TG-1>APU25N,N3LEE-10*,WIDE2-1:<IGATE,MSG_CNT=30,LOC_CNT=61<0x0d>
+ *
+ *		When we get the same thing via APRS-IS:
+ *		W1TG-1>APU25N,K1FFK,WIDE2*,qAR,WB2ZII-15:<IGATE,MSG_CNT=30,LOC_CNT=61
+ *
+ *		(Actually there is a trailing space.  Maybe some systems
+ *		change control characters to space???)
+ *		Hmmmm.  I guess we should ignore trailing space as well for 
+ *		duplicate detection and suppression.
+ *		
+ *------------------------------------------------------------------------------*/
+
+unsigned short ax25_dedupe_crc (packet_t pp)
+{
+	unsigned short crc;
+	char src[AX25_MAX_ADDR_LEN];
+	char dest[AX25_MAX_ADDR_LEN];
+	unsigned char *pinfo;
+	int info_len;
+
+	ax25_get_addr_with_ssid(pp, AX25_SOURCE, src);
+	ax25_get_addr_with_ssid(pp, AX25_DESTINATION, dest);
+	info_len = ax25_get_info (pp, &pinfo);
+
+	while (info_len >= 1 && (pinfo[info_len-1] == '\r' ||
+	                         pinfo[info_len-1] == '\n' ||
+	                         pinfo[info_len-1] == ' ')) {
+
+	// Temporary for debugging!
+
+	//  if (pinfo[info_len-1] == ' ') {
+	//    printf ("DEBUG:  ax25_dedupe_crc ignoring trailing space.\n");
+	//  }
+
+	  info_len--;
+	}
+
+	crc = 0xffff;
+	crc = crc16((unsigned char *)src, strlen(src), crc);
+	crc = crc16((unsigned char *)dest, strlen(dest), crc);
+	crc = crc16(pinfo, info_len, crc);
+
+	return (crc);
+}
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_m_m_crc 
+ * 
+ * Purpose:	Calculate a checksum for the packet.
+ *		This is used for the multimodem duplicate detection.
+ *
+ * Input:	pp	- Pointer to packet object.
+ *		
+ * Returns:	Value which will be the same for a duplicate but very unlikely 
+ *		to match a non-duplicate packet.
+ *
+ * Description:	For detecting duplicates, we need to look the entire packet.
+ *
+ *		Typically, only a checksum is kept to reduce memory 
+ *		requirements and amount of compution for comparisons.
+ *		There is a very very small probability that two unrelated 
+ *		packets will result in the same checksum, and the
+ *		undesired dropping of the packet.
+		
+ *------------------------------------------------------------------------------*/
+
+unsigned short ax25_m_m_crc (packet_t pp)
+{
+	unsigned short crc;
+	unsigned char fbuf[AX25_MAX_PACKET_LEN];
+	int flen;
+
+	flen = ax25_pack (pp, fbuf); 
+
+	crc = 0xffff;
+	crc = crc16(fbuf, flen, crc);
+
+	return (crc);
+}
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ax25_safe_print
+ *
+ * Purpose:	Print given string, changing non printable characters to 
+ *		hexadecimal notation.   Note that character values
+ *		<DEL>, 28, 29, 30, and 31 can appear in MIC-E message.
+ *
+ * Inputs:	pstr	- Pointer to string.
+ *
+ *		len	- Number of bytes.  If < 0 we use strlen().
+ *
+ *		ascii_only	- Restrict output to only ASCII.
+ *				  Normally we allow UTF-8.
+ *		
+ *		Stops after non-zero len characters or at nul.
+ *
+ * Returns:	none
+ *
+ * Description:	Print a string in a "safe" manner.
+ *		Anything that is not a printable character
+ *		will be converted to a hexadecimal representation.
+ *		For example, a Line Feed character will appear as <0x0a>
+ *		rather than dropping down to the next line on the screen.
+ *
+ *		ax25_from_text can accept this format.
+ *
+ *
+ * Example:	W1MED-1>T2QP0S,N1OHZ,N8VIM*,WIDE1-1:'cQBl <0x1c>-/]<0x0d>
+ *		                                          ------   ------
+ *
+ * Questions:	What should we do about UTF-8?  Should that be displayed
+ *		as hexadecimal for troubleshooting? Maybe an option so the
+ *		packet raw data is in hexadecimal but an extracted 
+ *		comment displays UTF-8?  Or a command line option for only ASCII?
+ *
+ * Trailing space:
+ *		I recently noticed a case where a packet has space character
+ *		at the end.  If the last character of the line is a space,
+ *		this will be displayed in hexadecimal to make it obvious.
+ *			
+ *------------------------------------------------------------------*/
+
+#define MAXSAFE 500
+
+void ax25_safe_print (char *pstr, int len, int ascii_only)
+{
+	int ch;
+	char safe_str[MAXSAFE*6+1];
+	int safe_len;
+
+	safe_len = 0;
+	safe_str[safe_len] = '\0';
+
+
+	if (len < 0) 
+	  len = strlen(pstr);
+
+	if (len > MAXSAFE)
+	  len = MAXSAFE;
+
+	while (len > 0)
+	{
+	  ch = *((unsigned char *)pstr);
+
+	  if (ch == ' ' && (len == 1 || pstr[1] == '\0')) {
+
+	      snprintf (safe_str + safe_len, sizeof(safe_str)-safe_len, "<0x%02x>", ch);
+	      safe_len += 6;
+	  }
+	  else if (ch < ' ' || ch == 0x7f || ch == 0xfe || ch == 0xff ||
+			(ascii_only && ch >= 0x80) ) {
+
+	      /* Control codes and delete. */
+	      /* UTF-8 does not use fe and ff except in a possible */
+	      /* "Byte Order Mark" (BOM) at the beginning. */
+
+	      snprintf (safe_str + safe_len, sizeof(safe_str)-safe_len, "<0x%02x>", ch);
+	      safe_len += 6;
+	    }
+	  else {
+	    /* Let everything else thru so we can handle UTF-8 */
+	    /* Maybe we should have an option to display 0x80 */
+	    /* and above as hexadecimal. */
+
+	    safe_str[safe_len++] = ch;
+	    safe_str[safe_len] = '\0';
+	  }
+
+	  pstr++;
+	  len--;
+	}
+
+// TODO1.2: should return string rather printing to remove a race condition.
+
+	printf ("%s", safe_str);
+
+} /* end ax25_safe_print */
+
+
+
+
+/* end ax25_pad.c */

+ 446 - 0
main/ax25_pad.h

@@ -0,0 +1,446 @@
+/*-------------------------------------------------------------------
+ *
+ * Name:	ax25_pad.h
+ *
+ * Purpose:	Header file for using ax25_pad.c
+ *
+ *------------------------------------------------------------------*/
+
+#ifndef AX25_PAD_H
+#define AX25_PAD_H 1
+
+
+#define AX25_MAX_REPEATERS 8
+#define AX25_MIN_ADDRS 2	/* Destinatin & Source. */
+#define AX25_MAX_ADDRS 10	/* Destination, Source, 8 digipeaters. */	
+
+#define AX25_DESTINATION  0	/* Address positions in frame. */
+#define AX25_SOURCE       1	
+#define AX25_REPEATER_1   2
+#define AX25_REPEATER_2   3
+#define AX25_REPEATER_3   4
+#define AX25_REPEATER_4   5
+#define AX25_REPEATER_5   6
+#define AX25_REPEATER_6   7
+#define AX25_REPEATER_7   8
+#define AX25_REPEATER_8   9
+
+#define AX25_MAX_ADDR_LEN 12	/* In theory, you would expect the maximum length */
+				/* to be 6 letters, dash, 2 digits, and nul for a */
+				/* total of 10.  However, object labels can be 10 */
+				/* characters so throw in a couple extra bytes */
+				/* to be safe. */
+
+#define AX25_MIN_INFO_LEN 0	/* Previously 1 when considering only APRS. */
+				
+#define AX25_MAX_INFO_LEN 2048	/* Maximum size for APRS. */
+				/* AX.25 starts out with 256 as the default max */
+				/* length but the end stations can negotiate */
+				/* something different. */
+				/* version 0.8:  Change from 256 to 2028 to */
+				/* handle the larger paclen for Linux AX25. */
+
+				/* These don't include the 2 bytes for the */
+				/* HDLC frame FCS. */
+
+/* 
+ * Previously, for APRS only.
+ * #define AX25_MIN_PACKET_LEN ( 2 * 7 + 2 + AX25_MIN_INFO_LEN)
+ * #define AX25_MAX_PACKET_LEN ( AX25_MAX_ADDRS * 7 + 2 + AX25_MAX_INFO_LEN)
+ */
+
+/* The more general case. */
+/* An AX.25 frame can have a control byte and no protocol. */
+
+#define AX25_MIN_PACKET_LEN ( 2 * 7 + 1 )
+
+#define AX25_MAX_PACKET_LEN ( AX25_MAX_ADDRS * 7 + 2 + 3 + AX25_MAX_INFO_LEN)
+
+
+/*
+ * packet_t is a pointer to a packet object.
+ *
+ * The actual implementation is not visible outside ax25_pad.c.
+ */
+
+#define AX25_UI_FRAME 3		/* Control field value. */
+
+#define AX25_PID_NO_LAYER_3 0xf0		/* protocol ID used for APRS */
+#define AX25_PID_SEGMENTATION_FRAGMENT 0x08
+#define AX25_PID_ESCAPE_CHARACTER 0xff
+
+
+#ifdef AX25_PAD_C	/* Keep this hidden - implementation could change. */
+
+struct packet_s {
+
+	int magic1;		/* for error checking. */
+
+	int seq;		/* unique sequence number for debugging. */
+
+	double release_time;	/* Time stamp in format returned by dtime_now(). */
+				/* When to release from the SATgate mode delay queue. */
+
+#define MAGIC 0x41583235
+
+	struct packet_s *nextp;	/* Pointer to next in queue. */
+
+	int num_addr;		/* Number of addresses in frame. */
+				/* Range of AX25_MIN_ADDRS .. AX25_MAX_ADDRS for AX.25. */	
+				/* It will be 0 if it doesn't look like AX.25. */
+				/* -1 is used temporarily at allocation to mean */
+				/* not determined yet. */
+
+
+
+				/* 
+ 				 * The 7th octet of each address contains:
+			         *
+				 * Bits:   H  R  R  SSID  0
+				 *
+				 *   H 		for digipeaters set to 0 intially.
+				 *		Changed to 1 when position has been used.
+ 				 *
+				 *		for source & destination it is called
+				 *		command/response.  Normally both 1 for APRS.
+				 *		They should be opposites for connected mode.
+				 *
+				 *   R	R	Reserved.  Normally set to 1 1.
+				 *
+				 *   SSID	Substation ID.  Range of 0 - 15.
+				 *
+				 *   0		Usually 0 but 1 for last address.
+				 */
+
+
+#define SSID_H_MASK	0x80
+#define SSID_H_SHIFT	7
+
+#define SSID_RR_MASK	0x60
+#define SSID_RR_SHIFT	5
+
+#define SSID_SSID_MASK	0x1e
+#define SSID_SSID_SHIFT	1
+
+#define SSID_LAST_MASK	0x01
+
+
+	int frame_len;		/* Frame length without CRC. */
+
+	int modulo;		/* I & S frames have sequence numbers of either 3 bits (modulo 8) */
+				/* or 7 bits (modulo 128).  This is conveyed by either 1 or 2 */
+				/* control bytes.  Unfortunately, we can't determine this by looking */
+				/* at an isolated frame.  We need to know about the context.  If we */
+				/* are part of the conversation, we would know.  But if we are */
+				/* just listening to others, this would be more difficult to determine. */
+
+				/* For U frames:   	set to 0 - not applicable */
+				/* For I & S frames:	8 or 128 if known.  0 if unknown. */
+
+	unsigned char frame_data[AX25_MAX_PACKET_LEN+1];
+				/* Raw frame contents, without the CRC. */
+				
+
+	int magic2;		/* Will get stomped on if above overflows. */
+};
+
+
+
+
+#else			/* Public view. */
+
+struct packet_s {
+	int secret;
+};
+
+#endif
+
+
+typedef struct packet_s *packet_t;
+
+typedef enum cmdres_e { cr_00 = 2, cr_cmd = 1, cr_res = 0, cr_11 = 3 } cmdres_t;
+
+
+extern packet_t ax25_new (void);
+
+
+#ifdef AX25_PAD_C	/* Keep this hidden - implementation could change. */
+
+
+/*
+ * APRS always has one control octet of 0x03 but the more
+ * general AX.25 case is one or two control bytes depending on
+ * whether "modulo 128 operation" is in effect.
+ */
+
+//#define DEBUGX 1
+
+static inline int ax25_get_control_offset (packet_t this_p) 
+{
+	return (this_p->num_addr*7);
+}
+
+static inline int ax25_get_num_control (packet_t this_p)
+{
+	int c;
+
+	c = this_p->frame_data[ax25_get_control_offset(this_p)];
+
+	if ( (c & 0x01) == 0 ) {			/* I   xxxx xxx0 */
+#if DEBUGX
+	  dw_printf ("ax25_get_num_control, %02x is I frame, returns %d\n", c, (this_p->modulo == 128) ? 2 : 1);
+#endif
+	  return ((this_p->modulo == 128) ? 2 : 1);
+	}
+
+	if ( (c & 0x03) == 1 ) {			/* S   xxxx xx01 */
+#if DEBUGX
+	  dw_printf ("ax25_get_num_control, %02x is S frame, returns %d\n", c, (this_p->modulo == 128) ? 2 : 1);
+#endif
+	  return ((this_p->modulo == 128) ? 2 : 1);
+	}
+
+#if DEBUGX
+	dw_printf ("ax25_get_num_control, %02x is U frame, always returns 1.\n", c);
+#endif
+
+	return (1);					/* U   xxxx xx11 */
+}
+
+
+
+/*
+ * APRS always has one protocol octet of 0xF0 meaning no level 3
+ * protocol but the more general case is 0, 1 or 2 protocol ID octets.
+ */
+
+static inline int ax25_get_pid_offset (packet_t this_p) 
+{
+	return (ax25_get_control_offset (this_p) + ax25_get_num_control(this_p));
+}
+
+static int ax25_get_num_pid (packet_t this_p)
+{
+	int c;
+	int pid;
+
+	c = this_p->frame_data[ax25_get_control_offset(this_p)];
+
+	if ( (c & 0x01) == 0 ||				/* I   xxxx xxx0 */
+	     c == 0x03 || c == 0x13) {			/* UI  000x 0011 */
+
+	  pid = this_p->frame_data[ax25_get_pid_offset(this_p)];
+#if DEBUGX
+	  dw_printf ("ax25_get_num_pid, %02x is I or UI frame, pid = %02x, returns %d\n", c, pid, (pid==AX25_PID_ESCAPE_CHARACTER) ? 2 : 1);
+#endif
+	  if (pid == AX25_PID_ESCAPE_CHARACTER) {
+	    return (2);			/* pid 1111 1111 means another follows. */
+	  }
+	  return (1);		
+	}
+#if DEBUGX
+	dw_printf ("ax25_get_num_pid, %02x is neither I nor UI frame, returns 0\n", c);
+#endif
+	return (0);
+}
+
+
+/*
+ * AX.25 has info field for 5 frame types depending on the control field.
+ *
+ *	xxxx xxx0	I
+ *	000x 0011	UI		(which includes APRS)
+ *	101x 1111	XID
+ *	111x 0011	TEST
+ *	100x 0111	FRMR
+ *
+ * APRS always has an Information field with at least one octet for the Data Type Indicator.  
+ */
+
+static inline int ax25_get_info_offset (packet_t this_p) 
+{
+	int offset = ax25_get_control_offset (this_p) + ax25_get_num_control(this_p) + ax25_get_num_pid(this_p);
+#if DEBUGX
+	dw_printf ("ax25_get_info_offset, returns %d\n", offset);
+#endif
+	return (offset);
+}
+
+static inline int ax25_get_num_info (packet_t this_p)
+{
+	int len;
+	
+	/* assuming AX.25 frame. */
+
+	len = this_p->frame_len - this_p->num_addr * 7 - ax25_get_num_control(this_p) - ax25_get_num_pid(this_p);
+	if (len < 0) {
+	  len = 0;		/* print error? */
+	}
+
+	return (len);
+}
+
+#endif
+
+
+typedef enum ax25_modulo_e { modulo_unknown = 0, modulo_8 = 8, modulo_128 = 128 } ax25_modulo_t;
+
+typedef enum ax25_frame_type_e {
+
+	frame_type_I = 0,	// Information
+
+	frame_type_S_RR,	// Receive Ready - System Ready To Receive
+	frame_type_S_RNR,	// Receive Not Ready - TNC Buffer Full
+	frame_type_S_REJ,	// Reject Frame - Out of Sequence or Duplicate
+	frame_type_S_SREJ,	// Selective Reject - Request single frame repeat
+
+	frame_type_U_SABME,	// Set Async Balanced Mode, Extended
+	frame_type_U_SABM,	// Set Async Balanced Mode
+	frame_type_U_DISC,	// Disconnect
+	frame_type_U_DM,	// Disconnect Mode
+	frame_type_U_UA,	// Unnumbered Acknowledge
+	frame_type_U_FRMR,	// Frame Reject
+	frame_type_U_UI,	// Unnumbered Information
+	frame_type_U_XID,	// Exchange Identification
+	frame_type_U_TEST,	// Test
+	frame_type_U,		// other Unnumbered, not used by AX.25.
+
+	frame_not_AX25		// Could not get control byte from frame.
+				// This must be last because value plus 1 is
+				// for the size of an array.
+
+} ax25_frame_type_t;
+	
+
+/* 
+ * Originally this was a single number. 
+ * Let's try something new in version 1.2.
+ * Also collect AGC values from the mark and space filters.
+ */
+
+typedef struct alevel_s {
+
+	int rec;
+	int mark;
+	int space;
+	//float ms_ratio;	// TODO: take out after temporary investigation.
+} alevel_t;
+
+
+#ifndef AXTEST
+// TODO: remove this?
+#define AX25MEMDEBUG 0
+#endif
+
+
+#if AX25MEMDEBUG	// to investigate a memory leak problem
+
+
+extern void ax25memdebug_set(void);
+extern int ax25memdebug_get (void);
+extern int ax25memdebug_seq (packet_t this_p);
+
+
+extern packet_t ax25_from_text_debug (char *monitor, int strict, char *src_file, int src_line);
+#define ax25_from_text(m,s) ax25_from_text_debug(m,s,__FILE__,__LINE__)
+
+extern packet_t ax25_from_frame_debug (unsigned char *data, int len, alevel_t alevel, char *src_file, int src_line);
+#define ax25_from_frame(d,l,a) ax25_from_frame_debug(d,l,a,__FILE__,__LINE__);
+
+extern packet_t ax25_dup_debug (packet_t copy_from, char *src_file, int src_line);
+#define ax25_dup(p) ax25_dup_debug(p,__FILE__,__LINE__);
+
+extern void ax25_delete_debug (packet_t pp, char *src_file, int src_line);
+#define ax25_delete(p) ax25_delete_debug(p,__FILE__,__LINE__);
+
+#else
+
+extern packet_t ax25_from_text (char *monitor, int strict);
+
+extern packet_t ax25_from_frame (unsigned char *data, int len, alevel_t alevel);
+
+extern packet_t ax25_dup (packet_t copy_from);
+
+extern void ax25_delete (packet_t pp);
+
+#endif
+
+
+
+
+extern int ax25_parse_addr (int position, char *in_addr, int strict, char *out_addr, int *out_ssid, int *out_heard);
+extern int ax25_check_addresses (packet_t pp);
+
+extern packet_t ax25_unwrap_third_party (packet_t from_pp);
+
+extern void ax25_set_addr (packet_t pp, int, char *);
+extern void ax25_insert_addr (packet_t this_p, int n, char *ad);
+extern void ax25_remove_addr (packet_t this_p, int n);
+
+extern int ax25_get_num_addr (packet_t pp);
+extern int ax25_get_num_repeaters (packet_t this_p);
+
+extern void ax25_get_addr_with_ssid (packet_t pp, int n, char *station);
+extern void ax25_get_addr_no_ssid (packet_t pp, int n, char *station);
+
+extern int ax25_get_ssid (packet_t pp, int n);
+extern void ax25_set_ssid (packet_t this_p, int n, int ssid);
+
+extern int ax25_get_h (packet_t pp, int n);
+
+extern void ax25_set_h (packet_t pp, int n);
+
+extern int ax25_get_heard(packet_t this_p);
+
+extern int ax25_get_first_not_repeated(packet_t pp);
+
+extern int ax25_get_rr (packet_t this_p, int n);
+
+extern int ax25_get_info (packet_t pp, unsigned char **paddr);
+extern int ax25_cut_at_crlf (packet_t this_p);
+
+extern void ax25_set_nextp (packet_t this_p, packet_t next_p);
+
+extern int ax25_get_dti (packet_t this_p);
+
+extern packet_t ax25_get_nextp (packet_t this_p);
+
+extern void ax25_set_release_time (packet_t this_p, double release_time);
+extern double ax25_get_release_time (packet_t this_p);
+
+extern void ax25_set_modulo (packet_t this_p, int modulo);
+
+extern void ax25_format_addrs (packet_t pp, char *);
+extern void ax25_format_via_path (packet_t this_p, char *result, size_t result_size);
+
+extern int ax25_pack (packet_t pp, unsigned char result[AX25_MAX_PACKET_LEN]);
+
+extern ax25_frame_type_t ax25_frame_type (packet_t this_p, cmdres_t *cr, char *desc, int *pf, int *nr, int *ns); 
+
+extern void ax25_hex_dump (packet_t this_p);
+
+extern int ax25_is_aprs (packet_t pp);
+extern int ax25_is_null_frame (packet_t this_p);
+
+extern int ax25_get_control (packet_t this_p); 
+extern int ax25_get_c2 (packet_t this_p); 
+
+extern int ax25_get_pid (packet_t this_p);
+
+extern int ax25_get_frame_len (packet_t this_p);
+
+extern unsigned short ax25_dedupe_crc (packet_t pp);
+
+extern unsigned short ax25_m_m_crc (packet_t pp);
+
+extern void ax25_safe_print (char *, int, int ascii_only);
+
+#define AX25_ALEVEL_TO_TEXT_SIZE 32	// overkill but safe.
+extern int ax25_alevel_to_text (alevel_t alevel, char text[AX25_ALEVEL_TO_TEXT_SIZE]);
+
+
+#endif /* AX25_PAD_H */
+
+/* end ax25_pad.h */
+
+

+ 909 - 0
main/ax25_pad2.c

@@ -0,0 +1,909 @@
+//
+//    This file is part of Dire Wolf, an amateur radio packet TNC.
+//
+//    Copyright (C) 2016  John Langner, WB2OSZ
+//
+//    This program is free software: you can redistribute it and/or modify
+//    it under the terms of the GNU General Public License as published by
+//    the Free Software Foundation, either version 2 of the License, or
+//    (at your option) any later version.
+//
+//    This program is distributed in the hope that it will be useful,
+//    but WITHOUT ANY WARRANTY; without even the implied warranty of
+//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//    GNU General Public License for more details.
+//
+//    You should have received a copy of the GNU General Public License
+//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+//
+
+
+
+/*------------------------------------------------------------------
+ *
+ * Name:	ax25_pad2.c
+ *
+ * Purpose:	Packet assembler and disasembler, part 2.
+ *
+ * Description:	
+ *
+ *	The original ax25_pad.c was written with APRS in mind.
+ *	It handles UI frames and transparency for a KISS TNC.
+ *	Here we add new functions that can handle the
+ *	more general cases of AX.25 frames.
+ *
+ *
+ *	* Destination Address  (note: opposite order in printed format)
+ *
+ *	* Source Address
+ *
+ *	* 0-8 Digipeater Addresses
+ *				(The AX.25 v2.2 spec reduced this number to
+ *				a maximum of 2 but I allow the original 8.)
+ *
+ *	Each address is composed of:
+ *
+ *	* 6 upper case letters or digits, blank padded.
+ *		These are shifted left one bit, leaving the LSB always 0.
+ *
+ *	* a 7th octet containing the SSID and flags.
+ *		The LSB is always 0 except for the last octet of the address field.
+ *
+ *	The final octet of the Destination has the form:
+ *
+ *		C R R SSID 0, where,
+ *
+ *			C = command/response.   Set to 1 for command.
+ *			R R = Reserved = 1 1	(See RR note, below)
+ *			SSID = substation ID
+ *			0 = zero
+ *
+ *	The final octet of the Source has the form:
+ *
+ *		C R R SSID 0, where,
+ *
+ *			C = command/response.   Must be inverse of destination C bit.
+ *			R R = Reserved = 1 1	(See RR note, below)
+ *			SSID = substation ID
+ *			0 = zero (or 1 if no repeaters)
+ *
+ *	The final octet of each repeater has the form:
+ *
+ *		H R R SSID 0, where,
+ *
+ *			H = has-been-repeated = 0 initially.  
+ *				Set to 1 after this address has been used.
+ *			R R = Reserved = 1 1
+ *			SSID = substation ID
+ *			0 = zero (or 1 if last repeater in list)
+ *
+ *		A digipeater would repeat this frame if it finds its address
+ *		with the "H" bit set to 0 and all earlier repeater addresses
+ *		have the "H" bit set to 1.  
+ *		The "H" bit would be set to 1 in the repeated frame.
+ *
+ *	In standard monitoring format, an asterisk is displayed after the last
+ *	digipeater with the "H" bit set.  That indicates who you are hearing
+ *	over the radio.
+ *
+ *	
+ *	Next we have:
+ *
+ *	* One or two byte Control Field - A U frame always has one control byte.
+ *					When using modulo 128 sequence numbers, the
+ *					I and S frames can have a second byte allowing
+ *					7 bit fields instead of 3 bit fields.
+ *					Unfortunately, we can't tell which we have by looking
+ *					at a frame out of context.  :-(
+ *					If we are one end of the link, we would know this
+ *					from SABM/SABME and possible later negotiation
+ *					with XID.  But if we start monitoring two other
+ *					stations that are already conversing, we don't know.
+ *
+ *			RR note:	It seems that some implementations put a hint
+ *					in the "RR" reserved bits.
+ *					http://www.tapr.org/pipermail/ax25-layer2/2005-October/000297.html
+ *					The RR bits can also be used for "DAMA" which is
+ *					some sort of channel access coordination scheme.
+ *					http://internet.freepage.de/cgi-bin/feets/freepage_ext/41030x030A/rewrite/hennig/afu/afudoc/afudama.html
+ *					Neither is part of the official protocol spec.
+ *
+ *	* One byte Protocol ID 		- Only for I and UI frames.
+ *					Normally we would use 0xf0 for no layer 3.
+ *
+ *	Finally the Information Field. The initial max size is 256 but it 
+ *	can be negotiated higher if both ends agree.
+ *
+ *	Only these types of frames can have an information part:
+ *		- I
+ *		- UI
+ *		- XID
+ *		- TEST
+ *		- FRMR
+ *
+ *	The 2 byte CRC is not stored here. 
+ *
+ *
+ * Constructors:
+ *		ax25_u_frame		- Construct a U frame.
+ *		ax25_s_frame		- Construct a S frame.
+ *		ax25_i_frame		- Construct a I frame.
+ *
+ * Get methods:	....			???
+ *
+ *------------------------------------------------------------------*/
+
+#define AX25_PAD_C		/* this will affect behavior of ax25_pad.h */
+
+
+#include "direwolf.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <stdio.h>
+#include <ctype.h>
+
+
+//#include "textcolor.h"
+#include "ax25_pad.h"
+#include "ax25_pad2.h"
+
+
+
+extern int ax25memdebug;
+
+static int set_addrs (packet_t pp, char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr);
+
+//#if AX25MEMDEBUG
+//#undef AX25MEMDEBUG
+//#endif
+
+		
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_u_frame
+ * 
+ * Purpose:	Construct a U frame.
+ *
+ * Input:	addrs		- Array of addresses.
+ *	
+ *		num_addr	- Number of addresses, range 2 .. 10.
+ *
+ *		cr		- cr_cmd command frame, cr_res for a response frame.
+ *
+ *		ftype		- One of:
+ *				        frame_type_U_SABME     // Set Async Balanced Mode, Extended
+ *				        frame_type_U_SABM      // Set Async Balanced Mode
+ *				        frame_type_U_DISC      // Disconnect
+ *				        frame_type_U_DM        // Disconnect Mode
+ *				        frame_type_U_UA        // Unnumbered Acknowledge
+ *				        frame_type_U_FRMR      // Frame Reject
+ *				        frame_type_U_UI        // Unnumbered Information
+ *				        frame_type_U_XID       // Exchange Identification
+ *				        frame_type_U_TEST      // Test
+ *
+ *		pf		- Poll/Final flag.
+ *
+ *		pid		- Protocol ID.  >>> Used ONLY for the UI type. <<<
+ *				  Normally 0xf0 meaning no level 3.
+ *				  Could be other values for NET/ROM, etc.
+ *
+ *		pinfo		- Pointer to data for Info field.  Allowed only for UI, XID, TEST, FRMR.
+ *		
+ *		info_len	- Length for Info field.
+ *
+ *
+ * Returns:	Pointer to new packet object.
+ *
+ *------------------------------------------------------------------------------*/
+
+#if AX25MEMDEBUG
+packet_t ax25_u_frame_debug (char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr, ax25_frame_type_t ftype, int pf, int pid, unsigned char *pinfo, int info_len, char *src_file, int src_line)
+#else
+packet_t ax25_u_frame (char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr, ax25_frame_type_t ftype, int pf, int pid, unsigned char *pinfo, int info_len)
+#endif
+{
+	packet_t this_p;
+	unsigned char *p;
+	int ctrl = 0;
+	unsigned int t = 999;	// 1 = must be cmd, 0 = must be response, 2 = can be either.
+	int i = 0;		// Is Info part allowed?
+
+	this_p = ax25_new ();
+
+#if AX25MEMDEBUG	
+	if (ax25memdebug) {
+	  printf ("ax25_u_frame, seq=%d, called from %s %d\n", this_p->seq, src_file, src_line);
+	}
+#endif
+	
+	if (this_p == NULL) return (NULL);
+
+	this_p->modulo = 0;
+
+	if ( ! set_addrs (this_p, addrs, num_addr, cr)) {
+	  printf ("Internal error in %s: Could not set addresses for U frame.\n", __func__);
+	  ax25_delete (this_p);
+	  return (NULL);
+	}  
+
+	switch (ftype) {
+							// 1 = cmd only, 0 = res only, 2 = either
+	  case frame_type_U_SABME:	ctrl = 0x6f;	t = 1;		break;
+	  case frame_type_U_SABM:	ctrl = 0x2f;	t = 1;		break;
+	  case frame_type_U_DISC:	ctrl = 0x43;	t = 1;		break;
+	  case frame_type_U_DM:		ctrl = 0x0f;	t = 0;		break;
+	  case frame_type_U_UA:		ctrl = 0x63;	t = 0;		break;
+	  case frame_type_U_FRMR:	ctrl = 0x87;	t = 0;	i = 1;	break;
+	  case frame_type_U_UI:		ctrl = 0x03;	t = 2;	i = 1;	break;
+	  case frame_type_U_XID:	ctrl = 0xaf;	t = 2;	i = 1;	break;
+	  case frame_type_U_TEST:	ctrl = 0xe3;	t = 2;	i = 1;	break;
+
+	  default:
+	    printf ("Internal error in %s: Invalid ftype %d for U frame.\n", __func__, ftype);
+	    ax25_delete (this_p);
+	    return (NULL);
+	    break;
+	}
+	if (pf) ctrl |= 0x10;
+
+	if (t != 2) {
+	  if (cr != t) {
+	    printf ("Internal error in %s: U frame, cr is %d but must be %d. ftype=%d\n", __func__, cr, t, ftype);
+	  }
+	}
+
+	p = this_p->frame_data + this_p->frame_len;
+	*p++ = ctrl;	
+	this_p->frame_len++;
+
+	if (ftype == frame_type_U_UI) {
+
+	  // Definitely don't want pid value of 0 (not in valid list)
+	  // or 0xff (which means more bytes follow).
+
+	  if (pid < 0 || pid == 0 || pid == 0xff) {
+	    printf ("Internal error in %s: U frame, Invalid pid value 0x%02x.\n", __func__, pid);
+	    pid = AX25_PID_NO_LAYER_3;
+	  }
+	  *p++ = pid;
+	  this_p->frame_len++;
+	}
+
+	if (i) {
+	  if (pinfo != NULL && info_len > 0) {
+	    if (info_len > AX25_MAX_INFO_LEN) {
+	      printf ("Internal error in %s: U frame, Invalid information field length %d.\n", __func__, info_len);
+	      info_len = AX25_MAX_INFO_LEN;
+	    }
+	    memcpy (p, pinfo, info_len);
+	    p += info_len;
+	    this_p->frame_len += info_len;
+	  }
+	}
+	else {
+	  if (pinfo != NULL && info_len > 0) {
+	    printf ("Internal error in %s: Info part not allowed for U frame type.\n", __func__);
+	  }
+	}
+	*p = '\0';
+
+	assert (p == this_p->frame_data + this_p->frame_len);
+        assert (this_p->magic1 == MAGIC);
+        assert (this_p->magic2 == MAGIC);
+
+#if PAD2TEST
+	ax25_frame_type_t check_ftype;
+	cmdres_t check_cr;
+	char check_desc[80];
+	int check_pf;
+	int check_nr;
+	int check_ns;
+
+	check_ftype = ax25_frame_type (this_p, &check_cr, check_desc, &check_pf, &check_nr, &check_ns);
+
+	printf ("check: ftype=%d, desc=\"%s\", pf=%d\n", check_ftype, check_desc, check_pf);
+
+	assert (check_cr == cr);
+	assert (check_ftype == ftype);
+	assert (check_pf == pf);
+	assert (check_nr == -1);
+	assert (check_ns == -1);
+
+#endif
+
+	return (this_p);
+
+} /* end ax25_u_frame */
+
+
+
+
+
+
+		
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_s_frame
+ * 
+ * Purpose:	Construct an S frame.
+ *
+ * Input:	addrs		- Array of addresses.
+ *	
+ *		num_addr	- Number of addresses, range 2 .. 10.
+ *
+ *		cr		- cr_cmd command frame, cr_res for a response frame.
+ *
+ *		ftype		- One of:
+ *				        frame_type_S_RR,        // Receive Ready - System Ready To Receive
+ *				        frame_type_S_RNR,       // Receive Not Ready - TNC Buffer Full
+ *				        frame_type_S_REJ,       // Reject Frame - Out of Sequence or Duplicate
+ *				        frame_type_S_SREJ,      // Selective Reject - Request single frame repeat
+ *
+ *		modulo		- 8 or 128.  Determines if we have 1 or 2 control bytes.
+ *
+ *		nr		- N(R) field --- describe.
+ *
+ *		pf		- Poll/Final flag.
+ *
+ *		pinfo		- Pointer to data for Info field.  Allowed only for SREJ.
+ *
+ *		info_len	- Length for Info field.
+ *
+ *
+ * Returns:	Pointer to new packet object.
+ *
+ *------------------------------------------------------------------------------*/
+
+#if AX25MEMDEBUG
+packet_t ax25_s_frame_debug (char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr, ax25_frame_type_t ftype, int modulo, int nr, int pf, unsigned char *pinfo, int info_len, char *src_file, int src_line)
+#else
+packet_t ax25_s_frame (char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr, ax25_frame_type_t ftype, int modulo, int nr, int pf, unsigned char *pinfo, int info_len)
+#endif
+{
+	packet_t this_p;
+	unsigned char *p;
+	int ctrl = 0;
+
+	this_p = ax25_new ();
+
+#if AX25MEMDEBUG	
+	if (ax25memdebug) {
+	  printf ("ax25_s_frame, seq=%d, called from %s %d\n", this_p->seq, src_file, src_line);
+	}
+#endif
+	
+	if (this_p == NULL) return (NULL);
+
+	if ( ! set_addrs (this_p, addrs, num_addr, cr)) {
+	  printf ("Internal error in %s: Could not set addresses for S frame.\n", __func__);
+	  ax25_delete (this_p);
+	  return (NULL);
+	}  
+
+	if (modulo != 8 && modulo != 128) {
+	  printf ("Internal error in %s: Invalid modulo %d for S frame.\n", __func__, modulo);
+	  modulo = 8;
+	}
+	this_p->modulo = modulo;
+
+	if (nr < 0 || nr >= modulo) {
+	  printf ("Internal error in %s: Invalid N(R) %d for S frame.\n", __func__, nr);
+	  nr &= (modulo - 1);
+	}
+
+	// Erratum: The AX.25 spec is not clear about whether SREJ should be command, response, or both.
+	// The underlying X.25 spec clearly says it is reponse only.  Let's go with that.
+
+	if (ftype == frame_type_S_SREJ && cr != cr_res) {
+	  printf ("Internal error in %s: SREJ must be response.\n", __func__);
+	}
+
+	switch (ftype) {
+
+	  case frame_type_S_RR:		ctrl = 0x01;	break;
+	  case frame_type_S_RNR:	ctrl = 0x05;	break;
+	  case frame_type_S_REJ:	ctrl = 0x09;	break;
+	  case frame_type_S_SREJ:	ctrl = 0x0d;	break;
+
+	  default:
+	    printf ("Internal error in %s: Invalid ftype %d for S frame.\n", __func__, ftype);
+	    ax25_delete (this_p);
+	    return (NULL);
+	    break;
+	}
+
+	p = this_p->frame_data + this_p->frame_len;
+
+	if (modulo == 8) {
+	  if (pf) ctrl |= 0x10;
+	  ctrl |= nr << 5;
+	  *p++ = ctrl;	
+	  this_p->frame_len++;
+	}
+	else {
+	  *p++ = ctrl;	
+	  this_p->frame_len++;
+	  
+	  ctrl = pf & 1;
+	  ctrl |= nr << 1;
+	  *p++ = ctrl;	
+	  this_p->frame_len++;
+	}
+
+	if (ftype == frame_type_S_SREJ) {
+	  if (pinfo != NULL && info_len > 0) {
+	    if (info_len > AX25_MAX_INFO_LEN) {
+	      printf ("Internal error in %s: SREJ frame, Invalid information field length %d.\n", __func__, info_len);
+	      info_len = AX25_MAX_INFO_LEN;
+	    }
+	    memcpy (p, pinfo, info_len);
+	    p += info_len;
+	    this_p->frame_len += info_len;
+	  }
+	}
+	else {
+	  if (pinfo != NULL || info_len != 0) {
+	    printf ("Internal error in %s: Info part not allowed for RR, RNR, REJ frame.\n", __func__);
+	  }
+	}
+	*p = '\0';
+
+	assert (p == this_p->frame_data + this_p->frame_len);
+        assert (this_p->magic1 == MAGIC);
+        assert (this_p->magic2 == MAGIC);
+
+#if PAD2TEST
+
+	ax25_frame_type_t check_ftype;
+	cmdres_t check_cr;
+	char check_desc[80];
+	int check_pf;
+	int check_nr;
+	int check_ns;
+	
+	// todo modulo must be input.
+	check_ftype = ax25_frame_type (this_p, &check_cr, check_desc, &check_pf, &check_nr, &check_ns);
+
+	printf ("check: ftype=%d, desc=\"%s\", pf=%d, nr=%d\n", check_ftype, check_desc, check_pf, check_nr);
+
+	assert (check_cr == cr);
+	assert (check_ftype == ftype);
+	assert (check_pf == pf);
+	assert (check_nr == nr);
+	assert (check_ns == -1);
+
+#endif
+	return (this_p);
+
+} /* end ax25_s_frame */
+
+
+
+
+		
+/*------------------------------------------------------------------------------
+ *
+ * Name:	ax25_i_frame
+ * 
+ * Purpose:	Construct an I frame.
+ *
+ * Input:	addrs		- Array of addresses.
+ *	
+ *		num_addr	- Number of addresses, range 2 .. 10.
+ *
+ *		cr		- cr_cmd command frame, cr_res for a response frame.
+ *
+ *		modulo		- 8 or 128.
+ *
+ *		nr		- N(R) field --- describe.
+ *
+ *		ns		- N(S) field --- describe.
+ *-rw-r--r-- 1 curiousmuch curiousmuch    235 Feb  2 19:36 objects.mk
+ *
+ *		pf		- Poll/Final flag.
+ *
+ *		pid		- Protocol ID.  
+ *				  Normally 0xf0 meaning no level 3.
+ *				  Could be other values for NET/ROM, etc.
+ *
+ *		pinfo		- Pointer to data for Info field.  
+ *		
+ *		info_len	- Length for Info field.
+ *
+ *
+ * Returns:	Pointer to new packet object.
+ *
+ *------------------------------------------------------------------------------*/
+
+#if AX25MEMDEBUG
+packet_t ax25_i_frame_debug (char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr, int modulo, int nr, int ns, int pf, int pid, unsigned char *pinfo, int info_len, char *src_file, int src_line)
+#else
+packet_t ax25_i_frame (char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr, int modulo, int nr, int ns, int pf, int pid, unsigned char *pinfo, int info_len)
+#endif
+{
+	packet_t this_p;
+	unsigned char *p;
+	int ctrl = 0;
+
+	this_p = ax25_new ();
+
+#if AX25MEMDEBUG	
+	if (ax25memdebug) {
+	  printf ("ax25_i_frame, seq=%d, called from %s %d\n", this_p->seq, src_file, src_line);
+	}
+#endif
+	
+	if (this_p == NULL) return (NULL);
+
+	if ( ! set_addrs (this_p, addrs, num_addr, cr)) {
+	  printf ("Internal error in %s: Could not set addresses for I frame.\n", __func__);
+	  ax25_delete (this_p);
+	  return (NULL);
+	}  
+
+	if (modulo != 8 && modulo != 128) {
+	  printf ("Internal error in %s: Invalid modulo %d for I frame.\n", __func__, modulo);
+	  modulo = 8;
+	}
+	this_p->modulo = modulo;
+
+	if (nr < 0 || nr >= modulo) {
+	  printf ("Internal error in %s: Invalid N(R) %d for I frame.\n", __func__, nr);
+	  nr &= (modulo - 1);
+	}
+
+	if (ns < 0 || ns >= modulo) {
+	  printf ("Internal error in %s: Invalid N(S) %d for I frame.\n", __func__, ns);
+	  ns &= (modulo - 1);
+	}
+
+	p = this_p->frame_data + this_p->frame_len;
+
+	if (modulo == 8) {
+	  ctrl = (nr << 5) | (ns << 1);
+	  if (pf) ctrl |= 0x10;
+	  *p++ = ctrl;	
+	  this_p->frame_len++;
+	}
+	else {
+	  ctrl = ns << 1;
+	  *p++ = ctrl;	
+	  this_p->frame_len++;
+
+	  ctrl = nr << 1;
+	  if (pf) ctrl |= 0x01;
+	  *p++ = ctrl;	
+	  this_p->frame_len++;
+	}
+
+	// Definitely don't want pid value of 0 (not in valid list)
+	// or 0xff (which means more bytes follow).
+
+	if (pid < 0 || pid == 0 || pid == 0xff) {
+	  printf ("Warning: Client application provided invalid PID value, 0x%02x, for I frame.\n", pid);
+	  pid = AX25_PID_NO_LAYER_3;
+	}
+	*p++ = pid;
+	this_p->frame_len++;
+
+	if (pinfo != NULL && info_len > 0) {
+	  if (info_len > AX25_MAX_INFO_LEN) {
+	    printf ("Internal error in %s: I frame, Invalid information field length %d.\n", __func__, info_len);
+	    info_len = AX25_MAX_INFO_LEN;
+	  }
+	  memcpy (p, pinfo, info_len);
+	  p += info_len;
+	  this_p->frame_len += info_len;
+	}
+
+	*p = '\0';
+
+	assert (p == this_p->frame_data + this_p->frame_len);
+        assert (this_p->magic1 == MAGIC);
+        assert (this_p->magic2 == MAGIC);
+
+#if PAD2TEST
+
+	ax25_frame_type_t check_ftype;
+	cmdres_t check_cr;
+	char check_desc[80];
+	int check_pf;
+	int check_nr;
+	int check_ns;
+	unsigned char *check_pinfo;
+	int check_info_len;
+
+	check_ftype = ax25_frame_type (this_p, &check_cr, check_desc, &check_pf, &check_nr, &check_ns);
+
+	printf ("check: ftype=%d, desc=\"%s\", pf=%d, nr=%d, ns=%d\n", check_ftype, check_desc, check_pf, check_nr, check_ns);
+
+	check_info_len = ax25_get_info (this_p, &check_pinfo);
+
+	assert (check_cr == cr);
+	assert (check_ftype == frame_type_I);
+	assert (check_pf == pf);
+	assert (check_nr == nr);
+	assert (check_ns == ns);
+
+	assert (check_info_len == info_len);
+	assert (strcmp((char*)check_pinfo,(char*)pinfo) == 0);
+#endif
+
+	return (this_p);
+
+} /* end ax25_i_frame */
+
+
+
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	set_addrs
+ * 
+ * Purpose:	Set address fields
+ *
+ * Input:	pp		- Packet object.
+ *
+ *		addrs		- Array of addresses.  Same order as in frame.
+ *	
+ *		num_addr	- Number of addresses, range 2 .. 10.
+ *
+ *		cr		- cr_cmd command frame, cr_res for a response frame.
+ *
+ * Output:	pp->frame_data 	- 7 bytes for each address.
+ *
+ *		pp->frame_len	- num_addr * 7
+ *
+ *		p->num_addr	- num_addr
+ *
+ * Returns:	1 for success.  0 for failure.
+ *
+ *------------------------------------------------------------------------------*/
+
+
+static int set_addrs (packet_t pp, char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr)
+{
+	int n;
+
+	assert (pp->frame_len == 0);
+	assert (cr == cr_cmd || cr == cr_res);
+
+	if (num_addr < AX25_MIN_ADDRS || num_addr > AX25_MAX_ADDRS) {
+	  printf ("INTERNAL ERROR: %s %s %d, num_addr = %d\n", __FILE__, __func__, __LINE__, num_addr);
+	  return (0);
+	}
+
+	for (n = 0; n < num_addr; n++) {
+
+	  unsigned char *pa = pp->frame_data + n * 7;
+	  int ok;
+	  int strict = 1;
+	  char oaddr[AX25_MAX_ADDR_LEN];
+	  int ssid;
+	  int heard;
+	  int j;
+
+	  ok = ax25_parse_addr (n, addrs[n], strict, oaddr, &ssid, &heard);
+
+	  if (! ok) return (0);
+
+	  // Fill in address.
+
+	  memset (pa, ' ' << 1, 6);
+	  for (j = 0; oaddr[j]; j++) {
+	    pa[j] = oaddr[j] << 1;
+	  }
+	  pa += 6;
+
+	  // Fill in SSID.
+
+	  *pa = 0x60 | ((ssid & 0xf) << 1);
+
+	  // Command / response flag.
+
+	  switch (n) {
+	   case AX25_DESTINATION:
+	      if (cr == cr_cmd) *pa |= 0x80;
+	      break;
+	   case AX25_SOURCE:
+	      if (cr == cr_res) *pa |= 0x80;
+	      break;
+	   default:
+	    break;
+	  }
+
+	  // Is this the end of address field?
+
+	  if (n == num_addr - 1) {
+	    *pa |= 1;
+	  }
+
+	  pp->frame_len += 7;
+	}
+
+	pp->num_addr = num_addr;
+	return (1);
+
+} /* end set_addrs */
+
+
+
+
+/*------------------------------------------------------------------------------
+ *
+ * Name:	main
+ * 
+ * Purpose:	Quick unit test for this file.
+ *
+ * Description:	Generate a variety of frames.
+ *		Each function calls ax25_frame_type to verify results.
+ *
+ *		$ gcc -DPAD2TEST -DUSE_REGEX_STATIC -Iregex ax25_pad.c ax25_pad2.c fcs_calc.o textcolor.o regex.a misc.a
+ *
+ *------------------------------------------------------------------------------*/
+
+#define PAD2TEST 1
+
+#if PAD2TEST
+
+void test_ax25_pad2 (void)
+{
+	char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN];
+	int num_addr = 2;
+	cmdres_t cr;
+	ax25_frame_type_t ftype;
+	int pf = 0;
+	int pid = 0xf0;
+	int modulo;
+	int nr, ns;
+	unsigned char *pinfo = NULL;
+	int info_len = 0;
+	packet_t pp;
+
+	strcpy (addrs[0], "W2UB");
+	strcpy (addrs[1], "WB2OSZ-15");
+	num_addr = 2;
+
+/* U frame */
+
+	for (ftype = frame_type_U_SABME; ftype <= frame_type_U_TEST; ftype++) {
+
+	  for (pf = 0; pf <= 1; pf++) {
+
+ 	    int cmin=0, cmax=0;
+
+	    switch (ftype) {
+					// 0 = response, 1 = command
+	      case frame_type_U_SABME:	cmin = 1; cmax = 1; break;
+	      case frame_type_U_SABM:	cmin = 1; cmax = 1; break;
+	      case frame_type_U_DISC:	cmin = 1; cmax = 1; break;
+	      case frame_type_U_DM:	cmin = 0; cmax = 0; break;
+	      case frame_type_U_UA:	cmin = 0; cmax = 0; break;
+	      case frame_type_U_FRMR:	cmin = 0; cmax = 0; break;
+	      case frame_type_U_UI:	cmin = 0; cmax = 1; break;
+	      case frame_type_U_XID:	cmin = 0; cmax = 1; break;
+	      case frame_type_U_TEST:	cmin = 0; cmax = 1; break;
+	      default:			break;	// avoid compiler warning.		
+	    }
+	  
+	    for (cr = cmin; cr <= cmax; cr++) {
+
+	      printf ("\nConstruct U frame, cr=%d, ftype=%d, pid=0x%02x\n", cr, ftype, pid);
+
+	      pp = ax25_u_frame (addrs, num_addr, cr, ftype, pf, pid, pinfo, info_len);
+	      ax25_hex_dump (pp);
+	      ax25_delete (pp);
+	    }
+	  }
+	}
+
+	printf ("\n----------\n\n");
+
+/* S frame */
+
+	strcpy (addrs[2], "DIGI1-1");
+	num_addr = 3;
+
+	for (ftype = frame_type_S_RR; ftype <= frame_type_S_SREJ; ftype++) {
+
+	  for (pf = 0; pf <= 1; pf++) {
+
+	    modulo = 8;
+	    nr = modulo / 2 + 1;
+
+ 	    for (cr = 0; cr <= 1; cr++) {
+
+	      printf ("\nConstruct S frame, cmd=%d, ftype=%d, pid=0x%02x\n", cr, ftype, pid);
+
+	      pp = ax25_s_frame (addrs, num_addr, cr, ftype, modulo, nr, pf, NULL, 0);
+
+	      ax25_hex_dump (pp);
+	      ax25_delete (pp);
+	    }
+
+	    modulo = 128;
+	    nr = modulo / 2 + 1;
+
+ 	    for (cr = 0; cr <= 1; cr++) {
+
+	      printf ("\nConstruct S frame, cmd=%d, ftype=%d, pid=0x%02x\n", cr, ftype, pid);
+
+	      pp = ax25_s_frame (addrs, num_addr, cr, ftype, modulo, nr, pf, NULL, 0);
+
+	      ax25_hex_dump (pp);
+	      ax25_delete (pp);
+	    }
+	  }
+	}
+
+/* SREJ is only S frame which can have information part. */
+
+	static unsigned char srej_info[] = { 1<<1, 2<<1, 3<<1, 4<<1 };
+
+	ftype = frame_type_S_SREJ;
+	for (pf = 0; pf <= 1; pf++) {
+
+	  modulo = 128;
+	  nr = 127;
+	  cr = cr_res;
+
+	  printf ("\nConstruct Multi-SREJ S frame, cmd=%d, ftype=%d, pid=0x%02x\n", cr, ftype, pid);
+
+	  pp = ax25_s_frame (addrs, num_addr, cr, ftype, modulo, nr, pf, srej_info, (int)(sizeof(srej_info)));
+
+	  ax25_hex_dump (pp);
+	  ax25_delete (pp);
+	}
+
+	printf ("\n----------\n\n");
+
+/* I frame */
+
+	pinfo = (unsigned char*)"The rain in Spain stays mainly on the plain.";
+	info_len = strlen((char*)pinfo);
+
+	for (pf = 0; pf <= 1; pf++) {
+
+	  modulo = 8;
+	  nr = 0x55 & (modulo - 1);
+	  ns = 0xaa & (modulo - 1);
+
+ 	  for (cr = 0; cr <= 1; cr++) {
+
+	    printf ("\nConstruct I frame, cmd=%d, ftype=%d, pid=0x%02x\n", cr, ftype, pid);
+
+	    pp = ax25_i_frame (addrs, num_addr, cr, modulo, nr, ns, pf, pid, pinfo, info_len);
+
+	    ax25_hex_dump (pp);
+	    ax25_delete (pp);
+	  }
+
+	  modulo = 128;
+	  nr = 0x55 & (modulo - 1);
+	  ns = 0xaa & (modulo - 1);
+
+ 	  for (cr = 0; cr <= 1; cr++) {
+
+	    printf ("\nConstruct I frame, cmd=%d, ftype=%d, pid=0x%02x\n", cr, ftype, pid);
+
+	    pp = ax25_i_frame (addrs, num_addr, cr, modulo, nr, ns, pf, pid, pinfo, info_len);
+
+	    ax25_hex_dump (pp);
+	    ax25_delete (pp);
+	  }
+	}
+
+	printf ("\n----------\n\n");
+	printf ("\nSUCCESS!\n");
+
+	//exit (EXIT_SUCCESS);
+
+} /* end main */
+
+#endif
+
+
+/* end ax25_pad2.c */

+ 54 - 0
main/ax25_pad2.h

@@ -0,0 +1,54 @@
+/*-------------------------------------------------------------------
+ *
+ * Name:	ax25_pad2.h
+ *
+ * Purpose:	Header file for using ax25_pad2.c
+ *		ax25_pad dealt only with UI frames.
+ *		This adds a facility for the other types: U, s, I.
+ *
+ *------------------------------------------------------------------*/
+
+#ifndef AX25_PAD2_H
+#define AX25_PAD2_H 1
+
+#include "ax25_pad.h"
+
+#if AX25MEMDEBUG	// to investigate a memory leak problem
+
+
+
+packet_t ax25_u_frame_debug (char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr, ax25_frame_type_t ftype, int pf, int pid, unsigned char *pinfo, int info_len, char *src_file, int src_line);
+
+packet_t ax25_s_frame_debug (char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr, ax25_frame_type_t ftype, int modulo, int nr, int pf, unsigned char *pinfo, int info_len, char *src_file, int src_line);
+
+packet_t ax25_i_frame_debug (char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr, int modulo, int nr, int ns, int pf, int pid, unsigned char *pinfo, int info_len, char *src_file, int src_line);
+
+
+#define ax25_u_frame(a,n,c,f,p,q,i,l) ax25_u_frame_debug(a,n,c,f,p,q,i,l,__FILE__,__LINE__)
+
+#define ax25_s_frame(a,n,c,f,m,r,p,i,l) ax25_s_frame_debug(a,n,c,f,m,r,p,i,l,__FILE__,__LINE__)
+
+#define ax25_i_frame(a,n,c,m,r,s,p,q,i,l) ax25_i_frame_debug(a,n,c,m,r,s,p,q,i,l,__FILE__,__LINE__)
+
+
+#else
+
+packet_t ax25_u_frame (char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr, ax25_frame_type_t ftype, int pf, int pid, unsigned char *pinfo, int info_len);
+
+packet_t ax25_s_frame (char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr, ax25_frame_type_t ftype, int modulo, int nr, int pf, unsigned char *pinfo, int info_len);
+
+packet_t ax25_i_frame (char addrs[AX25_MAX_ADDRS][AX25_MAX_ADDR_LEN], int num_addr, cmdres_t cr, int modulo, int nr, int ns, int pf, int pid, unsigned char *pinfo, int info_len);
+
+void test_ax25_pad2(void);
+
+
+#endif
+
+
+
+
+#endif /* AX25_PAD2_H */
+
+/* end ax25_pad2.h */
+
+

+ 66 - 0
main/direwolf.h

@@ -0,0 +1,66 @@
+
+/* direwolf.h - Common stuff used many places. */
+
+// TODO:   include this file first before anything else in each .c file.
+
+
+#ifndef DIREWOLF_H
+#define DIREWOLF_H
+
+#include <stdio.h>
+	
+#define SLEEP_SEC(n) sleep(n)
+#define SLEEP_MS(n) usleep((n)*1000)
+
+#ifndef G_UNKNOWN
+#include "latlong.h"
+#endif
+
+/* Conversion Macros */
+#define DW_METERS_TO_FEET(x) ((x) == G_UNKNOWN ? G_UNKNOWN : (x) * 3.2808399)
+#define DW_FEET_TO_METERS(x) ((x) == G_UNKNOWN ? G_UNKNOWN : (x) * 0.3048)
+#define DW_KM_TO_MILES(x) ((x) == G_UNKNOWN ? G_UNKNOWN : (x) * 0.621371192)
+
+#define DW_KNOTS_TO_MPH(x) ((x) == G_UNKNOWN ? G_UNKNOWN : (x) * 1.15077945)
+#define DW_KNOTS_TO_METERS_PER_SEC(x) ((x) == G_UNKNOWN ? G_UNKNOWN : (x) * 0.51444444444)
+#define DW_MPH_TO_KNOTS(x) ((x) == G_UNKNOWN ? G_UNKNOWN : (x) * 0.868976)
+#define DW_MPH_TO_METERS_PER_SEC(x) ((x) == G_UNKNOWN ? G_UNKNOWN : (x) * 0.44704)
+
+#define DW_MBAR_TO_INHG(x) ((x) == G_UNKNOWN ? G_UNKNOWN : (x) * 0.0295333727)
+
+
+#define SOCK_SEND(s,data,size) send(s,data,size, MSG_NOSIGNAL)
+#define SOCK_RECV(s,data,size) recv(s,data,size,0)
+
+
+/* Platform differences for string functions. */
+
+// Don't recall why for everyone.
+char *strcasestr(const char *S, const char *FIND);
+
+// These prevent /usr/include/gps.h from providing its own definition.
+#define HAVE_STRLCAT 1
+#define HAVE_STRLCPY 1
+
+
+#define DEBUG_STRL 0
+
+#if DEBUG_STRL
+
+#define strlcpy(dst,src,siz) strlcpy_debug(dst,src,siz,__FILE__,__func__,__LINE__)
+#define strlcat(dst,src,siz) strlcat_debug(dst,src,siz,__FILE__,__func__,__LINE__)
+
+size_t strlcpy_debug(char *__restrict__ dst, const char *__restrict__ src, size_t siz, const char *file, const char *func, int line);
+size_t strlcat_debug(char *__restrict__ dst, const char *__restrict__ src, size_t siz, const char *file, const char *func, int line);
+
+#else
+
+#define strlcpy(dst,src,siz) strlcpy_debug(dst,src,siz)
+#define strlcat(dst,src,siz) strlcat_debug(dst,src,siz)
+
+size_t strlcpy_debug(char *__restrict__ dst, const char *__restrict__ src, size_t siz);
+size_t strlcat_debug(char *__restrict__ dst, const char *__restrict__ src, size_t siz);
+
+#endif  /* DEBUG_STRL */
+
+#endif   /* ifndef DIREWOLF_H */

+ 126 - 0
main/fcs_calc.c

@@ -0,0 +1,126 @@
+//
+//    This file is part of Dire Wolf, an amateur radio packet TNC.
+//
+//    Copyright (C) 2011  John Langner, WB2OSZ
+//
+//    This program is free software: you can redistribute it and/or modify
+//    it under the terms of the GNU General Public License as published by
+//    the Free Software Foundation, either version 2 of the License, or
+//    (at your option) any later version.
+//
+//    This program is distributed in the hope that it will be useful,
+//    but WITHOUT ANY WARRANTY; without even the implied warranty of
+//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//    GNU General Public License for more details.
+//
+//    You should have received a copy of the GNU General Public License
+//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+//
+
+
+#include "direwolf.h"
+
+#include <stdio.h>
+
+/*
+ * Calculate the FCS for an AX.25 frame.
+ */
+
+#include "fcs_calc.h"
+
+
+static const unsigned short ccitt_table[256] = {
+
+// from http://www.ietf.org/rfc/rfc1549.txt
+
+   0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
+   0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
+   0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
+   0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
+   0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
+   0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
+   0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
+   0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
+   0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
+   0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
+   0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
+   0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
+   0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
+   0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
+   0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
+   0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
+   0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
+   0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
+   0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
+   0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
+   0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
+   0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
+   0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
+   0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
+   0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
+   0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
+   0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
+   0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
+   0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
+   0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
+   0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
+   0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
+
+};
+
+
+/* 
+ * Use this for an AX.25 frame. 
+ */
+
+unsigned short fcs_calc (unsigned char *data, int len)
+{
+	unsigned short crc = 0xffff;
+	int j;
+
+	for (j=0; j<len; j++) {
+
+  	  crc = ((crc) >> 8) ^ ccitt_table[((crc) ^ data[j]) & 0xff];
+	}
+
+	return ( crc ^ 0xffff );
+}
+
+
+/*
+ * CRC is also used for duplicate checking for the digipeater and IGate.
+ * A packet is considered a duplicate if the source, destination, and
+ * information parts match.  In other words, we ignore the via path
+ * which changes along the way.
+ * Rather than keeping a variable length string we just keep a 16 bit
+ * CRC which takes less memory and processing to compare.
+ *
+ * This can result in occasional false matches.  If we had a random
+ * 16 bit number, there is a 1/65536 ( = 0.0015 % ) chance that it will
+ * match and we will drop something that should be passed along.
+ *
+ * Looking at it another way, there is a 0.9999847412109375 (out of 1)
+ * probability of doing the right thing.
+ */
+
+/* 
+ * This can be used when we want to calculate a single CRC over disjoint data.
+ *
+ * 	crc = crc16 (region1, sizeof(region1), 0xffff);
+ *	crc = crc16 (region2, sizeof(region2), crc);
+ *	crc = crc16 (region3, sizeof(region3), crc);
+ */
+
+unsigned short crc16 (unsigned char *data, int len, unsigned short seed)
+{
+	unsigned short crc = seed;
+	int j;
+
+	for (j=0; j<len; j++) {
+
+  	  crc = ((crc) >> 8) ^ ccitt_table[((crc) ^ data[j]) & 0xff];
+	}
+
+	return ( crc ^ 0xffff );
+}
+

+ 11 - 0
main/fcs_calc.h

@@ -0,0 +1,11 @@
+
+/* fcs_calc.h */
+
+
+unsigned short fcs_calc (unsigned char *data, int len);
+
+unsigned short crc16 (unsigned char *data, int len, unsigned short seed);
+
+/* end fcs_calc.h */
+
+

+ 1048 - 0
main/latlong.c

@@ -0,0 +1,1048 @@
+//
+//    This file is part of Dire Wolf, an amateur radio packet TNC.
+//
+//    Copyright (C) 2013, 2014, 2015  John Langner, WB2OSZ
+//
+//    This program is free software: you can redistribute it and/or modify
+//    it under the terms of the GNU General Public License as published by
+//    the Free Software Foundation, either version 2 of the License, or
+//    (at your option) any later version.
+//
+//    This program is distributed in the hope that it will be useful,
+//    but WITHOUT ANY WARRANTY; without even the implied warranty of
+//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//    GNU General Public License for more details.
+//
+//    You should have received a copy of the GNU General Public License
+//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+//
+
+
+/*------------------------------------------------------------------
+ *
+ * Module:      latlong.c
+ *
+ * Purpose:   	Various functions for dealing with latitude and longitude.
+ *		
+ * Description: Originally, these were scattered around in many places.
+ *		Over time they might all be gathered into one place
+ *		for consistency, reuse, and easier maintenance.
+ *
+ *---------------------------------------------------------------*/
+
+#include "direwolf.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <ctype.h>
+#include <time.h>
+#include <math.h>
+#include <assert.h>
+
+#include "latlong.h"
+//#include "textcolor.h"
+
+
+/*------------------------------------------------------------------
+ *
+ * Name:        latitude_to_str
+ *
+ * Purpose:     Convert numeric latitude to string for transmission.
+ *
+ * Inputs:      dlat		- Floating point degrees.
+ * 		ambiguity	- If 1, 2, 3, or 4, blank out that many trailing digits.
+ *
+ * Outputs:	slat		- String in format ddmm.mm[NS]
+ *				  Should always be exactly 8 characters + NUL.
+ *
+ * Returns:     None
+ *
+ * Idea for future:
+ *		Non zero ambiguity removes least significant digits without rounding.
+ *		Maybe we could use -1 and -2 to add extra digits using !DAO! as
+ *		documented in http://www.aprs.org/datum.txt
+ *
+ *		For example, -1 adds one more human readable digit.
+ *			lat minutes 12.345 would produce "12.34" and !W5 !
+ *
+ *		-2 would encode almost 2 digits in base 91.
+ *			lat minutes 10.0027 would produce "10.00" and !w: !
+ *
+ *----------------------------------------------------------------*/
+
+void latitude_to_str (double dlat, int ambiguity, char *slat)
+{
+	char hemi;	/* Hemisphere: N or S */
+	int ideg;	/* whole number of degrees. */
+	double dmin;	/* Minutes after removing degrees. */
+	char smin[8];	/* Minutes in format mm.mm */
+	
+	if (dlat < -90.) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf ("Latitude is less than -90.  Changing to -90.n");
+	  dlat = -90.;
+	}
+	if (dlat > 90.) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf ("Latitude is greater than 90.  Changing to 90.n");
+	  dlat = 90.;
+	}
+
+	if (dlat < 0) {
+	  dlat = (- dlat);
+	  hemi = 'S';
+	}
+	else {
+	  hemi = 'N';
+	}
+
+	ideg = (int)dlat;
+	dmin = (dlat - ideg) * 60.;
+
+	snprintf (smin, sizeof(smin), "%05.2f", dmin);
+	/* Due to roundoff, 59.9999 could come out as "60.00" */
+	if (smin[0] == '6') {
+	  smin[0] = '0';
+	  ideg++;
+	}
+
+	sprintf (slat, "%02d%s%c", ideg, smin, hemi);
+
+	if (ambiguity >= 1) {
+	  slat[6] = ' ';
+	  if (ambiguity >= 2) {
+	    slat[5] = ' ';
+	    if (ambiguity >= 3) {
+	      slat[3] = ' ';
+	      if (ambiguity >= 4) {
+	        slat[2] = ' ';
+	      }
+	    }
+	  }
+	}
+
+} /* end latitude_to_str */
+
+
+/*------------------------------------------------------------------
+ *
+ * Name:        longitude_to_str
+ *
+ * Purpose:     Convert numeric longitude to string for transmission.
+ *
+ * Inputs:      dlong		- Floating point degrees.
+ * 		ambiguity	- If 1, 2, 3, or 4, blank out that many trailing digits.
+ *
+ * Outputs:	slat		- String in format dddmm.mm[NS]
+ *				  Should always be exactly 9 characters + NUL.
+ *
+ * Returns:     None
+ *
+ *----------------------------------------------------------------*/
+
+void longitude_to_str (double dlong, int ambiguity, char *slong)
+{
+	char hemi;	/* Hemisphere: N or S */
+	int ideg;	/* whole number of degrees. */
+	double dmin;	/* Minutes after removing degrees. */
+	char smin[8];	/* Minutes in format mm.mm */
+	
+	if (dlong < -180.) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf ("Longitude is less than -180.  Changing to -180.n");
+	  dlong = -180.;
+	}
+	if (dlong > 180.) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf ("Longitude is greater than 180.  Changing to 180.n");
+	  dlong = 180.;
+	}
+
+	if (dlong < 0) {
+	  dlong = (- dlong);
+	  hemi = 'W';
+	}
+	else {
+	  hemi = 'E';
+	}
+
+	ideg = (int)dlong;
+	dmin = (dlong - ideg) * 60.;
+
+	snprintf (smin, sizeof(smin), "%05.2f", dmin);
+	/* Due to roundoff, 59.9999 could come out as "60.00" */
+	if (smin[0] == '6') {
+	  smin[0] = '0';
+	  ideg++;
+	}
+
+	sprintf (slong, "%03d%s%c", ideg, smin, hemi);
+/*
+ * The spec says position ambiguity in latitude also
+ * applies to longitude automatically.  
+ * Blanking longitude digits is not necessary but I do it
+ * because it makes things clearer.
+ */
+	if (ambiguity >= 1) {
+	  slong[7] = ' ';
+	  if (ambiguity >= 2) {
+	    slong[6] = ' ';
+	    if (ambiguity >= 3) {
+	      slong[4] = ' ';
+	      if (ambiguity >= 4) {
+	        slong[3] = ' ';
+	      }
+	    }
+	  }
+	}
+
+} /* end longitude_to_str */
+
+
+/*------------------------------------------------------------------
+ *
+ * Name:        latitude_to_comp_str
+ *
+ * Purpose:     Convert numeric latitude to compressed string for transmission.
+ *
+ * Inputs:      dlat		- Floating point degrees.
+ *
+ * Outputs:	slat		- String in format yyyy.
+ *				  Exactly 4 bytes, no nul terminator.
+ *
+ *----------------------------------------------------------------*/
+
+void latitude_to_comp_str (double dlat, char *clat)
+{
+	int y, y0, y1, y2, y3;
+
+	if (dlat < -90.) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf ("Latitude is less than -90.  Changing to -90.n");
+	  dlat = -90.;
+	}
+	if (dlat > 90.) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf ("Latitude is greater than 90.  Changing to 90.n");
+	  dlat = 90.;
+	}
+
+	y = (int)round(380926. * (90. - dlat));
+	
+	y0 = y / (91*91*91);
+	y -= y0 * (91*91*91);
+
+	y1 = y / (91*91);
+	y -= y1 * (91*91);
+
+	y2 = y / (91);
+	y -= y2 * (91);
+
+	y3 = y;
+
+	clat[0] = y0 + 33;
+	clat[1] = y1 + 33;
+	clat[2] = y2 + 33;
+	clat[3] = y3 + 33;
+}
+
+/*------------------------------------------------------------------
+ *
+ * Name:        longitude_to_comp_str
+ *
+ * Purpose:     Convert numeric longitude to compressed string for transmission.
+ *
+ * Inputs:      dlong		- Floating point degrees.
+ *
+ * Outputs:	slat		- String in format xxxx.
+ *				  Exactly 4 bytes, no nul terminator.
+ *
+ *----------------------------------------------------------------*/
+
+void longitude_to_comp_str (double dlong, char *clon)
+{
+	int x, x0, x1, x2, x3;
+
+	if (dlong < -180.) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf ("Longitude is less than -180.  Changing to -180.n");
+	  dlong = -180.;
+	}
+	if (dlong > 180.) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf ("Longitude is greater than 180.  Changing to 180.n");
+	  dlong = 180.;
+	}
+
+	x = (int)round(190463. * (180. + dlong));
+	
+	x0 = x / (91*91*91);
+	x -= x0 * (91*91*91);
+
+	x1 = x / (91*91);
+	x -= x1 * (91*91);
+
+	x2 = x / (91);
+	x -= x2 * (91);
+
+	x3 = x;
+
+	clon[0] = x0 + 33;
+	clon[1] = x1 + 33;
+	clon[2] = x2 + 33;
+	clon[3] = x3 + 33;
+}
+
+
+/*------------------------------------------------------------------
+ *
+ * Name:        latitude_to_nmea
+ *
+ * Purpose:     Convert numeric latitude to strings for NMEA sentence.
+ *
+ * Inputs:      dlat		- Floating point degrees.
+ *
+ * Outputs:	slat		- String in format ddmm.mmmm
+ *		hemi		- Hemisphere or empty string.
+ *
+ * Returns:     None
+ *
+ *----------------------------------------------------------------*/
+
+void latitude_to_nmea (double dlat, char *slat, char *hemi)
+{
+	int ideg;	/* whole number of degrees. */
+	double dmin;	/* Minutes after removing degrees. */
+	char smin[10];	/* Minutes in format mm.mmmm */
+	
+	if (dlat == G_UNKNOWN) {
+	  strcpy (slat, "");
+	  strcpy (hemi, "");
+	  return;
+	}
+
+	if (dlat < -90.) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf ("Latitude is less than -90.  Changing to -90.n");
+	  dlat = -90.;
+	}
+	if (dlat > 90.) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf ("Latitude is greater than 90.  Changing to 90.n");
+	  dlat = 90.;
+	}
+
+	if (dlat < 0) {
+	  dlat = (- dlat);
+	  strcpy (hemi, "S");
+	}
+	else {
+	  strcpy (hemi, "N");
+	}
+
+	ideg = (int)dlat;
+	dmin = (dlat - ideg) * 60.;
+
+	snprintf (smin, sizeof(smin), "%07.4f", dmin);
+	/* Due to roundoff, 59.99999 could come out as "60.0000" */
+	if (smin[0] == '6') {
+	  smin[0] = '0';
+	  ideg++;
+	}
+
+	sprintf (slat, "%02d%s", ideg, smin);
+
+} /* end latitude_to_str */
+
+
+/*------------------------------------------------------------------
+ *
+ * Name:        longitude_to_nmea
+ *
+ * Purpose:     Convert numeric longitude to strings for NMEA sentence.
+ *
+ * Inputs:      dlong		- Floating point degrees.
+ *
+ * Outputs:	slong		- String in format dddmm.mmmm
+ *		hemi		- Hemisphere or empty string.
+ *
+ * Returns:     None
+ *
+ *----------------------------------------------------------------*/
+
+void longitude_to_nmea (double dlong, char *slong, char *hemi)
+{
+	int ideg;	/* whole number of degrees. */
+	double dmin;	/* Minutes after removing degrees. */
+	char smin[10];	/* Minutes in format mm.mmmm */
+	
+	if (dlong == G_UNKNOWN) {
+	  strcpy (slong, "");
+	  strcpy (hemi, "");
+	  return;
+	}
+
+	if (dlong < -180.) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf ("longitude is less than -180.  Changing to -180.n");
+	  dlong = -180.;
+	}
+	if (dlong > 180.) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf ("longitude is greater than 180.  Changing to 180.n");
+	  dlong = 180.;
+	}
+
+	if (dlong < 0) {
+	  dlong = (- dlong);
+	  strcpy (hemi, "W");
+	}
+	else {
+	  strcpy (hemi, "E");
+	}
+
+	ideg = (int)dlong;
+	dmin = (dlong - ideg) * 60.;
+
+	snprintf (smin, sizeof(smin), "%07.4f", dmin);
+	/* Due to roundoff, 59.99999 could come out as "60.0000" */
+	if (smin[0] == '6') {
+	  smin[0] = '0';
+	  ideg++;
+	}
+
+	sprintf (slong, "%03d%s", ideg, smin);
+
+} /* end longitude_to_nmea */
+
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	latitude_from_nmea
+ *
+ * Purpose:	Convert NMEA latitude encoding to degrees.
+ *
+ * Inputs:	pstr 	- Pointer to numeric string.
+ *		phemi	- Pointer to following field.  Should be N or S.
+ *
+ * Returns:	Double precision value in degrees.  Negative for South.
+ *
+ * Description:	Latitude field has
+ *			2 digits for degrees
+ *			2 digits for minutes
+ *			period
+ *			Variable number of fractional digits for minutes.
+ *			I've seen 2, 3, and 4 fractional digits.
+ *
+ *
+ * Bugs:	Very little validation of data.
+ *
+ * Errors:	Return constant G_UNKNOWN for any type of error.
+ *
+ *------------------------------------------------------------------*/
+
+
+double latitude_from_nmea (char *pstr, char *phemi)
+{
+
+	double lat;
+
+	if ( ! isdigit((uint)(pstr[0]))) return (G_UNKNOWN);
+
+	if (pstr[4] != '.') return (G_UNKNOWN);
+
+
+	lat = (pstr[0] - '0') * 10 + (pstr[1] - '0') + atof(pstr+2) / 60.0;
+
+	if (lat < 0 || lat > 90) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf("Error: Latitude not in range of 0 to 90.\n");
+	}
+
+	// Saw this one time:
+	//	$GPRMC,000000,V,0000.0000,0,00000.0000,0,000,000,000000,,*01
+
+	// If location is unknown, I think the hemisphere should be
+	// an empty string.  TODO: Check on this.
+	// 'V' means void, so sentence should be discarded rather than
+	// trying to extract any data from it.
+
+	if (*phemi != 'N' && *phemi != 'S' && *phemi != '\0') {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf("Error: Latitude hemisphere should be N or S.\n");
+	}
+
+	if (*phemi == 'S') lat = ( - lat);
+
+	return (lat);
+}
+
+
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	longitude_from_nmea
+ *
+ * Purpose:	Convert NMEA longitude encoding to degrees.
+ *
+ * Inputs:	pstr 	- Pointer to numeric string.
+ *		phemi	- Pointer to following field.  Should be E or W.
+ *
+ * Returns:	Double precision value in degrees.  Negative for West.
+ *
+ * Description:	Longitude field has
+ *			3 digits for degrees
+ *			2 digits for minutes
+ *			period
+ *			Variable number of fractional digits for minutes
+ *
+ *
+ * Bugs:	Very little validation of data.
+ *
+ * Errors:	Return constant G_UNKNOWN for any type of error.
+ *
+ *------------------------------------------------------------------*/
+
+
+double longitude_from_nmea (char *pstr, char *phemi)
+{
+	double lon;
+
+	if ( ! isdigit((uint)(pstr[0]))) return (G_UNKNOWN);
+
+	if (pstr[5] != '.') return (G_UNKNOWN);
+
+	lon = (pstr[0] - '0') * 100 + (pstr[1] - '0') * 10 + (pstr[2] - '0') + atof(pstr+3) / 60.0;
+
+	if (lon < 0 || lon > 180) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf("Error: Longitude not in range of 0 to 180.\n");
+	}
+	
+	if (*phemi != 'E' && *phemi != 'W' && *phemi != '\0') {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf("Error: Longitude hemisphere should be E or W.\n");
+	}
+
+	if (*phemi == 'W') lon = ( - lon);
+
+	return (lon);
+}
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ll_distance_km
+ *
+ * Purpose:	Calculate distance between two locations.
+ *
+ * Inputs:	lat1, lon1	- One location, in degrees.
+ *		lat2, lon2	- other location
+ *
+ * Returns:	Distance in km.
+ *
+ * Description:	The Ubiquitous Haversine formula.
+ *
+ *------------------------------------------------------------------*/
+
+#define R 6371
+
+double ll_distance_km (double lat1, double lon1, double lat2, double lon2)
+{
+	double a;
+
+	lat1 *= M_PI / 180;
+	lon1 *= M_PI / 180;	
+	lat2 *= M_PI / 180;	
+	lon2 *= M_PI / 180;	
+	
+	a = pow(sin((lat2-lat1)/2),2) + cos(lat1) * cos(lat2) * pow(sin((lon2-lon1)/2),2);
+
+	return (R * 2 *atan2(sqrt(a), sqrt(1-a)));
+}
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ll_bearing_deg
+ *
+ * Purpose:	Calculate bearing between two locations.
+ *
+ * Inputs:	lat1, lon1	- starting location, in degrees.
+ *		lat2, lon2	- destination location
+ *
+ * Returns:	Initial Bearing, in degrees.
+ *		The calculation produces Range +- 180 degrees.
+ *		But I think that 0 - 360 would be more customary?
+ *
+ *------------------------------------------------------------------*/
+
+double ll_bearing_deg (double lat1, double lon1, double lat2, double lon2)
+{
+	double b;
+
+	lat1 *= M_PI / 180;
+	lon1 *= M_PI / 180;
+	lat2 *= M_PI / 180;
+	lon2 *= M_PI / 180;
+
+	b = atan2 (sin(lon2-lon1) * cos(lat2),
+		cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(lon2-lon1));
+
+	b *= 180 / M_PI;
+	if (b < 0) b += 360;
+
+	return (b);
+}
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ll_dest_lat
+ *		ll_dest_lon
+ *
+ * Purpose:	Calculate the destination location given a starting point,
+ *		distance, and bearing,
+ *
+ * Inputs:	lat1, lon1	- starting location, in degrees.
+ *		dist		- distance in km.
+ *		bearing		- direction in degrees.  Shouldn't matter
+ *				  if it is in +- 180 or 0 to 360 range.
+ *
+ * Returns:	New latitude or longitude.
+ *
+ *------------------------------------------------------------------*/
+
+double ll_dest_lat (double lat1, double lon1, double dist, double bearing)
+{
+	double lat2;
+
+	lat1 *= M_PI / 180;	// Everything to radians.
+	lon1 *= M_PI / 180;
+	bearing *= M_PI / 180;
+
+	lat2 = asin(sin(lat1) * cos(dist/R) + cos(lat1) * sin(dist/R) * cos(bearing));
+
+	lat2 *= 180 / M_PI;	// Back to degrees.
+
+	return (lat2);
+}
+
+double ll_dest_lon (double lat1, double lon1, double dist, double bearing)
+{
+	double lon2;
+	double lat2;
+
+	lat1 *= M_PI / 180;	// Everything to radians.
+	lon1 *= M_PI / 180;
+	bearing *= M_PI / 180;
+
+	lat2 = asin(sin(lat1) * cos(dist/R) + cos(lat1) * sin(dist/R) * cos(bearing));
+
+	lon2 = lon1 + atan2(sin(bearing) * sin(dist/R) * cos(lat1), cos(dist/R) - sin(lat1) * sin(lat2));
+
+	lon2 *= 180 / M_PI;	// Back to degrees.
+
+	return (lon2);
+}
+
+
+
+/*------------------------------------------------------------------
+ *
+ * Function:	ll_from_grid_square
+ *
+ * Purpose:	Convert Maidenhead locator to latitude and longitude.
+ *
+ * Inputs:	maidenhead	- 2, 4, 6, 8, 10, or 12 character grid square locator.
+ *
+ * Outputs:	dlat, dlon	- Latitude and longitude.  
+ *				  Original values unchanged if error.
+ *
+ * Returns:	1 for success, 0 if error.
+ *
+ * Reference:	A good converter for spot checking.  Only handles 4 or 6 characters :-(
+ *		http://home.arcor.de/waldemar.kebsch/The_Makrothen_Contest/fmaidenhead.html
+ *
+ * Rambling:	What sort of resolution does this provide?
+ *		For 8 character form, each latitude unit is 0.25 minute.
+ *		(Longitude can be up to twice that around the equator.)
+ *		6371 km * 2 * pi * 0.25 / 60 / 360 = 0.463 km.  Is that right?
+ *
+ *		Using this calculator, http://www.earthpoint.us/Convert.aspx
+ *		It gives lower left corner of square rather than the middle.  :-(
+ *
+ *		FN42MA00  -->  19T 334361mE 4651711mN
+ *		FN42MA11  -->  19T 335062mE 4652157mN
+ *				   ------   -------
+ *				      701       446    meters difference.
+ *
+ *		With another two pairs, we are down around 2 meters for latitude.
+ *
+ *------------------------------------------------------------------*/
+
+#define MH_MIN_PAIR 1
+#define MH_MAX_PAIR 6
+#define MH_UNITS ( 18 * 10 * 24 * 10 * 24 * 10 * 2 )
+
+static const struct {
+	char *position;
+	char min_ch;
+	char max_ch;
+	int value;
+} mh_pair[MH_MAX_PAIR] = {
+	{ "first",    'A', 'R',  10 * 24 * 10 * 24 * 10 * 2 },
+	{ "second",   '0', '9',       24 * 10 * 24 * 10 * 2 },
+	{ "third",    'A', 'X',            10 * 24 * 10 * 2 },
+	{ "fourth",   '0', '9',                 24 * 10 * 2 },
+	{ "fifth",    'A', 'X',                      10 * 2 },
+	{ "sixth",    '0', '9',                           2 } };  // Even so we can get center of square.
+
+
+
+#if 1
+
+int ll_from_grid_square (char *maidenhead, double *dlat, double *dlon)
+{
+	char mh[16];			/* Local copy, changed to upper case. */
+	int ilat = 0, ilon = 0;		/* In units in table above. */
+	char *p;
+	int n;
+
+	int np = strlen(maidenhead) / 2;	/* Number of pairs of characters. */
+
+	if (strlen(maidenhead) %2 != 0 || np < MH_MIN_PAIR || np > MH_MAX_PAIR) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf("Maidenhead locator \"%s\" must from 1 to %d pairs of characters.\n", maidenhead, MH_MAX_PAIR);
+	  return (0);
+	}
+
+	strlcpy (mh, maidenhead, sizeof(mh));
+	for (p = mh; *p != '\0'; p++) {
+	  if (islower((uint)*p)) *p = toupper((uint)*p);
+	}
+
+	for (n = 0; n < np; n++) {
+
+	  if (mh[2*n]   < mh_pair[n].min_ch || mh[2*n]   > mh_pair[n].max_ch || 
+	      mh[2*n+1] < mh_pair[n].min_ch || mh[2*n+1] > mh_pair[n].max_ch) {
+	    //text_color_set(DW_COLOR_ERROR);
+	    printf("The %s pair of characters in Maidenhead locator \"%s\" must be in range of %c thru %c.\n",
+			mh_pair[n].position, maidenhead, mh_pair[n].min_ch, mh_pair[n].max_ch);
+	    return (0);
+	  }
+
+	  ilon +=  ( mh[2*n]   - mh_pair[n].min_ch ) * mh_pair[n].value;
+	  ilat +=  ( mh[2*n+1] - mh_pair[n].min_ch ) * mh_pair[n].value;
+
+	  if (n == np-1) {	// If last pair, take center of square.
+	    ilon += mh_pair[n].value / 2;
+	    ilat += mh_pair[n].value / 2;
+	  }
+	}
+
+	*dlat = (double)ilat / MH_UNITS * 180. - 90.;
+	*dlon = (double)ilon / MH_UNITS * 360. - 180.;
+
+	////text_color_set(DW_COLOR_DEBUG);
+	//printf("DEBUG: Maidenhead conversion \"%s\" -> %.6f %.6f\n", maidenhead, *dlat, *dlon);
+
+	return (1);
+}
+#else
+
+int ll_from_grid_square (char *maidenhead, double *dlat, double *dlon)
+{
+	double lat, lon;
+	char mh[16];
+
+
+	if (strlen(maidenhead) != 2 &&  strlen(maidenhead) != 4 &&  strlen(maidenhead) != 6 &&  strlen(maidenhead) != 8) {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf("Maidenhead locator \"%s\" must 2, 4, 6, or 8 characters.\n", maidenhead);
+	  return (0);
+	}
+
+	strcpy (mh, maidenhead);
+	if (islower((uint)mh[0])) mh[0] = toupper((uint)mh[0]);
+	if (islower((uint)mh[1])) mh[1] = toupper((uint)mh[1]);
+	
+	if (mh[0] < 'A' || mh[0] > 'R' || mh[1] < 'A' || mh[1] > 'R') {
+	  //text_color_set(DW_COLOR_ERROR);
+	  printf("The first pair of characters in Maidenhead locator \"%s\" must be in range of A thru R.\n", maidenhead);
+	  return (0);
+	}
+
+
+	/* Lon:  360 deg / 18 squares = 20 deg / square */
+	/* Lat:  180 deg / 18 squares = 10 deg / square */
+
+	lon = (mh[0] - 'A') * 20 - 180;
+	lat = (mh[1] - 'A') * 10 - 90;
+
+	if (strlen(mh) >= 4) {
+
+	  if ( ! isdigit((uint)mh[2]) || ! isdigit((uint)mh[3]) ) {
+	    //text_color_set(DW_COLOR_ERROR);
+	    printf("The second pair of characters in Maidenhead locator \"%s\" must be digits.\n", maidenhead);
+	    return (0);
+	  }
+
+	  /* Lon:  20 deg / 10 squares = 2 deg / square */
+	  /* Lat:  10 deg / 10 squares = 1 deg / square */
+
+	  lon += (mh[2] - '0') * 2;
+	  lat += (mh[3] - '0');
+
+
+	  if (strlen(mh) >=6) {
+
+	    if (islower((uint)mh[4])) mh[4] = toupper((uint)mh[4]);
+	    if (islower((uint)mh[5])) mh[5] = toupper((uint)mh[5]);
+
+	    if (mh[4] < 'A' || mh[4] > 'X' || mh[5] < 'A' || mh[5] > 'X') {
+	      //text_color_set(DW_COLOR_ERROR);
+	      printf("The third pair of characters in Maidenhead locator \"%s\" must be in range of A thru X.\n", maidenhead);
+	      return (0);
+	    }
+
+	    /* Lon:  2 deg / 24 squares = 5 minutes / square */
+	    /* Lat:  1 deg / 24 squares = 2.5 minutes / square */
+
+	    lon += (mh[4] - 'A') * 5.0 / 60.0;
+	    lat += (mh[5] - 'A') * 2.5 / 60.0;
+
+	    if (strlen(mh) >= 8) {
+
+	      if ( ! isdigit((uint)mh[6]) || ! isdigit((uint)mh[7]) ) {
+	        //text_color_set(DW_COLOR_ERROR);
+	        printf("The fourth pair of characters in Maidenhead locator \"%s\" must be digits.\n", maidenhead);
+	        return (0);
+	      }
+
+	      /* Lon:  5   min / 10 squares = 0.5 minutes / square */
+	      /* Lat:  2.5 min / 10 squares = 0.25 minutes / square */
+
+	      lon += (mh[6] - '0') * 0.50 / 60.0;
+	      lat += (mh[7] - '0') * 0.25 / 60.0;
+
+	      lon += 0.250 / 60.0;	/* Move from corner to center of square */
+	      lat += 0.125 / 60.0;
+	    }
+	    else {
+	      lon += 2.5  / 60.0;	/* Move from corner to center of square */
+	      lat += 1.25 / 60.0;
+	    }
+	  }
+	  else {
+	    lon += 1.0;	/* Move from corner to center of square */
+	    lat += 0.5;
+	  }
+	}
+	else {
+	  lon += 10;	/* Move from corner to center of square */
+	  lat += 5;
+	}
+
+ 	////text_color_set(DW_COLOR_DEBUG);
+	//printf("DEBUG: Maidenhead conversion \"%s\" -> %.6f %.6f\n", maidenhead, lat, lon);
+
+	*dlat = lat;
+	*dlon = lon;
+
+	return (1);
+}
+
+#endif
+
+/* end ll_from_grid_square */
+
+
+#if LLTEST
+
+/* gcc -o lltest -DLLTEST latlong.c textcolor.o misc.a && lltest */
+
+
+int main (int argc, char *argv[])
+{
+	char result[20];
+	int errors = 0;
+	int ok;
+	double dlat, dlon;
+	double d, b;
+
+/* Latitude to APRS format. */
+
+	latitude_to_str (45.25, 0, result);
+	if (strcmp(result, "4515.00N") != 0) { errors++; printf ("Error 1.1: Did not expect \"%s\"\n", result); }
+
+	latitude_to_str (-45.25, 0, result);
+	if (strcmp(result, "4515.00S") != 0) { errors++; printf ("Error 1.2: Did not expect \"%s\"\n", result); }
+
+
+	latitude_to_str (45.999830, 0, result);
+	if (strcmp(result, "4559.99N") != 0) { errors++; printf ("Error 1.3: Did not expect \"%s\"\n", result); }
+
+	latitude_to_str (45.99999, 0, result);
+	if (strcmp(result, "4600.00N") != 0) { errors++; printf ("Error 1.4: Did not expect \"%s\"\n", result); }
+
+
+	latitude_to_str (45.999830, 1, result);
+	if (strcmp(result, "4559.9 N") != 0) { errors++; printf ("Error 1.5: Did not expect \"%s\"\n", result); }
+
+	latitude_to_str (45.999830, 2, result);
+	if (strcmp(result, "4559.  N") != 0) { errors++; printf ("Error 1.6: Did not expect \"%s\"\n", result); }
+
+	latitude_to_str (45.999830, 3, result);
+	if (strcmp(result, "455 .  N") != 0) { errors++; printf ("Error 1.7: Did not expect \"%s\"\n", result); }
+
+	latitude_to_str (45.999830, 4, result);
+	if (strcmp(result, "45  .  N") != 0) { errors++; printf ("Error 1.8: Did not expect \"%s\"\n", result); }
+
+/* Longitude to APRS format. */
+
+	longitude_to_str (45.25, 0, result);
+	if (strcmp(result, "04515.00E") != 0) { errors++; printf ("Error 2.1: Did not expect \"%s\"\n", result); }
+
+	longitude_to_str (-45.25, 0, result);
+	if (strcmp(result, "04515.00W") != 0) { errors++; printf ("Error 2.2: Did not expect \"%s\"\n", result); }
+
+
+	longitude_to_str (45.999830, 0, result);
+	if (strcmp(result, "04559.99E") != 0) { errors++; printf ("Error 2.3: Did not expect \"%s\"\n", result); }
+
+	longitude_to_str (45.99999, 0, result);
+	if (strcmp(result, "04600.00E") != 0) { errors++; printf ("Error 2.4: Did not expect \"%s\"\n", result); }
+
+
+	longitude_to_str (45.999830, 1, result);
+	if (strcmp(result, "04559.9 E") != 0) { errors++; printf ("Error 2.5: Did not expect \"%s\"\n", result); }
+
+	longitude_to_str (45.999830, 2, result);
+	if (strcmp(result, "04559.  E") != 0) { errors++; printf ("Error 2.6: Did not expect \"%s\"\n", result); }
+
+	longitude_to_str (45.999830, 3, result);
+	if (strcmp(result, "0455 .  E") != 0) { errors++; printf ("Error 2.7: Did not expect \"%s\"\n", result); }
+
+	longitude_to_str (45.999830, 4, result);
+	if (strcmp(result, "045  .  E") != 0) { errors++; printf ("Error 2.8: Did not expect \"%s\"\n", result); }
+
+/* Compressed format. */
+/* Protocol spec example has <*e7 but I got <*e8 due to rounding rather than truncation to integer. */
+
+	memset(result, 0, sizeof(result));
+
+	latitude_to_comp_str (-90.0, result);
+	if (strcmp(result, "{{!!") != 0) { errors++; printf ("Error 3.1: Did not expect \"%s\"\n", result); }
+
+	latitude_to_comp_str (49.5, result);
+	if (strcmp(result, "5L!!") != 0) { errors++; printf ("Error 3.2: Did not expect \"%s\"\n", result); }
+
+	latitude_to_comp_str (90.0, result);
+	if (strcmp(result, "!!!!") != 0) { errors++; printf ("Error 3.3: Did not expect \"%s\"\n", result); }
+
+
+	longitude_to_comp_str (-180.0, result);
+	if (strcmp(result, "!!!!") != 0) { errors++; printf ("Error 3.4: Did not expect \"%s\"\n", result); }
+
+	longitude_to_comp_str (-72.75, result);
+	if (strcmp(result, "<*e8") != 0) { errors++; printf ("Error 3.5: Did not expect \"%s\"\n", result); }
+
+	longitude_to_comp_str (180.0, result);
+	if (strcmp(result, "{{!!") != 0) { errors++; printf ("Error 3.6: Did not expect \"%s\"\n", result); }
+
+// to be continued for others...  NMEA...
+
+
+/* Distance & bearing - Take a couple examples from other places and see if we get similar results. */
+
+	// http://www.movable-type.co.uk/scripts/latlong.html
+
+	d = ll_distance_km (35., 45., 35., 135.);
+	b = ll_bearing_deg (35., 45., 35., 135.);
+
+	if (d < 7862 || d > 7882) { errors++; printf ("Error 5.1: Did not expect distance %.1f\n", d); }
+
+	if (b < 59.7 || b > 60.3) { errors++; printf ("Error 5.2: Did not expect bearing %.1f\n", b); }
+
+	// Sydney to Kinsale.  https://woodshole.er.usgs.gov/staffpages/cpolloni/manitou/ccal.htm
+
+	d = ll_distance_km (-33.8688, 151.2093, 51.7059, -8.5222);
+	b = ll_bearing_deg (-33.8688, 151.2093, 51.7059, -8.5222);
+
+	if (d < 17435 || d > 17455) { errors++; printf ("Error 5.3: Did not expect distance %.1f\n", d); }
+
+	if (b < 327-1 || b > 327+1) { errors++; printf ("Error 5.4: Did not expect bearing %.1f\n", b); }
+
+
+/*
+ * More distance and bearing.
+ * Here we will start at some location1 (lat1,lon1) and go some distance (d1) at some bearing (b1).
+ * This results in a new location2 (lat2, lon2).
+ * We then calculate the distance and bearing from location1 to location2 and compare with the intention.
+ */
+	int lat1, lon1, d1 = 10, b1;
+	double lat2, lon2, d2, b2;
+
+	for (lat1 = -60; lat1 <= 60; lat1 += 30) {
+	  for (lon1 = -180; lon1 <= 180; lon1 +=30) {
+	    for (b1 = 0; b1 < 360; b1 += 15) {
+
+	      lat2 = ll_dest_lat ((double)lat1, (double)lon1, (double)d1, (double)b1);
+	      lon2 = ll_dest_lon ((double)lat1, (double)lon1, (double)d1, (double)b1);
+
+	      d2 = ll_distance_km ((double)lat1, (double)lon1, lat2, lon2);
+	      b2 = ll_bearing_deg ((double)lat1, (double)lon1, lat2, lon2);
+	      if (b2 > 359.9 && b2 < 360.1) b2 = 0;
+
+	      // must be within 0.1% of distance and 0.1 degree.
+	      if (d2 < 0.999 * d1 || d2 > 1.001 * d1) { errors++; printf ("Error 5.8: lat1=%d, lon2=%d, d1=%d, b1=%d, d2=%.2f\n", lat1, lon1, d1, b1, d2); }
+	      if (b2 < b1 - 0.1 || b2 > b1 + 0.1)       { errors++; printf ("Error 5.9: lat1=%d, lon2=%d, d1=%d, b1=%d, b2=%.2f\n", lat1, lon1, d1, b1, b2); }
+	    }
+	  }
+	}
+
+
+/* Maidenhead locator to lat/long. */
+
+
+	ok = ll_from_grid_square ("BL11", &dlat, &dlon);
+	if (!ok || dlat < 20.4999999 || dlat > 21.5000001 || dlon < -157.0000001 || dlon > -156.9999999) { errors++; printf ("Error 7.1: Did not expect %.6f %.6f\n", dlat, dlon); }
+
+	ok = ll_from_grid_square ("BL11BH", &dlat, &dlon);
+	if (!ok || dlat < 21.31249 || dlat > 21.31251 || dlon < -157.87501 || dlon > -157.87499) { errors++; printf ("Error 7.2: Did not expect %.6f %.6f\n", dlat, dlon); }
+
+#if 0		// TODO: add more test cases after comparing results with other cconverters.
+		// Many other converters are limited to smaller number of characters,
+		// or return corner rather than center of square, or return 3 decimal places for degrees.
+
+	ok = ll_from_grid_square ("BL11BH16", &dlat, &dlon);
+	if (!ok || dlat < 21.? || dlat > 21.? || dlon < -157.? || dlon > -157.?) { errors++; printf ("Error 7.3: Did not expect %.6f %.6f\n", dlat, dlon); }
+
+	ok = ll_from_grid_square ("BL11BH16oo", &dlat, &dlon);
+	if (!ok || dlat < 21.? || dlat > 21.? || dlon < -157.? || dlon > -157.?) { errors++; printf ("Error 7.4: Did not expect %.6f %.6f\n", dlat, dlon); }
+
+	ok = ll_from_grid_square ("BL11BH16oo66", &dlat, &dlon);
+	if (!ok || dlat < 21.? || dlat > 21.? || dlon < -157.? || dlon > -157.?) { errors++; printf ("Error 7.5: Did not expect %.6f %.6f\n", dlat, dlon); }
+#endif
+        if (errors > 0) {
+          //text_color_set (DW_COLOR_ERROR);
+          printf ("\nLocation Coordinate Conversion Test - FAILED!\n");
+          exit (EXIT_FAILURE);
+        }
+        //text_color_set (DW_COLOR_REC);
+        printf ("\nLocation Coordinate Conversion Test - SUCCESS!\n");
+        exit (EXIT_SUCCESS);
+
+}
+
+
+
+#endif
+
+
+/* end latlong.c */

+ 24 - 0
main/latlong.h

@@ -0,0 +1,24 @@
+
+/* latlong.h */
+
+
+/* Use this value for unknown latitude/longitude or other values. */
+
+#define G_UNKNOWN (-999999)
+
+
+void latitude_to_str (double dlat, int ambiguity, char *slat);
+void longitude_to_str (double dlong, int ambiguity, char *slong);
+
+void latitude_to_comp_str (double dlat, char *clat);
+void longitude_to_comp_str (double dlon, char *clon);
+
+void latitude_to_nmea (double dlat, char *slat, char *hemi);
+void longitude_to_nmea (double dlong, char *slong, char *hemi);
+
+double latitude_from_nmea (char *pstr, char *phemi);
+double longitude_from_nmea (char *pstr, char *phemi);
+
+double ll_distance_km (double lat1, double lon1, double lat2, double lon2);
+
+int ll_from_grid_square (char *maidenhead, double *dlat, double *dlon);

+ 22 - 1
main/main.c

@@ -12,6 +12,10 @@
 #include "cc1120_protocol.h"
 #include "board.h"
 
+#include "ax25_pad2.h"
+#include "ax25_pad.h"
+#include "fcs_calc.h"
+
 extern uint8_t tx_symbol;
 extern uint8_t sample_count;
 
@@ -19,8 +23,25 @@ void IRAM_ATTR app_main()
 {
 	cc1120_radio_init(APRS_SETTINGS, sizeof(APRS_SETTINGS)/sizeof(cc1120_reg_settings_t));
 	vTaskDelay(500/portTICK_PERIOD_MS);
-	cc1120_radio_APRSTXPacket();
+
+	// generate sample packet
+	packet_t pp;
+	unsigned char fbuf[AX25_MAX_PACKET_LEN+2];
+	uint32_t flen;
+	uint32_t c;
+
+	pp = ax25_from_text("WB2OSZ-15>TEST:,The quick brown fox jumps over the lazy dog!  1 of 4", 1);
+	flen = ax25_pack(pp, fbuf);
+
+	uint32_t fcs = fcs_calc(fbuf, flen);
+
+	ax25_hex_dump(pp);
+	printf("FCS: %x\n", fcs);
+
+
+	//cc1120_radio_APRSTXPacket();
 	//xTaskCreatePinnedToCore();
 
 
+
 }

+ 128 - 0
main/strlcat.c

@@ -0,0 +1,128 @@
+
+
+/*------------------------------------------------------------------
+ *
+ * Module:      strlcat.c
+ *
+ * Purpose:   	Safe string functions to guard against buffer overflow.
+ *			
+ * Description:	The size of character strings, especially when coming from the 
+ *		outside, can sometimes exceed a fixed size storage area.  
+ *
+ *		There was one case where a MIC-E format packet had an enormous
+ *		comment that exceeded an internal buffer of 256 characters,
+ *		resulting in a crash.
+ *
+ *		We are not always meticulous about checking sizes to avoid overflow.
+ *		Use of these functions, instead of strcpy and strcat, should
+ *		help avoid issues.
+ *
+ * Orgin:	From OpenBSD as the copyright notice indicates.
+ *		The GNU folks didn't think it was appropriate for inclusion 
+ *		in glibc.     https://lwn.net/Articles/507319/
+ *
+ * Modifications:	Added extra debug output when strings are truncated.
+ *			Not sure if I will leave this in the release version
+ *			or just let it happen silently.		
+ *
+ *---------------------------------------------------------------*/
+
+#include "direwolf.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+//#include "textcolor.h"
+
+
+/*	$NetBSD: strlcat.c,v 1.5 2014/10/31 18:59:32 spz Exp $	*/
+/*	from	NetBSD: strlcat.c,v 1.16 2003/10/27 00:12:42 lukem Exp	*/
+/*	from OpenBSD: strlcat.c,v 1.10 2003/04/12 21:56:39 millert Exp	*/
+
+/*
+ * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND TODD C. MILLER DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL TODD C. MILLER BE LIABLE
+ * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
+ * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+ * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+
+
+/*
+ * Appends src to string dst of size siz (unlike strncat, siz is the
+ * full size of dst, not space left).  At most siz-1 characters
+ * will be copied.  Always NUL terminates (unless siz <= strlen(dst)).
+ * Returns strlen(src) + MIN(siz, strlen(initial dst)).
+ * If retval >= siz, truncation occurred.
+ */
+
+#if DEBUG_STRL
+size_t strlcat_debug(char *__restrict__ dst, const char *__restrict__ src, size_t siz, const char *file, const char *func, int line)
+#else
+size_t strlcat_debug(char *__restrict__ dst, const char *__restrict__ src, size_t siz)
+#endif
+{
+	char *d = dst;
+	const char *s = src;
+	size_t n = siz;
+	size_t dlen;
+	size_t retval;
+
+#if DEBUG_STRL
+	if (dst == NULL) {
+		//text_color_set (DW_COLOR_ERROR);
+		printf ("ERROR: strlcat dst is NULL.  (%s %s %d)\n", file, func, line);
+		return (0);
+	}
+	if (src == NULL) {
+		//text_color_set (DW_COLOR_ERROR);
+		printf ("ERROR: strlcat src is NULL.  (%s %s %d)\n", file, func, line);
+		return (0);
+	}
+	if (siz == 1 || siz == 4) {
+		//text_color_set (DW_COLOR_ERROR);
+		printf ("Suspicious strlcat siz.  Is it using sizeof a pointer variable?  (%s %s %d)\n", file, func, line);
+	}
+#endif
+
+	/* Find the end of dst and adjust bytes left but don't go past end */
+	while (n-- != 0 && *d != '\0')
+		d++;
+	dlen = d - dst;
+	n = siz - dlen;
+
+	if (n == 0) {
+		retval = dlen + strlen(s);
+		goto the_end;
+	}
+	while (*s != '\0') {
+		if (n != 1) {
+			*d++ = *s;
+			n--;
+		}
+		s++;
+	}
+	*d = '\0';
+
+	retval = dlen + (s - src);	/* count does not include NUL */
+the_end:
+
+#if DEBUG_STRL
+	if (retval >= siz) {
+		//text_color_set (DW_COLOR_ERROR);
+		printf ("WARNING: strlcat result length %d exceeds maximum length %d.  (%s %s %d)\n",
+				(int)retval, (int)(siz-1), file, func, line);
+	}
+#endif
+	return (retval);
+}

+ 122 - 0
main/strlcpy.c

@@ -0,0 +1,122 @@
+
+
+/*------------------------------------------------------------------
+ *
+ * Module:      strlcpy.c
+ *
+ * Purpose:   	Safe string functions to guard against buffer overflow.
+ *			
+ * Description:	The size of character strings, especially when coming from the 
+ *		outside, can sometimes exceed a fixed size storage area.  
+ *
+ *		There was one case where a MIC-E format packet had an enormous
+ *		comment that exceeded an internal buffer of 256 characters,
+ *		resulting in a crash.
+ *
+ *		We are not always meticulous about checking sizes to avoid overflow.
+ *		Use of these functions, instead of strcpy and strcat, should
+ *		help avoid issues.
+ *
+ * Orgin:	From OpenBSD as the copyright notice indicates.
+ *		The GNU folks didn't think it was appropriate for inclusion 
+ *		in glibc.     https://lwn.net/Articles/507319/
+ *
+ * Modifications:	Added extra debug output when strings are truncated.
+ *			Not sure if I will leave this in the release version
+ *			or just let it happen silently.		
+ *
+ *---------------------------------------------------------------*/
+
+
+
+/*	$NetBSD: strlcpy.c,v 1.5 2014/10/31 18:59:32 spz Exp $	*/
+/*	from	NetBSD: strlcpy.c,v 1.14 2003/10/27 00:12:42 lukem Exp	*/
+/*	from OpenBSD: strlcpy.c,v 1.7 2003/04/12 21:56:39 millert Exp	*/
+
+/*
+ * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND TODD C. MILLER DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL TODD C. MILLER BE LIABLE
+ * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
+ * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+ * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include "direwolf.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+
+//#include "textcolor.h"
+
+/*
+ * Copy src to string dst of size siz.  At most siz-1 characters
+ * will be copied.  Always NUL terminates (unless siz == 0).
+ * Returns strlen(src); if retval >= siz, truncation occurred.
+ */
+
+#if DEBUG_STRL
+size_t strlcpy_debug(char *__restrict__ dst, const char *__restrict__ src, size_t siz, const char *file, const char *func, int line)
+#else
+size_t strlcpy_debug(char *__restrict__ dst, const char *__restrict__ src, size_t siz)
+#endif
+{
+	char *d = dst;
+	const char *s = src;
+	size_t n = siz;
+	size_t retval;
+
+#if DEBUG_STRL
+	if (dst == NULL) {
+		//text_color_set (DW_COLOR_ERROR);
+		printf ("ERROR: strlcpy dst is NULL.  (%s %s %d)\n", file, func, line);
+		return (0);
+	}
+	if (src == NULL) {
+		//text_color_set (DW_COLOR_ERROR);
+		printf ("ERROR: strlcpy src is NULL.  (%s %s %d)\n", file, func, line);
+		return (0);
+	}
+	if (siz == 1 || siz == 4) {
+		//text_color_set (DW_COLOR_ERROR);
+		printf ("Suspicious strlcpy siz.  Is it using sizeof a pointer variable?  (%s %s %d)\n", file, func, line);
+	}
+#endif
+
+	/* Copy as many bytes as will fit */
+	if (n != 0 && --n != 0) {
+		do {
+			if ((*d++ = *s++) == 0)
+				break;
+		} while (--n != 0);
+	}
+
+	/* Not enough room in dst, add NUL and traverse rest of src */
+	if (n == 0) {
+		if (siz != 0)
+			*d = '\0';		/* NUL-terminate dst */
+		while (*s++)
+			;
+	}
+
+	retval = s - src - 1;	/* count does not include NUL */
+
+#if DEBUG_STRL
+	if (retval >= siz) {
+		//text_color_set (DW_COLOR_ERROR);
+		printf ("WARNING: strlcpy result length %d exceeds maximum length %d.  (%s %s %d)\n",
+				(int)retval, (int)(siz-1), file, func, line);
+	}
+#endif
+	return (retval);
+}
+