common_defs.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  1. /*
  2. * Copyright (c) 2019 Clementine Computing LLC.
  3. *
  4. * This file is part of PopuFare.
  5. *
  6. * PopuFare is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * PopuFare is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with PopuFare. If not, see <https:// www.gnu.org/licenses/>.
  18. *
  19. */
  20. #include <sys/termios.h>
  21. #include <sys/types.h>
  22. #include <sys/stat.h>
  23. #include <sys/ioctl.h>
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <fcntl.h>
  27. #include <unistd.h>
  28. #include <signal.h>
  29. #include <string.h>
  30. #include <poll.h>
  31. #include <syslog.h>
  32. #include <sysexits.h>
  33. #include <stdarg.h>
  34. #include <dirent.h>
  35. #include <fnmatch.h>
  36. #include "common_defs.h"
  37. #ifndef DEFAULT_BAUD
  38. #define DEFAULT_BAUD (B115200)
  39. #endif
  40. // ------------------------------------------- This horrible blob of code goes and hunts for package install records and gathers
  41. // ------------------------------------------- them into a sane data structure for display to the user in status/diagnostic screens.
  42. #define PKG_SEARCH_DIR CONFIG_FILE_PATH
  43. #define PATTERN_SUFFIX ".tgz.version"
  44. #define CHECKSUM_SUFFIX ".tgz.checksum"
  45. #define PATTTERN ("*" PATTERN_SUFFIX)
  46. static int package_filter(const struct dirent *file) {
  47. int match = fnmatch(PATTTERN, file->d_name, 0);
  48. return !match;
  49. }
  50. int find_packages(package_signature *pkgs, int n) {
  51. int i = 0;
  52. int scandir_ret;
  53. struct dirent **matchlist;
  54. int j;
  55. int match_len;
  56. int suffix_len = strlen(PATTERN_SUFFIX);
  57. FILE *f;
  58. struct stat st;
  59. char pathbuffer[1024];
  60. // Look for any file that matches the pattern PATTERN (see package_filter above) and return into matchlist a pointer
  61. // to and array of pointers to dirent structures for each directory entry that made the cut, sorted alphabetically
  62. //
  63. scandir_ret = scandir(PKG_SEARCH_DIR, &matchlist, package_filter, alphasort);
  64. // If that seemed to work....
  65. //
  66. if( (scandir_ret >= 0) && (matchlist != NULL) ) {
  67. // Walk the resultant list
  68. //
  69. for(i=0; i < scandir_ret; i++) {
  70. // if we've filled our caller's buffer, break out now
  71. //
  72. if(i >= n) {
  73. break;
  74. }
  75. // Go figure out how long the module name part is (it'll be the length of the filename minus the length of the suffix)
  76. //
  77. match_len = strlen(matchlist[i]->d_name) - suffix_len;
  78. // If that would cause an overflow, truncate it...
  79. //
  80. if (match_len > (PKG_STRING_SIZE - 1)) {
  81. match_len = PKG_STRING_SIZE - 1;
  82. }
  83. // Copy our package name
  84. //
  85. strncpy(pkgs[i].pkgname, matchlist[i]->d_name, match_len);
  86. pkgs[i].pkgname[match_len] = '\0';
  87. // (if fscanf fails, we want an empty string rather than random crap from memory...)
  88. //
  89. pkgs[i].pkgver[0] = '\0';
  90. // generate the file name of the package version string...
  91. //
  92. snprintf(pathbuffer, sizeof(pathbuffer), "%s%s%s", PKG_SEARCH_DIR, pkgs[i].pkgname, PATTERN_SUFFIX);
  93. // Go and read the contents of that into the pkgver part of our structure...
  94. //
  95. f = fopen(pathbuffer, "rb");
  96. if (f) {
  97. fscanf(f, PKG_STRING_FORMAT, pkgs[i].pkgver);
  98. fclose(f);
  99. }
  100. pkgs[i].checksum[0] = '\0';
  101. // generate the file name of the file containing the package checksum
  102. //
  103. snprintf(pathbuffer, sizeof(pathbuffer), "%s%s%s", PKG_SEARCH_DIR, pkgs[i].pkgname, CHECKSUM_SUFFIX);
  104. // Go and read the contents of that into the checkdum part of our structure...
  105. //
  106. f = fopen(pathbuffer, "rb");
  107. if (f) {
  108. fscanf(f, PKG_STRING_FORMAT, pkgs[i].checksum);
  109. fclose(f);
  110. }
  111. pkgs[i].installed = 0;
  112. // Go and grab the mtime of the package install file
  113. //
  114. if (!stat(pathbuffer, &st)) {
  115. pkgs[i].installed = st.st_mtime;
  116. }
  117. // Free this dirent
  118. //
  119. free(matchlist[i]);
  120. }
  121. // Clean up any leftovers
  122. //
  123. for (j = i; j < scandir_ret; j++) {
  124. free(matchlist[i]);
  125. }
  126. // free the array of pointers
  127. //
  128. free(matchlist);
  129. }
  130. // return the number actually filled
  131. //
  132. return i;
  133. }
  134. // --------------------------------------------------------------------------------------------------
  135. // This function checks the dropfile to see if the tunnel is up...
  136. //
  137. int tunnel_is_up() {
  138. struct stat st;
  139. int retval;
  140. retval = stat(TUNNEL_DROPFILE, &st);
  141. if (retval) {
  142. return 0;
  143. }
  144. else {
  145. return 1;
  146. }
  147. }
  148. // This function checks the dropfile to see if the GPRS modem is up...
  149. //
  150. int gprs_is_up() {
  151. struct stat st;
  152. int retval;
  153. retval = stat(GPRS_DROPFILE, &st);
  154. if(retval) {
  155. return 0;
  156. }
  157. else {
  158. return 1;
  159. }
  160. }
  161. // This function gets the equipment number from the appropriate config file
  162. // If it cannot be gotten, it returns -1
  163. //
  164. int get_equip_num() {
  165. FILE *f;
  166. int num = -1;
  167. f = fopen(EQUIPNUM_FILE, "rb");
  168. if (f) {
  169. fscanf(f,"%d",&num);
  170. fclose(f);
  171. }
  172. else {
  173. num = -1;
  174. }
  175. return num;
  176. }
  177. // This function sets the euipment number in the config file.
  178. // if this operation fails, -1 is returned.
  179. //
  180. int set_equip_num(int num) {
  181. FILE *f;
  182. if ( (num < 1) || (num > MAX_EQUIPNUM) ) {
  183. return -1;
  184. }
  185. f = fopen(EQUIPNUM_TEMPFILE, "wb");
  186. if (f) {
  187. fprintf(f,"%d\n", num);
  188. fclose(f);
  189. rename(EQUIPNUM_TEMPFILE, EQUIPNUM_FILE);
  190. sync();
  191. return 0;
  192. }
  193. return -1;
  194. }
  195. //
  196. /*
  197. int get_state_info(state_info_t *_state) {
  198. FILE *fp;
  199. int ch = 1,
  200. input_idx=0,
  201. n=0,
  202. field_len=0;
  203. char buffer[LINE_BUFFER_SIZE],
  204. *chp;
  205. if (access(STATE_INFO_FILE, R_OK)!=0) {
  206. return -1;
  207. }
  208. memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
  209. if ((fp = fopen(STATE_INFO_FILE, "r")) == NULL) {
  210. return -1;
  211. }
  212. while (!feof(fp)) {
  213. ch = fgetc(fp);
  214. if ((ch == '\n') || (ch == EOF)) {
  215. // ignore blank lines and comment lines
  216. // (begining with '#')
  217. //
  218. if (input_idx == 0) { continue; }
  219. if (buffer[0] == '#') { continue; }
  220. chp = strchr(buffer, ' ');
  221. if (chp != NULL) {
  222. chp++;
  223. n = chp - buffer;
  224. if (strncmp(buffer, "LAT ", n)==0) {
  225. _state->lat = atof(chp+1);
  226. }
  227. else if (strncmp(buffer, "LON ", n)==0) {
  228. _state->lon = atof(chp+1);
  229. }
  230. else if (strncmp(buffer, "HEADING ", n)==0) {
  231. _state->heading = atof(chp+1);
  232. }
  233. else if (strncmp(buffer, "VELOCITY ", n)==0) {
  234. _state->velocity = atof(chp+1);
  235. }
  236. else if (strncmp(buffer, "NUM_SATS ", n)==0) {
  237. _state->num_sats = atoi(chp+1);
  238. }
  239. else if (strncmp(buffer, "GPS_GOOD ", n)==0) {
  240. _state->gps_good = atoi(chp+1);
  241. }
  242. else if (strncmp(buffer, "STAMP ", n)==0) {
  243. _state->stamp = (time_t)atoi(chp+1);
  244. }
  245. else if (strncmp(buffer, "GPSTAMP ", n)==0) {
  246. _state->gpstime = (time_t)atoi(chp+1);
  247. }
  248. else if (strncmp(buffer, "PADDLE ", n)==0) {
  249. _state->paddle = atoi(chp+1);
  250. }
  251. else if (strncmp(buffer, "ROUTE ", n)==0) {
  252. _state->route = atoi(chp+1);
  253. }
  254. else if (strncmp(buffer, "TRIP ", n)==0) {
  255. _state->trip = atoi(chp+1);
  256. }
  257. else if (strncmp(buffer, "STOP ", n)==0) {
  258. _state->stop = atoi(chp+1);
  259. }
  260. else if (strncmp(buffer, "STOPNAME ", n)==0) {
  261. field_len = input_idx - n;
  262. if (field_len >= STATE_INFO_FIELD_SIZE) {
  263. field_len = STATE_INFO_FIELD_SIZE-1;
  264. }
  265. memcpy(_state->stopname, chp, field_len);
  266. _state->stopname[field_len] = '\0';
  267. }
  268. else if (strncpy(buffer, "LOGGED_IN_DRIVER ", n)==0) {
  269. _state->logged_in_driver = atoi(chp+1);
  270. }
  271. else if (strncpy(buffer, "DRIVER_NAME ", n)==0) {
  272. field_len = input_idx - n;
  273. if (field_len >= STATE_INFO_FIELD_SIZE) {
  274. field_len = STATE_INFO_FIELD_SIZE-1;
  275. }
  276. memcpy(_state->driver_name, chp+1, input_idx - n + 1);
  277. _state->driver_name[field_len] = '\0';
  278. }
  279. else if (strncmp(buffer, "EQUIP_NUM ", n)==0) {
  280. _state->equip_num = atoi(chp+1);
  281. }
  282. }
  283. buffer[0] = '\0';
  284. input_idx = 0;
  285. continue;
  286. }
  287. buffer[input_idx] = ch;
  288. input_idx++;
  289. if (input_idx >= LINE_BUFFER_SIZE) {
  290. input_idx = LINE_BUFFER_SIZE-1;
  291. }
  292. buffer[input_idx] = '\0';
  293. }
  294. fclose(fp);
  295. return 0;
  296. }
  297. // save on disk state
  298. //
  299. int set_state_info(state_info_t *_state) {
  300. FILE *fp;
  301. if ((fp = fopen(STATE_INFO_TEMPFILE, "w")) == NULL) {
  302. return -1;
  303. }
  304. fprintf(fp, "LAT %f\n", _state->lat);
  305. fprintf(fp, "LON %f\n", _state->lon);
  306. fprintf(fp, "HEADING %f\n", _state->heading);
  307. fprintf(fp, "VELOCITY %f\n", _state->velocity);
  308. fprintf(fp, "NUM_SATS %i\n", _state->num_sats);
  309. fprintf(fp, "GPS_GOOD %i\n", _state->gps_good);
  310. fprintf(fp, "STAMP %i\n", (int)(_state->stamp));
  311. fprintf(fp, "GPSTAMP %i\n", (int)(_state->gpstime));
  312. fprintf(fp, "PADDLE %i\n", _state->paddle);
  313. fprintf(fp, "ROUTE %i\n", _state->route);
  314. fprintf(fp, "TRIP %i\n", _state->trip);
  315. fprintf(fp, "STOP %i\n", _state->stop);
  316. fprintf(fp, "STOPNAME %s\n", _state->stopname);
  317. fprintf(fp, "LOGGED_IN_DRIVER %i\n", _state->logged_in_driver);
  318. fprintf(fp, "DRIVER_NAME %s\n", _state->driver_name);
  319. fprintf(fp, "equip_num %i\n", _state->equip_num);
  320. fclose(fp);
  321. return rename(STATE_INFO_TEMPFILE, STATE_INFO_FILE);
  322. }
  323. // save on disk state
  324. //
  325. int print_state_info(state_info_t *_state) {
  326. FILE *fp = stdout;
  327. fprintf(fp, "LAT %f\n", _state->lat);
  328. fprintf(fp, "LON %f\n", _state->lon);
  329. fprintf(fp, "HEADING %f\n", _state->heading);
  330. fprintf(fp, "VELOCITY %f\n", _state->velocity);
  331. fprintf(fp, "NUM_SATS %i\n", _state->num_sats);
  332. fprintf(fp, "GPS_GOOD %i\n", _state->gps_good);
  333. fprintf(fp, "STAMP %i\n", (int)(_state->stamp));
  334. fprintf(fp, "GPSTAMP %i\n", (int)(_state->gpstime));
  335. fprintf(fp, "PADDLE %i\n", _state->paddle);
  336. fprintf(fp, "ROUTE %i\n", _state->route);
  337. fprintf(fp, "TRIP %i\n", _state->trip);
  338. fprintf(fp, "STOP %i\n", _state->stop);
  339. fprintf(fp, "STOPNAME %s\n", _state->stopname);
  340. fprintf(fp, "LOGGED_IN_DRIVER %i\n", _state->logged_in_driver);
  341. fprintf(fp, "DRIVER_NAME %s\n", _state->driver_name);
  342. fprintf(fp, "equip_num %i\n", _state->equip_num);
  343. return 0;
  344. }
  345. */
  346. /*
  347. int get_driver_state(driver_status *_driver_stat) {
  348. FILE *fp;
  349. int input_idx=0,
  350. n=0,
  351. ch;
  352. char buffer[LINE_BUFFER_SIZE];
  353. // 0 - logged_in_driver
  354. // 1 - driver_name
  355. // 2 - equip_num
  356. //
  357. int _read_state = 0;
  358. if (access(DRIVER_STATE_FILE, R_OK)!=0) {
  359. return -1;
  360. }
  361. memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
  362. n = DRIVER_NAME_LEN;
  363. if (LINE_BUFFER_SIZE < n) {
  364. n = LINE_BUFFER_SIZE;
  365. }
  366. fp = fopen(DRIVER_STATE_FILE, "r");
  367. while ( (ch = fgetc(fp)) != EOF ) {
  368. if ((ch == '\n') || (ch == EOF)) {
  369. if (_read_state == 0) {
  370. _driver_stat->logged_in_driver = atoi(buffer);
  371. _read_state++;
  372. }
  373. else if (_read_state == 1) {
  374. n = input_idx+1;
  375. if (n > DRIVER_NAME_LEN) {
  376. n = DRIVER_NAME_LEN;
  377. }
  378. buffer[n-1] = '\0';
  379. memcpy(_driver_stat->driver_name, buffer, n);
  380. _read_state++;
  381. }
  382. else if (_read_state == 2) {
  383. _driver_stat->equip_num = atoi(buffer);
  384. _read_state++;
  385. }
  386. memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
  387. input_idx=0;
  388. continue;
  389. }
  390. buffer[input_idx] = ch;
  391. input_idx++;
  392. if (input_idx >= LINE_BUFFER_SIZE) {
  393. input_idx = LINE_BUFFER_SIZE-1;
  394. buffer[LINE_BUFFER_SIZE-1] = 0;
  395. }
  396. }
  397. fclose(fp);
  398. if (_read_state < 3) {
  399. return -2;
  400. }
  401. return 0;
  402. }
  403. int get_stop_state(stop_status *_stop_stat) {
  404. FILE *fp;
  405. int input_idx=0,
  406. n=0,
  407. ch;
  408. char buffer[LINE_BUFFER_SIZE];
  409. // 0 - paddle
  410. // 1 - route
  411. // 2 - trip
  412. // 3 - stop
  413. // 4 - lat
  414. // 5 - lon
  415. // 6 - stopname
  416. //
  417. int _read_state = 0;
  418. if (access(STOP_STATE_FILE, R_OK)!=0) {
  419. return -1;
  420. }
  421. memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
  422. fp = fopen(DRIVER_STATE_FILE, "r");
  423. while ( (ch = fgetc(fp)) != EOF ) {
  424. if ((ch == '\n') || (ch == EOF)) {
  425. if (_read_state == 0) {
  426. _stop_stat->paddle= atoi(buffer);
  427. _read_state++;
  428. }
  429. else if (_read_state == 1) {
  430. _stop_stat->route = atoi(buffer);
  431. _read_state++;
  432. }
  433. else if (_read_state == 2) {
  434. _stop_stat->trip = atoi(buffer);
  435. _read_state++;
  436. }
  437. else if (_read_state == 3) {
  438. _stop_stat->stop= atoi(buffer);
  439. _read_state++;
  440. }
  441. else if (_read_state == 4) {
  442. _stop_stat->lat = atof(buffer);
  443. _read_state++;
  444. }
  445. else if (_read_state == 5) {
  446. _stop_stat->lon = atof(buffer);
  447. _read_state++;
  448. }
  449. else if (_read_state == 6) {
  450. n = input_idx+1;
  451. if (n > STOP_NAME_LEN) {
  452. n = DRIVER_NAME_LEN;
  453. }
  454. buffer[n-1] = '\0';
  455. memcpy(_stop_stat->stopname, buffer, n);
  456. _read_state++;
  457. }
  458. memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
  459. input_idx=0;
  460. continue;
  461. }
  462. buffer[input_idx] = ch;
  463. input_idx++;
  464. if (input_idx >= LINE_BUFFER_SIZE) {
  465. input_idx = LINE_BUFFER_SIZE-1;
  466. buffer[LINE_BUFFER_SIZE-1] = 0;
  467. }
  468. }
  469. fclose(fp);
  470. if (_read_state < 6) {
  471. return -2;
  472. }
  473. return 0;
  474. }
  475. int get_gps_state(gps_status *_gps_stat) {
  476. FILE *fp;
  477. int input_idx=0,
  478. ch;
  479. char buffer[LINE_BUFFER_SIZE];
  480. // 0 - lat
  481. // 1 - lon
  482. // 2 - heading
  483. // 3 - velocity
  484. // 4 - num_sats
  485. // 5 - gps_good
  486. // 6 - stamp
  487. // 7 - gpstime
  488. //
  489. int _read_state = 0;
  490. if (access(GPS_STATE_FILE, R_OK)!=0) {
  491. return -1;
  492. }
  493. memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
  494. fp = fopen(DRIVER_STATE_FILE, "r");
  495. while ( (ch = fgetc(fp)) != EOF ) {
  496. if ((ch == '\n') || (ch == EOF)) {
  497. if (_read_state == 0) {
  498. _gps_stat->lat = atof(buffer);
  499. _read_state++;
  500. }
  501. else if (_read_state == 1) {
  502. _gps_stat->lon = atof(buffer);
  503. _read_state++;
  504. }
  505. else if (_read_state == 2) {
  506. _gps_stat->heading = atof(buffer);
  507. _read_state++;
  508. }
  509. else if (_read_state == 3) {
  510. _gps_stat->velocity = atof(buffer);
  511. _read_state++;
  512. }
  513. else if (_read_state == 4) {
  514. _gps_stat->num_sats = atoi(buffer);
  515. _read_state++;
  516. }
  517. else if (_read_state == 5) {
  518. _gps_stat->gps_good = atoi(buffer);
  519. _read_state++;
  520. }
  521. else if (_read_state == 6) {
  522. _gps_stat->stamp = (time_t)atoi(buffer);
  523. _read_state++;
  524. }
  525. else if (_read_state == 7) {
  526. _gps_stat->gpstime = (time_t)atoi(buffer);
  527. _read_state++;
  528. }
  529. memset(buffer, 0, sizeof(char)*LINE_BUFFER_SIZE);
  530. input_idx=0;
  531. continue;
  532. }
  533. buffer[input_idx] = ch;
  534. input_idx++;
  535. if (input_idx >= LINE_BUFFER_SIZE) {
  536. input_idx = LINE_BUFFER_SIZE-1;
  537. buffer[LINE_BUFFER_SIZE-1] = 0;
  538. }
  539. }
  540. fclose(fp);
  541. if (_read_state < 7) {
  542. return -2;
  543. }
  544. return 0;
  545. }
  546. */
  547. int get_server_desc(char *desc, int len) {
  548. char svrname[LINE_BUFFER_SIZE];
  549. FILE *f;
  550. if (!desc) {
  551. return -1;
  552. }
  553. if (len <= 0) {
  554. return -1;
  555. }
  556. f = fopen(SERVER_DESC_FILE, "rb");
  557. if (f) {
  558. fgets(svrname, LINE_BUFFER_SIZE, f);
  559. svrname[LINE_BUFFER_SIZE - 1] = '\0';
  560. strip_crlf(svrname);
  561. strncpy(desc, svrname, len);
  562. desc[len - 1] = '\0';
  563. return 0;
  564. }
  565. return -1;
  566. }
  567. int get_field(char *dest, char *src, int dest_len, int *eol_flag) {
  568. int i,j;
  569. int done = 0;
  570. int eol = 0;
  571. i = j = 0;
  572. while ( ! done ) {
  573. switch(src[i]) {
  574. case '\0': // If we've hit the end of the input line
  575. case '\n':
  576. case '\r':
  577. // cap off our destination string if there is room
  578. //
  579. if (j < dest_len) {
  580. dest[j++] = '\0';
  581. }
  582. // set our internal End Of Line flag
  583. //
  584. eol = 1;
  585. // set the done flag so we break out of the while
  586. //
  587. done = 1;
  588. break;
  589. // If we have hit a record boundary
  590. //
  591. case '\t':
  592. // cap off our input line
  593. //
  594. if (j < dest_len) {
  595. dest[j++] = '\0';
  596. }
  597. // Advance past this input character
  598. //
  599. i++;
  600. // flag us as done
  601. //
  602. done = 1;
  603. break;
  604. // otherwise (for normal characters) just copy them if there is space
  605. //
  606. default:
  607. if (j < dest_len) {
  608. dest[j++] = src[i];
  609. }
  610. // and advance past them
  611. //
  612. i++;
  613. break;
  614. }
  615. }
  616. // If we have filled our line to capacity
  617. //
  618. if ( j == dest_len ) {
  619. // Truncate it by 1 character to fit the terminating NUL
  620. //
  621. dest[dest_len - 1] = '\0';
  622. }
  623. // If the user has passed us a place to store our EOL flag,
  624. //
  625. if( eol_flag != NULL ) {
  626. // store it there
  627. //
  628. *eol_flag = eol;
  629. }
  630. // Return the index of the next character to be consumed.
  631. //
  632. return i;
  633. }
  634. // magic hash function hashes english strings well enough for our needs
  635. //
  636. unsigned long long stringhash(char *string) {
  637. unsigned long long hash = 5381;
  638. int c;
  639. while ((c = *string++)) {
  640. /* hash * 33 + c */
  641. hash = ((hash << 5) + hash) + c;
  642. }
  643. return hash;
  644. }
  645. int strip_crlf(char *buffer) {
  646. char *src,*dst;
  647. int count=0;
  648. // Set both our source and destination pointers to the buffer in question
  649. //
  650. src=dst=buffer;
  651. // While we still have unprocessed buffer bytes
  652. //
  653. while(*src) {
  654. // If we encounter a CR or LF character
  655. //
  656. if((*src == '\r') || (*src == '\n')) {
  657. // If the NEXT character is not another EOL character or a terminating nul
  658. //
  659. if( (src[1] != '\0') && (src[1] != '\r') && (src[1] != '\n') ) {
  660. src++;
  661. // replace the CR or LF with a space.
  662. //
  663. *dst++ = ' ';
  664. count++;
  665. continue;
  666. }
  667. // On the other hand, if what comes next is EOL or end of string,
  668. //
  669. else {
  670. // just trim this character
  671. //
  672. src++;
  673. continue;
  674. }
  675. }
  676. // If this character isn't one of the special ones, just copy it.
  677. //
  678. *dst++ = *src++;
  679. count++;
  680. }
  681. // Copy the terminating NUL
  682. //
  683. *dst++ = *src++;
  684. return count;
  685. }
  686. int open_rs232_device(char *devname, int custom_baud, int linemode) {
  687. struct termios tty={0};
  688. int retval;
  689. int fd;
  690. // Open the specified character device READ/WRITE and not as a Controlling TTY
  691. //
  692. fd = open(devname, O_RDWR | O_NOCTTY);
  693. if (fd < 0) {
  694. #ifdef COMMON_PRINT_WARNING
  695. fprintf(stderr, "Warning: Cannot open TTY %s\n", devname);
  696. #endif
  697. return -1;
  698. }
  699. // Try and fetch the TTY properties of the device
  700. //
  701. retval = ioctl(fd, TCGETS, &tty);
  702. if (retval) {
  703. #ifdef COMMON_PRINT_WARNING
  704. fprintf(stderr, "Warning: Cannot get TTY attributes on %s. Not a TTY?\n", devname);
  705. #endif
  706. close(fd);
  707. return -1;
  708. }
  709. if (custom_baud > 0) {
  710. tty.c_cflag = custom_baud | CS8 | CREAD | CLOCAL;
  711. }
  712. else {
  713. tty.c_cflag = DEFAULT_BAUD | CS8 | CREAD | CLOCAL;
  714. }
  715. if (linemode) {
  716. tty.c_iflag = IGNBRK;
  717. tty.c_oflag = 0;
  718. tty.c_lflag = ICANON;
  719. tty.c_line = 0;
  720. tty.c_cc[VMIN] = 1; // minimum one character read
  721. tty.c_cc[VTIME] = ACCUM_SECONDS * 10; // wait ACCUM_SECONDS without any further chars
  722. // before giving up on the arrival of a newline.
  723. // (VTIME is specified in deciseconds (who knows why...))
  724. tty.c_cc[VEOL] = '\n'; // allow a newline to release the buffer
  725. }
  726. else {
  727. tty.c_iflag = IGNBRK;
  728. tty.c_oflag = 0;
  729. tty.c_lflag = 0;
  730. tty.c_line = 0;
  731. tty.c_cc[VMIN] = 1;
  732. tty.c_cc[VTIME] = 5;
  733. }
  734. // try and plunk our desired settings down on the device
  735. //
  736. retval = ioctl(fd, TCSETS, &tty);
  737. if (retval) {
  738. #ifdef COMMON_PRINT_WARNING
  739. fprintf(stderr, "Warning: Cannot set TTY attributes on %s. Unsupported mode?\n", devname);
  740. #endif
  741. close(fd);
  742. return -1;
  743. }
  744. // flush the serial port buffers to clean up any detritus that has accumulated before we got here
  745. //
  746. tcflush(fd, TCIOFLUSH);
  747. return fd;
  748. }
  749. static int read_with_timeout(int fd, void *buffer, int n, int timeout) {
  750. int retval;
  751. struct pollfd fds[1];
  752. fds[0].fd = fd;
  753. fds[0].events = POLLIN;
  754. retval = poll(fds, 1, timeout);
  755. if (retval > 0) {
  756. return read(fd, buffer, n);
  757. }
  758. else {
  759. return retval;
  760. }
  761. }
  762. static int init_device(int fd, device_test_vector *vec, char *diag) {
  763. char buffer[1024] = {0};
  764. int i;
  765. int retval;
  766. int len;
  767. char *trav;
  768. int timeout = DEVICE_TEST_TIMEOUT;
  769. if (vec->init_timeout > 0) {
  770. timeout = vec->init_timeout;
  771. }
  772. // If we were given an init string
  773. //
  774. if (vec->init_string != NULL) {
  775. // calculate how long it is
  776. //
  777. len = strlen(vec->init_string);
  778. // send it on its way
  779. //
  780. retval = write(fd, vec->init_string, len);
  781. // if that didn't work
  782. //
  783. if (retval != len) {
  784. // complain and fail
  785. //
  786. if (diag) {
  787. snprintf(diag, DIAG_BUFFER_SIZE, "Cannot write init string to device.");
  788. }
  789. return -1;
  790. }
  791. }
  792. i = 0;
  793. while (i < vec->n_reply_lines) {
  794. // Ask the kernel for a line from the TTY
  795. //
  796. retval = read_with_timeout(fd, buffer, sizeof(buffer), timeout);
  797. // If we DID read something from the device, make sure it is correct
  798. //
  799. if(retval > 0) {
  800. buffer[retval] = '\0';
  801. strip_crlf(buffer);
  802. trav = buffer;
  803. // Skip any garbage before the start character
  804. //
  805. while (*trav && (*trav != '/')) {
  806. trav++;
  807. }
  808. if (*trav == '\0') {
  809. continue; // ignore blank lines
  810. }
  811. if ( (trav[0] == '/') && (trav[1] == '?') && (trav[2] == ':') ) {
  812. // ignore device ID lines
  813. //
  814. continue;
  815. }
  816. // The order of these tests in importand. Short circuit keeps us from
  817. // dereferencing expected_reply_lines if the first test fails
  818. //
  819. // If we have a pattern to test against
  820. //
  821. if ( (vec->reply_strings != NULL) && (vec->reply_strings[i] != NULL) ) {
  822. if (strcmp(trav, vec->reply_strings[i])) {
  823. if (diag) {
  824. snprintf(diag, DIAG_BUFFER_SIZE, "Read init reply line %d from device, expected \"%s\" but got \"%s\"", i, vec->reply_strings[i], trav);
  825. }
  826. return -1;
  827. }
  828. }
  829. }
  830. // If we DIDN'T read anything from the device...
  831. //
  832. else {
  833. // Complain
  834. //
  835. if (diag) {
  836. snprintf(diag, DIAG_BUFFER_SIZE, "Reading init reply from device timed out waiting for line %d", i);
  837. }
  838. // And fail
  839. //
  840. return -1;
  841. }
  842. i++;
  843. }
  844. return 0;
  845. }
  846. int test_and_init_device(int fd, device_test_vector *vec, char *diag) {
  847. char buffer[DEV_INIT_BUFFER_SIZE] = {0};
  848. char module_id[DEV_INIT_BUFFER_SIZE] = {0};
  849. int tries = DEVICE_TEST_TRIES;
  850. int timeout = DEVICE_TEST_TIMEOUT;
  851. int retval;
  852. char *trav;
  853. if (vec == NULL) {
  854. return -1;
  855. }
  856. if (vec->dev_id == NULL) {
  857. return -1;
  858. }
  859. if (vec->init_tries > 0) {
  860. tries = vec->init_tries;
  861. }
  862. if (vec->init_timeout > 0) {
  863. timeout = vec->init_timeout;
  864. }
  865. // We want to iterate through DEVICE_TEST_TRIES tries at getting a valid line from the device
  866. //
  867. do {
  868. // Send a CR to stimulate the device to spit out its help message
  869. //
  870. write(fd,"\r", 1);
  871. // Ask the kernel for a line from the TTY
  872. //
  873. retval = read_with_timeout(fd, buffer, sizeof(buffer), timeout);
  874. // If we actually got a line of data
  875. //
  876. if (retval > 0) {
  877. buffer[retval] = '\0';
  878. strip_crlf(buffer);
  879. // Start examining our buffer
  880. //
  881. trav = buffer;
  882. // Skip any garbage before the start character
  883. //
  884. while (*trav && (*trav != '/')) {
  885. trav++;
  886. }
  887. // See if it is our Device ID / help line...
  888. //
  889. if ( (trav[0] == '/') && (trav[1] == '?') && (trav[2] == ':') ) {
  890. // Skip the header and go to the body
  891. //
  892. trav += 3;
  893. // Look for our module ID string
  894. //
  895. retval = sscanf(trav, " ?=%s", module_id);
  896. if (retval < 1) {
  897. // Look for our module ID string without leading space
  898. //
  899. retval = sscanf(trav, "?=%s", module_id);
  900. }
  901. // If we have found id
  902. //
  903. if (retval == 1) {
  904. // See if it is the correct one
  905. //
  906. if (!strcmp(module_id, vec->dev_id)) {
  907. // If so, pass on our diagnostic message if we have a place to
  908. //
  909. if (diag) {
  910. snprintf(diag, DIAG_BUFFER_SIZE, "Device connected OK");
  911. }
  912. return init_device(fd, vec, diag); // Perform initialization and return the status of that operation
  913. }
  914. // Otherwise, if it is NOT the one we are expecting
  915. //
  916. else {
  917. // Complain if we have a place to
  918. //
  919. if (diag) {
  920. snprintf(diag, DIAG_BUFFER_SIZE, "Device present: Expecting: \"%s\" Got: \"%s\"", vec->dev_id, module_id);
  921. }
  922. return -2; // Return a distinct failure code
  923. }
  924. }
  925. }
  926. // If we DIDN'T get the line we were looking for, pretend it was blank so we'll try again...
  927. //
  928. else {
  929. // This pretends the received line was black.
  930. //
  931. retval = 0;
  932. }
  933. // if we got 0 bytes or EINTR from the alarm firing
  934. //
  935. }
  936. // While we still have tries and a previous try didn't work
  937. //
  938. } while ( (retval <= 0) && ( --tries > 0) );
  939. if (diag) {
  940. snprintf(diag, DIAG_BUFFER_SIZE, "Could not get reply from device");
  941. }
  942. return -1;
  943. }
  944. // ========================================================================================================
  945. // ------------------------------- WATCHDOG TIMER and other SIGNAL HANDLERS -------------------------------
  946. // ========================================================================================================
  947. // volatile int hup_request_status = 0;
  948. //
  949. volatile sig_atomic_t hup_request_status = 0;
  950. void request_hup(char *fmt, ...) {
  951. va_list ap;
  952. hup_request_status = 1;
  953. va_start(ap, fmt);
  954. vprintf(fmt, ap);
  955. va_end(ap);
  956. }
  957. // Our signal handlers and standard message handlers will OR these bits into exit_request_status
  958. //
  959. volatile int exit_request_status = 0;
  960. static int exit_signal_counter = 0;
  961. void request_polite_exit(int reason, char *fmt, ...) {
  962. va_list ap;
  963. exit_request_status |= reason;
  964. if (reason) {
  965. exit_signal_counter++;
  966. }
  967. if (exit_request_status & EXIT_REQUEST_CRASH) {
  968. va_start(ap, fmt);
  969. vsyslog(LOG_ERR, fmt, ap);
  970. va_end(ap);
  971. exit(EX_SOFTWARE);
  972. }
  973. if (exit_signal_counter >= MAX_POLITE_EXIT_REQUESTS) {
  974. va_start(ap, fmt);
  975. vsyslog(LOG_NOTICE, fmt, ap);
  976. va_end(ap);
  977. exit(SIGTERM);
  978. }
  979. }
  980. static void watchdog_handler(int signum, siginfo_t *info, void *data) {
  981. request_polite_exit(EXIT_REQUEST_CRASH, "Watchdog timer has expired!");
  982. }
  983. static void term_int_handler(int signum, siginfo_t *info, void *data) {
  984. request_polite_exit(EXIT_REQUEST_INT_TERM, "Received signal %d", signum);
  985. }
  986. static void hard_crash_handler(int signum, siginfo_t *info, void *data) {
  987. switch(signum) {
  988. case SIGSEGV:
  989. request_polite_exit(EXIT_REQUEST_CRASH, "Segmentation fault at virtual address %p", info->si_addr);
  990. break;
  991. case SIGILL:
  992. request_polite_exit(EXIT_REQUEST_CRASH, "Illegal instruction at virtual address %p", info->si_addr);
  993. break;
  994. case SIGFPE:
  995. request_polite_exit(EXIT_REQUEST_CRASH, "Floating point exception at virtual address %p", info->si_addr);
  996. break;
  997. case SIGBUS:
  998. request_polite_exit(EXIT_REQUEST_CRASH, "SIGBUS (hardware error!) at address %p", info->si_addr);
  999. break;
  1000. default:
  1001. request_polite_exit(EXIT_REQUEST_CRASH, "Caught Signal %d", signum);
  1002. break;
  1003. }
  1004. }
  1005. void configure_signal_handlers(char *procname) {
  1006. struct sigaction sa = {{0}};
  1007. openlog(procname, LOG_CONS | LOG_PERROR, LOG_USER);
  1008. #ifdef USE_WATCHDOG_ALARM
  1009. sa.sa_sigaction = watchdog_handler;
  1010. sa.sa_flags = SA_SIGINFO;
  1011. sigfillset(&sa.sa_mask);
  1012. sigaction(SIGALRM, &sa, NULL);
  1013. RESET_WATCHDOG();
  1014. #endif
  1015. // Install our "boy did we ever fuck up this time" signal handler
  1016. // to trap segmentation faults, illegal instructions, divides by zero,
  1017. // and things like RAM chips popping off a running board (SIGBUS).
  1018. //
  1019. sa.sa_sigaction = hard_crash_handler;
  1020. sa.sa_flags = SA_SIGINFO;
  1021. sigaction(SIGSEGV, &sa, NULL);
  1022. sigaction(SIGILL, &sa, NULL);
  1023. sigaction(SIGFPE, &sa, NULL);
  1024. sigaction(SIGBUS, &sa, NULL);
  1025. // Install our polite exit handler...
  1026. //
  1027. sa.sa_sigaction = term_int_handler;
  1028. sa.sa_flags = SA_SIGINFO | SA_RESTART; // Allow interrupted I/O calls to finish to facilitate clean exit
  1029. sigaction(SIGTERM, &sa, NULL);
  1030. sigaction(SIGINT, &sa, NULL);
  1031. }
  1032. // ------------------