| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349 |
- /*
- * Copyright (c) 2019 Clementine Computing LLC.
- *
- * This file is part of PopuFare.
- *
- * PopuFare is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * PopuFare 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 Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with PopuFare. If not, see <https:// www.gnu.org/licenses/>.
- *
- */
- #include <sys/termios.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/ioctl.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <signal.h>
- #include <string.h>
- #include <poll.h>
- #include <syslog.h>
- #include <sysexits.h>
- #include <stdarg.h>
- #include <dirent.h>
- #include <fnmatch.h>
- #include "common_defs.h"
- #ifndef DEFAULT_BAUD
- #define DEFAULT_BAUD (B115200)
- #endif
- // ------------------------------------------- This horrible blob of code goes and hunts for package install records and gathers
- // ------------------------------------------- them into a sane data structure for display to the user in status/diagnostic screens.
- #define PKG_SEARCH_DIR CONFIG_FILE_PATH
- #define PATTERN_SUFFIX ".tgz.version"
- #define CHECKSUM_SUFFIX ".tgz.checksum"
- #define PATTTERN ("*" PATTERN_SUFFIX)
- static int package_filter(const struct dirent *file) {
- int match = fnmatch(PATTTERN, file->d_name, 0);
- return !match;
- }
- int find_packages(package_signature *pkgs, int n) {
- int i = 0;
- int scandir_ret;
- struct dirent **matchlist;
- int j;
- int match_len;
- int suffix_len = strlen(PATTERN_SUFFIX);
- FILE *f;
- struct stat st;
- char pathbuffer[1024];
- // Look for any file that matches the pattern PATTERN (see package_filter above) and return into matchlist a pointer
- // to and array of pointers to dirent structures for each directory entry that made the cut, sorted alphabetically
- //
- scandir_ret = scandir(PKG_SEARCH_DIR, &matchlist, package_filter, alphasort);
- // If that seemed to work....
- //
- if( (scandir_ret >= 0) && (matchlist != NULL) ) {
- // Walk the resultant list
- //
- for(i=0; i < scandir_ret; i++) {
- // if we've filled our caller's buffer, break out now
- //
- if(i >= n) {
- break;
- }
- // Go figure out how long the module name part is (it'll be the length of the filename minus the length of the suffix)
- //
- match_len = strlen(matchlist[i]->d_name) - suffix_len;
- // If that would cause an overflow, truncate it...
- //
- if (match_len > (PKG_STRING_SIZE - 1)) {
- match_len = PKG_STRING_SIZE - 1;
- }
- // Copy our package name
- //
- strncpy(pkgs[i].pkgname, matchlist[i]->d_name, match_len);
- pkgs[i].pkgname[match_len] = '\0';
- // (if fscanf fails, we want an empty string rather than random crap from memory...)
- //
- pkgs[i].pkgver[0] = '\0';
- // generate the file name of the package version string...
- //
- snprintf(pathbuffer, sizeof(pathbuffer), "%s%s%s", PKG_SEARCH_DIR, pkgs[i].pkgname, PATTERN_SUFFIX);
- // Go and read the contents of that into the pkgver part of our structure...
- //
- f = fopen(pathbuffer, "rb");
- if (f) {
- fscanf(f, PKG_STRING_FORMAT, pkgs[i].pkgver);
- fclose(f);
- }
- pkgs[i].checksum[0] = '\0';
- // generate the file name of the file containing the package checksum
- //
- snprintf(pathbuffer, sizeof(pathbuffer), "%s%s%s", PKG_SEARCH_DIR, pkgs[i].pkgname, CHECKSUM_SUFFIX);
- // Go and read the contents of that into the checkdum part of our structure...
- //
- f = fopen(pathbuffer, "rb");
- if (f) {
- fscanf(f, PKG_STRING_FORMAT, pkgs[i].checksum);
- fclose(f);
- }
- pkgs[i].installed = 0;
- // Go and grab the mtime of the package install file
- //
- if (!stat(pathbuffer, &st)) {
- pkgs[i].installed = st.st_mtime;
- }
- // Free this dirent
- //
- free(matchlist[i]);
- }
- // Clean up any leftovers
- //
- for (j = i; j < scandir_ret; j++) {
- free(matchlist[i]);
- }
- // free the array of pointers
- //
- free(matchlist);
- }
- // return the number actually filled
- //
- return i;
- }
- // --------------------------------------------------------------------------------------------------
- // This function checks the dropfile to see if the tunnel is up...
- //
- int tunnel_is_up() {
- struct stat st;
- int retval;
- retval = stat(TUNNEL_DROPFILE, &st);
- if (retval) {
- return 0;
- }
- else {
- return 1;
- }
- }
- // This function checks the dropfile to see if the GPRS modem is up...
- //
- int gprs_is_up() {
- struct stat st;
- int retval;
- retval = stat(GPRS_DROPFILE, &st);
- if(retval) {
- return 0;
- }
- else {
- return 1;
- }
- }
- // This function gets the equipment number from the appropriate config file
- // If it cannot be gotten, it returns -1
- //
- int get_equip_num() {
- FILE *f;
- int num = -1;
- f = fopen(EQUIPNUM_FILE, "rb");
- if (f) {
- fscanf(f,"%d",&num);
- fclose(f);
- }
- else {
- num = -1;
- }
- return num;
- }
- // This function sets the euipment number in the config file.
- // if this operation fails, -1 is returned.
- //
- int set_equip_num(int num) {
- FILE *f;
- if ( (num < 1) || (num > MAX_EQUIPNUM) ) {
- return -1;
- }
- f = fopen(EQUIPNUM_TEMPFILE, "wb");
- if (f) {
- fprintf(f,"%d\n", num);
- fclose(f);
- rename(EQUIPNUM_TEMPFILE, EQUIPNUM_FILE);
- sync();
- return 0;
- }
- return -1;
- }
- //
- /*
- int get_state_info(state_info_t *_state) {
- FILE *fp;
- int ch = 1,
- input_idx=0,
- n=0,
- field_len=0;
- char buffer[LINE_BUFFER_SIZE],
- *chp;
- if (access(STATE_INFO_FILE, R_OK)!=0) {
- return -1;
- }
- memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
- if ((fp = fopen(STATE_INFO_FILE, "r")) == NULL) {
- return -1;
- }
- while (!feof(fp)) {
- ch = fgetc(fp);
- if ((ch == '\n') || (ch == EOF)) {
- // ignore blank lines and comment lines
- // (begining with '#')
- //
- if (input_idx == 0) { continue; }
- if (buffer[0] == '#') { continue; }
- chp = strchr(buffer, ' ');
- if (chp != NULL) {
- chp++;
- n = chp - buffer;
- if (strncmp(buffer, "LAT ", n)==0) {
- _state->lat = atof(chp+1);
- }
- else if (strncmp(buffer, "LON ", n)==0) {
- _state->lon = atof(chp+1);
- }
- else if (strncmp(buffer, "HEADING ", n)==0) {
- _state->heading = atof(chp+1);
- }
- else if (strncmp(buffer, "VELOCITY ", n)==0) {
- _state->velocity = atof(chp+1);
- }
- else if (strncmp(buffer, "NUM_SATS ", n)==0) {
- _state->num_sats = atoi(chp+1);
- }
- else if (strncmp(buffer, "GPS_GOOD ", n)==0) {
- _state->gps_good = atoi(chp+1);
- }
- else if (strncmp(buffer, "STAMP ", n)==0) {
- _state->stamp = (time_t)atoi(chp+1);
- }
- else if (strncmp(buffer, "GPSTAMP ", n)==0) {
- _state->gpstime = (time_t)atoi(chp+1);
- }
- else if (strncmp(buffer, "PADDLE ", n)==0) {
- _state->paddle = atoi(chp+1);
- }
- else if (strncmp(buffer, "ROUTE ", n)==0) {
- _state->route = atoi(chp+1);
- }
- else if (strncmp(buffer, "TRIP ", n)==0) {
- _state->trip = atoi(chp+1);
- }
- else if (strncmp(buffer, "STOP ", n)==0) {
- _state->stop = atoi(chp+1);
- }
- else if (strncmp(buffer, "STOPNAME ", n)==0) {
- field_len = input_idx - n;
- if (field_len >= STATE_INFO_FIELD_SIZE) {
- field_len = STATE_INFO_FIELD_SIZE-1;
- }
- memcpy(_state->stopname, chp, field_len);
- _state->stopname[field_len] = '\0';
- }
- else if (strncpy(buffer, "LOGGED_IN_DRIVER ", n)==0) {
- _state->logged_in_driver = atoi(chp+1);
- }
- else if (strncpy(buffer, "DRIVER_NAME ", n)==0) {
- field_len = input_idx - n;
- if (field_len >= STATE_INFO_FIELD_SIZE) {
- field_len = STATE_INFO_FIELD_SIZE-1;
- }
- memcpy(_state->driver_name, chp+1, input_idx - n + 1);
- _state->driver_name[field_len] = '\0';
- }
- else if (strncmp(buffer, "EQUIP_NUM ", n)==0) {
- _state->equip_num = atoi(chp+1);
- }
- }
- buffer[0] = '\0';
- input_idx = 0;
- continue;
- }
- buffer[input_idx] = ch;
- input_idx++;
- if (input_idx >= LINE_BUFFER_SIZE) {
- input_idx = LINE_BUFFER_SIZE-1;
- }
- buffer[input_idx] = '\0';
- }
- fclose(fp);
- return 0;
- }
- // save on disk state
- //
- int set_state_info(state_info_t *_state) {
- FILE *fp;
- if ((fp = fopen(STATE_INFO_TEMPFILE, "w")) == NULL) {
- return -1;
- }
- fprintf(fp, "LAT %f\n", _state->lat);
- fprintf(fp, "LON %f\n", _state->lon);
- fprintf(fp, "HEADING %f\n", _state->heading);
- fprintf(fp, "VELOCITY %f\n", _state->velocity);
- fprintf(fp, "NUM_SATS %i\n", _state->num_sats);
- fprintf(fp, "GPS_GOOD %i\n", _state->gps_good);
- fprintf(fp, "STAMP %i\n", (int)(_state->stamp));
- fprintf(fp, "GPSTAMP %i\n", (int)(_state->gpstime));
- fprintf(fp, "PADDLE %i\n", _state->paddle);
- fprintf(fp, "ROUTE %i\n", _state->route);
- fprintf(fp, "TRIP %i\n", _state->trip);
- fprintf(fp, "STOP %i\n", _state->stop);
- fprintf(fp, "STOPNAME %s\n", _state->stopname);
- fprintf(fp, "LOGGED_IN_DRIVER %i\n", _state->logged_in_driver);
- fprintf(fp, "DRIVER_NAME %s\n", _state->driver_name);
- fprintf(fp, "equip_num %i\n", _state->equip_num);
- fclose(fp);
- return rename(STATE_INFO_TEMPFILE, STATE_INFO_FILE);
- }
- // save on disk state
- //
- int print_state_info(state_info_t *_state) {
- FILE *fp = stdout;
- fprintf(fp, "LAT %f\n", _state->lat);
- fprintf(fp, "LON %f\n", _state->lon);
- fprintf(fp, "HEADING %f\n", _state->heading);
- fprintf(fp, "VELOCITY %f\n", _state->velocity);
- fprintf(fp, "NUM_SATS %i\n", _state->num_sats);
- fprintf(fp, "GPS_GOOD %i\n", _state->gps_good);
- fprintf(fp, "STAMP %i\n", (int)(_state->stamp));
- fprintf(fp, "GPSTAMP %i\n", (int)(_state->gpstime));
- fprintf(fp, "PADDLE %i\n", _state->paddle);
- fprintf(fp, "ROUTE %i\n", _state->route);
- fprintf(fp, "TRIP %i\n", _state->trip);
- fprintf(fp, "STOP %i\n", _state->stop);
- fprintf(fp, "STOPNAME %s\n", _state->stopname);
- fprintf(fp, "LOGGED_IN_DRIVER %i\n", _state->logged_in_driver);
- fprintf(fp, "DRIVER_NAME %s\n", _state->driver_name);
- fprintf(fp, "equip_num %i\n", _state->equip_num);
- return 0;
- }
- */
- /*
- int get_driver_state(driver_status *_driver_stat) {
- FILE *fp;
- int input_idx=0,
- n=0,
- ch;
- char buffer[LINE_BUFFER_SIZE];
- // 0 - logged_in_driver
- // 1 - driver_name
- // 2 - equip_num
- //
- int _read_state = 0;
- if (access(DRIVER_STATE_FILE, R_OK)!=0) {
- return -1;
- }
- memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
- n = DRIVER_NAME_LEN;
- if (LINE_BUFFER_SIZE < n) {
- n = LINE_BUFFER_SIZE;
- }
- fp = fopen(DRIVER_STATE_FILE, "r");
- while ( (ch = fgetc(fp)) != EOF ) {
- if ((ch == '\n') || (ch == EOF)) {
- if (_read_state == 0) {
- _driver_stat->logged_in_driver = atoi(buffer);
- _read_state++;
- }
- else if (_read_state == 1) {
- n = input_idx+1;
- if (n > DRIVER_NAME_LEN) {
- n = DRIVER_NAME_LEN;
- }
- buffer[n-1] = '\0';
- memcpy(_driver_stat->driver_name, buffer, n);
- _read_state++;
- }
- else if (_read_state == 2) {
- _driver_stat->equip_num = atoi(buffer);
- _read_state++;
- }
- memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
- input_idx=0;
- continue;
- }
- buffer[input_idx] = ch;
- input_idx++;
- if (input_idx >= LINE_BUFFER_SIZE) {
- input_idx = LINE_BUFFER_SIZE-1;
- buffer[LINE_BUFFER_SIZE-1] = 0;
- }
- }
- fclose(fp);
- if (_read_state < 3) {
- return -2;
- }
- return 0;
- }
- int get_stop_state(stop_status *_stop_stat) {
- FILE *fp;
- int input_idx=0,
- n=0,
- ch;
- char buffer[LINE_BUFFER_SIZE];
- // 0 - paddle
- // 1 - route
- // 2 - trip
- // 3 - stop
- // 4 - lat
- // 5 - lon
- // 6 - stopname
- //
- int _read_state = 0;
- if (access(STOP_STATE_FILE, R_OK)!=0) {
- return -1;
- }
- memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
- fp = fopen(DRIVER_STATE_FILE, "r");
- while ( (ch = fgetc(fp)) != EOF ) {
- if ((ch == '\n') || (ch == EOF)) {
- if (_read_state == 0) {
- _stop_stat->paddle= atoi(buffer);
- _read_state++;
- }
- else if (_read_state == 1) {
- _stop_stat->route = atoi(buffer);
- _read_state++;
- }
- else if (_read_state == 2) {
- _stop_stat->trip = atoi(buffer);
- _read_state++;
- }
- else if (_read_state == 3) {
- _stop_stat->stop= atoi(buffer);
- _read_state++;
- }
- else if (_read_state == 4) {
- _stop_stat->lat = atof(buffer);
- _read_state++;
- }
- else if (_read_state == 5) {
- _stop_stat->lon = atof(buffer);
- _read_state++;
- }
- else if (_read_state == 6) {
- n = input_idx+1;
- if (n > STOP_NAME_LEN) {
- n = DRIVER_NAME_LEN;
- }
- buffer[n-1] = '\0';
- memcpy(_stop_stat->stopname, buffer, n);
- _read_state++;
- }
- memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
- input_idx=0;
- continue;
- }
- buffer[input_idx] = ch;
- input_idx++;
- if (input_idx >= LINE_BUFFER_SIZE) {
- input_idx = LINE_BUFFER_SIZE-1;
- buffer[LINE_BUFFER_SIZE-1] = 0;
- }
- }
- fclose(fp);
- if (_read_state < 6) {
- return -2;
- }
- return 0;
- }
- int get_gps_state(gps_status *_gps_stat) {
- FILE *fp;
- int input_idx=0,
- ch;
- char buffer[LINE_BUFFER_SIZE];
- // 0 - lat
- // 1 - lon
- // 2 - heading
- // 3 - velocity
- // 4 - num_sats
- // 5 - gps_good
- // 6 - stamp
- // 7 - gpstime
- //
- int _read_state = 0;
- if (access(GPS_STATE_FILE, R_OK)!=0) {
- return -1;
- }
- memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
- fp = fopen(DRIVER_STATE_FILE, "r");
- while ( (ch = fgetc(fp)) != EOF ) {
- if ((ch == '\n') || (ch == EOF)) {
- if (_read_state == 0) {
- _gps_stat->lat = atof(buffer);
- _read_state++;
- }
- else if (_read_state == 1) {
- _gps_stat->lon = atof(buffer);
- _read_state++;
- }
- else if (_read_state == 2) {
- _gps_stat->heading = atof(buffer);
- _read_state++;
- }
- else if (_read_state == 3) {
- _gps_stat->velocity = atof(buffer);
- _read_state++;
- }
- else if (_read_state == 4) {
- _gps_stat->num_sats = atoi(buffer);
- _read_state++;
- }
- else if (_read_state == 5) {
- _gps_stat->gps_good = atoi(buffer);
- _read_state++;
- }
- else if (_read_state == 6) {
- _gps_stat->stamp = (time_t)atoi(buffer);
- _read_state++;
- }
- else if (_read_state == 7) {
- _gps_stat->gpstime = (time_t)atoi(buffer);
- _read_state++;
- }
- memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
- input_idx=0;
- continue;
- }
- buffer[input_idx] = ch;
- input_idx++;
- if (input_idx >= LINE_BUFFER_SIZE) {
- input_idx = LINE_BUFFER_SIZE-1;
- buffer[LINE_BUFFER_SIZE-1] = 0;
- }
- }
- fclose(fp);
- if (_read_state < 7) {
- return -2;
- }
- return 0;
- }
- */
- int get_server_desc(char *desc, int len) {
- char svrname[LINE_BUFFER_SIZE];
- FILE *f;
- if (!desc) {
- return -1;
- }
- if (len <= 0) {
- return -1;
- }
- f = fopen(SERVER_DESC_FILE, "rb");
- if (f) {
- fgets(svrname, LINE_BUFFER_SIZE, f);
- svrname[LINE_BUFFER_SIZE - 1] = '\0';
- strip_crlf(svrname);
- strncpy(desc, svrname, len);
- desc[len - 1] = '\0';
- return 0;
- }
- return -1;
- }
- int get_field(char *dest, char *src, int dest_len, int *eol_flag) {
- int i,j;
- int done = 0;
- int eol = 0;
- i = j = 0;
- while ( ! done ) {
- switch(src[i]) {
- case '\0': // If we've hit the end of the input line
- case '\n':
- case '\r':
- // cap off our destination string if there is room
- //
- if (j < dest_len) {
- dest[j++] = '\0';
- }
- // set our internal End Of Line flag
- //
- eol = 1;
- // set the done flag so we break out of the while
- //
- done = 1;
- break;
- // If we have hit a record boundary
- //
- case '\t':
- // cap off our input line
- //
- if (j < dest_len) {
- dest[j++] = '\0';
- }
- // Advance past this input character
- //
- i++;
- // flag us as done
- //
- done = 1;
- break;
- // otherwise (for normal characters) just copy them if there is space
- //
- default:
- if (j < dest_len) {
- dest[j++] = src[i];
- }
- // and advance past them
- //
- i++;
- break;
- }
- }
- // If we have filled our line to capacity
- //
- if ( j == dest_len ) {
- // Truncate it by 1 character to fit the terminating NUL
- //
- dest[dest_len - 1] = '\0';
- }
- // If the user has passed us a place to store our EOL flag,
- //
- if( eol_flag != NULL ) {
- // store it there
- //
- *eol_flag = eol;
- }
- // Return the index of the next character to be consumed.
- //
- return i;
- }
- // magic hash function hashes english strings well enough for our needs
- //
- unsigned long long stringhash(char *string) {
- unsigned long long hash = 5381;
- int c;
- while ((c = *string++)) {
- /* hash * 33 + c */
- hash = ((hash << 5) + hash) + c;
- }
- return hash;
- }
- int strip_crlf(char *buffer) {
- char *src,*dst;
- int count=0;
- // Set both our source and destination pointers to the buffer in question
- //
- src=dst=buffer;
- // While we still have unprocessed buffer bytes
- //
- while(*src) {
- // If we encounter a CR or LF character
- //
- if((*src == '\r') || (*src == '\n')) {
- // If the NEXT character is not another EOL character or a terminating nul
- //
- if( (src[1] != '\0') && (src[1] != '\r') && (src[1] != '\n') ) {
- src++;
- // replace the CR or LF with a space.
- //
- *dst++ = ' ';
- count++;
- continue;
- }
- // On the other hand, if what comes next is EOL or end of string,
- //
- else {
- // just trim this character
- //
- src++;
- continue;
- }
- }
- // If this character isn't one of the special ones, just copy it.
- //
- *dst++ = *src++;
- count++;
- }
- // Copy the terminating NUL
- //
- *dst++ = *src++;
- return count;
- }
- int open_rs232_device(char *devname, int custom_baud, int linemode) {
- struct termios tty={0};
- int retval;
- int fd;
- // Open the specified character device READ/WRITE and not as a Controlling TTY
- //
- fd = open(devname, O_RDWR | O_NOCTTY);
- if (fd < 0) {
- #ifdef COMMON_PRINT_WARNING
- fprintf(stderr, "Warning: Cannot open TTY %s\n", devname);
- #endif
- return -1;
- }
- // Try and fetch the TTY properties of the device
- //
- retval = ioctl(fd, TCGETS, &tty);
- if (retval) {
- #ifdef COMMON_PRINT_WARNING
- fprintf(stderr, "Warning: Cannot get TTY attributes on %s. Not a TTY?\n", devname);
- #endif
- close(fd);
- return -1;
- }
- if (custom_baud > 0) {
- tty.c_cflag = custom_baud | CS8 | CREAD | CLOCAL;
- }
- else {
- tty.c_cflag = DEFAULT_BAUD | CS8 | CREAD | CLOCAL;
- }
- if (linemode) {
- tty.c_iflag = IGNBRK;
- tty.c_oflag = 0;
- tty.c_lflag = ICANON;
- tty.c_line = 0;
- tty.c_cc[VMIN] = 1; // minimum one character read
- tty.c_cc[VTIME] = ACCUM_SECONDS * 10; // wait ACCUM_SECONDS without any further chars
- // before giving up on the arrival of a newline.
- // (VTIME is specified in deciseconds (who knows why...))
- tty.c_cc[VEOL] = '\n'; // allow a newline to release the buffer
- }
- else {
- tty.c_iflag = IGNBRK;
- tty.c_oflag = 0;
- tty.c_lflag = 0;
- tty.c_line = 0;
- tty.c_cc[VMIN] = 1;
- tty.c_cc[VTIME] = 5;
- }
- // try and plunk our desired settings down on the device
- //
- retval = ioctl(fd, TCSETS, &tty);
- if (retval) {
- #ifdef COMMON_PRINT_WARNING
- fprintf(stderr, "Warning: Cannot set TTY attributes on %s. Unsupported mode?\n", devname);
- #endif
- close(fd);
- return -1;
- }
- // flush the serial port buffers to clean up any detritus that has accumulated before we got here
- //
- tcflush(fd, TCIOFLUSH);
- return fd;
- }
- static int read_with_timeout(int fd, void *buffer, int n, int timeout) {
- int retval;
- struct pollfd fds[1];
- fds[0].fd = fd;
- fds[0].events = POLLIN;
- retval = poll(fds, 1, timeout);
- if (retval > 0) {
- return read(fd, buffer, n);
- }
- else {
- return retval;
- }
- }
- static int init_device(int fd, device_test_vector *vec, char *diag) {
- char buffer[1024] = {0};
- int i;
- int retval;
- int len;
- char *trav;
- int timeout = DEVICE_TEST_TIMEOUT;
- if (vec->init_timeout > 0) {
- timeout = vec->init_timeout;
- }
- // If we were given an init string
- //
- if (vec->init_string != NULL) {
- // calculate how long it is
- //
- len = strlen(vec->init_string);
- // send it on its way
- //
- retval = write(fd, vec->init_string, len);
- // if that didn't work
- //
- if (retval != len) {
- // complain and fail
- //
- if (diag) {
- snprintf(diag, DIAG_BUFFER_SIZE, "Cannot write init string to device.");
- }
- return -1;
- }
- }
- i = 0;
- while (i < vec->n_reply_lines) {
- // Ask the kernel for a line from the TTY
- //
- retval = read_with_timeout(fd, buffer, sizeof(buffer), timeout);
- // If we DID read something from the device, make sure it is correct
- //
- if(retval > 0) {
- buffer[retval] = '\0';
- strip_crlf(buffer);
- trav = buffer;
- // Skip any garbage before the start character
- //
- while (*trav && (*trav != '/')) {
- trav++;
- }
- if (*trav == '\0') {
- continue; // ignore blank lines
- }
- if ( (trav[0] == '/') && (trav[1] == '?') && (trav[2] == ':') ) {
- // ignore device ID lines
- //
- continue;
- }
- // The order of these tests in importand. Short circuit keeps us from
- // dereferencing expected_reply_lines if the first test fails
- //
- // If we have a pattern to test against
- //
- if ( (vec->reply_strings != NULL) && (vec->reply_strings[i] != NULL) ) {
- if (strcmp(trav, vec->reply_strings[i])) {
- if (diag) {
- snprintf(diag, DIAG_BUFFER_SIZE, "Read init reply line %d from device, expected \"%s\" but got \"%s\"", i, vec->reply_strings[i], trav);
- }
- return -1;
- }
- }
- }
- // If we DIDN'T read anything from the device...
- //
- else {
- // Complain
- //
- if (diag) {
- snprintf(diag, DIAG_BUFFER_SIZE, "Reading init reply from device timed out waiting for line %d", i);
- }
- // And fail
- //
- return -1;
- }
- i++;
- }
- return 0;
- }
- int test_and_init_device(int fd, device_test_vector *vec, char *diag) {
- char buffer[DEV_INIT_BUFFER_SIZE] = {0};
- char module_id[DEV_INIT_BUFFER_SIZE] = {0};
- int tries = DEVICE_TEST_TRIES;
- int timeout = DEVICE_TEST_TIMEOUT;
- int retval;
- char *trav;
- if (vec == NULL) {
- return -1;
- }
- if (vec->dev_id == NULL) {
- return -1;
- }
- if (vec->init_tries > 0) {
- tries = vec->init_tries;
- }
- if (vec->init_timeout > 0) {
- timeout = vec->init_timeout;
- }
- // We want to iterate through DEVICE_TEST_TRIES tries at getting a valid line from the device
- //
- do {
- // Send a CR to stimulate the device to spit out its help message
- //
- write(fd,"\r", 1);
- // Ask the kernel for a line from the TTY
- //
- retval = read_with_timeout(fd, buffer, sizeof(buffer), timeout);
- // If we actually got a line of data
- //
- if (retval > 0) {
- buffer[retval] = '\0';
- strip_crlf(buffer);
- // Start examining our buffer
- //
- trav = buffer;
- // Skip any garbage before the start character
- //
- while (*trav && (*trav != '/')) {
- trav++;
- }
- // See if it is our Device ID / help line...
- //
- if ( (trav[0] == '/') && (trav[1] == '?') && (trav[2] == ':') ) {
- // Skip the header and go to the body
- //
- trav += 3;
- // Look for our module ID string
- //
- retval = sscanf(trav, " ?=%s", module_id);
- if (retval < 1) {
- // Look for our module ID string without leading space
- //
- retval = sscanf(trav, "?=%s", module_id);
- }
- // If we have found id
- //
- if (retval == 1) {
- // See if it is the correct one
- //
- if (!strcmp(module_id, vec->dev_id)) {
- // If so, pass on our diagnostic message if we have a place to
- //
- if (diag) {
- snprintf(diag, DIAG_BUFFER_SIZE, "Device connected OK");
- }
- return init_device(fd, vec, diag); // Perform initialization and return the status of that operation
- }
- // Otherwise, if it is NOT the one we are expecting
- //
- else {
- // Complain if we have a place to
- //
- if (diag) {
- snprintf(diag, DIAG_BUFFER_SIZE, "Device present: Expecting: \"%s\" Got: \"%s\"", vec->dev_id, module_id);
- }
- return -2; // Return a distinct failure code
- }
- }
- }
- // If we DIDN'T get the line we were looking for, pretend it was blank so we'll try again...
- //
- else {
- // This pretends the received line was black.
- //
- retval = 0;
- }
- // if we got 0 bytes or EINTR from the alarm firing
- //
- }
- // While we still have tries and a previous try didn't work
- //
- } while ( (retval <= 0) && ( --tries > 0) );
- if (diag) {
- snprintf(diag, DIAG_BUFFER_SIZE, "Could not get reply from device");
- }
- return -1;
- }
- // ========================================================================================================
- // ------------------------------- WATCHDOG TIMER and other SIGNAL HANDLERS -------------------------------
- // ========================================================================================================
- // volatile int hup_request_status = 0;
- //
- volatile sig_atomic_t hup_request_status = 0;
- void request_hup(char *fmt, ...) {
- va_list ap;
- hup_request_status = 1;
- va_start(ap, fmt);
- vprintf(fmt, ap);
- va_end(ap);
- }
- // Our signal handlers and standard message handlers will OR these bits into exit_request_status
- //
- volatile int exit_request_status = 0;
- static int exit_signal_counter = 0;
- void request_polite_exit(int reason, char *fmt, ...) {
- va_list ap;
- exit_request_status |= reason;
- if (reason) {
- exit_signal_counter++;
- }
- if (exit_request_status & EXIT_REQUEST_CRASH) {
- va_start(ap, fmt);
- vsyslog(LOG_ERR, fmt, ap);
- va_end(ap);
- exit(EX_SOFTWARE);
- }
- if (exit_signal_counter >= MAX_POLITE_EXIT_REQUESTS) {
- va_start(ap, fmt);
- vsyslog(LOG_NOTICE, fmt, ap);
- va_end(ap);
- exit(SIGTERM);
- }
- }
- static void watchdog_handler(int signum, siginfo_t *info, void *data) {
- request_polite_exit(EXIT_REQUEST_CRASH, "Watchdog timer has expired!");
- }
- static void term_int_handler(int signum, siginfo_t *info, void *data) {
- request_polite_exit(EXIT_REQUEST_INT_TERM, "Received signal %d", signum);
- }
- static void hard_crash_handler(int signum, siginfo_t *info, void *data) {
- switch(signum) {
- case SIGSEGV:
- request_polite_exit(EXIT_REQUEST_CRASH, "Segmentation fault at virtual address %p", info->si_addr);
- break;
- case SIGILL:
- request_polite_exit(EXIT_REQUEST_CRASH, "Illegal instruction at virtual address %p", info->si_addr);
- break;
- case SIGFPE:
- request_polite_exit(EXIT_REQUEST_CRASH, "Floating point exception at virtual address %p", info->si_addr);
- break;
- case SIGBUS:
- request_polite_exit(EXIT_REQUEST_CRASH, "SIGBUS (hardware error!) at address %p", info->si_addr);
- break;
- default:
- request_polite_exit(EXIT_REQUEST_CRASH, "Caught Signal %d", signum);
- break;
- }
- }
- void configure_signal_handlers(char *procname) {
- struct sigaction sa = {{0}};
- openlog(procname, LOG_CONS | LOG_PERROR, LOG_USER);
- #ifdef USE_WATCHDOG_ALARM
- sa.sa_sigaction = watchdog_handler;
- sa.sa_flags = SA_SIGINFO;
- sigfillset(&sa.sa_mask);
- sigaction(SIGALRM, &sa, NULL);
- RESET_WATCHDOG();
- #endif
- // Install our "boy did we ever fuck up this time" signal handler
- // to trap segmentation faults, illegal instructions, divides by zero,
- // and things like RAM chips popping off a running board (SIGBUS).
- //
- sa.sa_sigaction = hard_crash_handler;
- sa.sa_flags = SA_SIGINFO;
- sigaction(SIGSEGV, &sa, NULL);
- sigaction(SIGILL, &sa, NULL);
- sigaction(SIGFPE, &sa, NULL);
- sigaction(SIGBUS, &sa, NULL);
- // Install our polite exit handler...
- //
- sa.sa_sigaction = term_int_handler;
- sa.sa_flags = SA_SIGINFO | SA_RESTART; // Allow interrupted I/O calls to finish to facilitate clean exit
- sigaction(SIGTERM, &sa, NULL);
- sigaction(SIGINT, &sa, NULL);
- }
- // ------------------
|