void shell_mode() { char arriving_char; char c; print_initial_prompt_lines(); while (1) { if (current_vt == CHAT_VT && serial_received()) { arriving_char = read_serial(); parse_arriving_char(arriving_char); } while ((c = getc()) == -1) ; if (current_vt == CHAT_VT) { parse_departing_char(c); } else { parse_command_char(c); } refresh_screen(); } }
void usbutil_list(void) { const struct usb_bus *bus; for (bus = usb_get_busses(); bus; bus = bus->next) { struct usb_device *dev; int busnum = atoi(bus->dirname); printc("Devices on bus %03d:\n", busnum); for (dev = bus->devices; dev; dev = dev->next) { int devnum = atoi(dev->filename); char serial[128]; printc(" %03d:%03d %04x:%04x %s", busnum, devnum, dev->descriptor.idVendor, dev->descriptor.idProduct, device_help(dev)); if (!read_serial(dev, serial, sizeof(serial))) printc(" [serial: %s]\n", serial); else printc("\n"); } } }
struct usb_device *usbutil_find_by_id(int vendor, int product, const char *requested_serial) { struct usb_bus *bus; for (bus = usb_get_busses(); bus; bus = bus->next) { struct usb_device *dev; for (dev = bus->devices; dev; dev = dev->next) { if (dev->descriptor.idVendor == vendor && dev->descriptor.idProduct == product) { char buf[128]; if (!requested_serial || (!read_serial(dev, buf, sizeof(buf)) && !strcasecmp(requested_serial, buf))) return dev; } } } if(requested_serial) printc_err("usbutil: unable to find device matching " "%04x:%04x with serial %s\n", vendor, product, requested_serial); else printc_err("usbutil: unable to find a device matching " "%04x:%04x\n", vendor, product); return NULL; }
/*!***************************************************************************** ******************************************************************************* \note clear_serial \date Oct 2000 \remarks empties the serial buffer ******************************************************************************* Function Parameters: [in]=input,[out]=output \param[in] fd : file descriptor ******************************************************************************/ int clear_serial(int fd) { int n_bytes; int n_bytes_read; char buf[10000]; while(TRUE) { n_bytes = check_serial(fd); if (n_bytes > 10000) { n_bytes = 10000; n_bytes_read = read_serial(fd,n_bytes,buf); } else { n_bytes_read = read_serial(fd,n_bytes,buf); break; } } return TRUE; }
int at_cmd (struct serial *s) { char buf [32]; ssize_t r; if (write_serial (s, "AT\r", 3) == -1) error (1, 0, "could not write"); memset (buf, 0, sizeof (buf)); r = read_serial (s, buf, sizeof (buf) - 1); if (r < 0) return -1; else if (r == 0) return -1; if (!strcmp (buf, "OK\r")) return 0; return (-1); }
int main (int argc, char **argv) { int i,j, number_bytes; unsigned char buffer[512]; /* Check inputs parameters */ if (argc < 2) { fprintf (stderr, "./bd970_rx <serial_port_path>\n"); return ERROR; } /* Open serial port*/ printf ("Connecting to BD970_EMU [%s].......", argv[1]); /* Argv[1] is the normal "/dev/ttyUSB0" driver description file on Linux system*/ int fd = init_serial (argv[1]); if (fd != ERROR) { /* Print text information confirming that the connection was stabilize */ printf ("OK.\n"); for (i=0; i < 10; ++i) { sleep(1.0); number_bytes = read_serial(fd, buffer, 512); printf("Read %d bytes from fd (%d) \n", number_bytes, fd); if (number_bytes != ERROR) { for (j=0; j < number_bytes; j++) { fprintf (stdout, "%c", buffer[j]); } } } close(fd); } //End if of file description (serial port) return OK; }
/* Generates a new serial number for a certificate. */ long get_serial() { long serial = read_serial(); if (serial == INVALID_SERIAL) { /* Read failed */ /* Generate a new serial */ RAND_pseudo_bytes((unsigned char*)&serial, sizeof(serial)); serial &= 0x0FFFFFFF; /* Fix sign and allow loads of serials before an overflow occurs */ RAND_cleanup(); write_serial(serial); } else write_serial(++serial); /* Update serial file */ return serial; }
void kernel_main(void* mem) { init_serial(); terminal_init(); terminal_writeln("Kernel Startup."); pool = tlsf_create((void*)0x2000000, 32768); //terminal_writehexln(pool); lua_State* L = lua_newstate(l_alloc, pool); lua_pushcfunction(L, l_Print); lua_setglobal(L, "print"); #define BUFFER_SIZE 128 #if 0 char test[BUFFER_SIZE]; test[BUFFER_SIZE-1] = 0; int i ; for(i = 0; i < BUFFER_SIZE-1; ++i) { test[i] = read_serial(); if(test[i] == 0 || test[i] == '\r' || test[i] == '\n') { break; } if(!IsValid(test[i])) { i--; continue; } } test[i] = 0; terminal_write("Read "); terminal_writehexln(i); terminal_writeln(test); #else char* test = "print(1 + 2)"; #endif size_t len = strlen(test); if(luaL_loadbufferx(L, test, len, "Sample", 0) != 0) { terminal_writeln(lua_tostring(L, -1)); } if(lua_pcall(L, 0, LUA_MULTRET, 0) != 0) { terminal_writeln(lua_tostring(L, -1)); } terminal_writeln("Finished"); }
size_t write_verify_read(void* com_port, unsigned char* in, size_t inlen, unsigned char* out, size_t outlen) { size_t ret; unsigned char buf[4096]; ret = write_serial(com_port, in, inlen); if(ret != inlen) { return (unsigned int)-1; } ret = read_serial(com_port, buf, inlen+outlen); if(ret < inlen || memcmp(in, buf, inlen)) { printf("%s: Read %Ix bytes\n", __FUNCTION__, ret); printbuffer(buf, ret); return (unsigned int)-1; } //printbuffer(buf, ret); memmove(out, buf+inlen, ret-inlen); return ret-inlen; }
/*!***************************************************************************** ******************************************************************************* \note read_frame \date Oct 2000 \remarks Reads a frame from the serial port. Note: all date comes as ASCII characters!!! Weird ..... The following characters demark the frame: start of frame : ^ end of frame : \n start of camera 2: / end of channel : ; end of number : space For the following readings, the NewtonLabs hardware needs to be set to: - report frame counter (otherwise this function reports errors) - only report x and y of the blobs, no other data (this could be changed if needed) - only allow one object per channel (can be improved in the future, too, but requires to use temporal reasoning to avoid confusing two objects with the same color, and also occlusions) Currently, blob numbering coincides with the the color channel number. Thus, an empty frame would look like: 1213;;;;/;;;;/ A valid frame with one blob would looke like: 4475460 356 269;;;;/238 174;;;;/ ******************************************************************************* Function Parameters: [in]=input,[out]=output none returns the number of bytes read ******************************************************************************/ static int read_frame(void) { int i,j; char *start_camera[N_CAMERAS+1]; char *startbuf; int rc; char buffer[1000]; char store_char; char *cptr; while (TRUE) { if ((rc=check_serial(serial_fd)) > 0) { rc=read_serial(serial_fd,rc,buffer); if (buffer[rc-1]=='\n') break; else printf("Last character was not CR in LINE mode serial connection\n"); } nanosleep(&nsleep,NULL); } /* where is the start of camera 2 data: at the first "/" */ start_camera[CAMERA_2] = strchr(buffer,'/'); if (start_camera[CAMERA_2]==NULL) { printf("Invalid Frame: / character not found\n"); printf("Frame = >%s<\n",buffer); return FALSE; } *(start_camera[CAMERA_2]) = '\0'; ++start_camera[CAMERA_2]; /* where is the start of camera 1 data: more tricky: it is before the first ";", and after the first space, if blob1 exists */ cptr = strchr(buffer,';'); start_camera[CAMERA_1] = strchr(buffer,' '); if (start_camera[CAMERA_1]==NULL) start_camera[CAMERA_1]=cptr; else if (cptr<start_camera[CAMERA_1]) start_camera[CAMERA_1]=cptr; store_char = *(start_camera[CAMERA_1]); *(start_camera[CAMERA_1])='\0'; /* read the frame counter and the first blob of camera 1 */ if (sscanf(buffer,"%d",&the_frame.counter) == 0) { printf("Invalid Frame: frame counter not found\n"); return FALSE; } *(start_camera[CAMERA_1])=store_char; /* loop through both cameras and parse the data */ for (i=1; i<=N_CAMERAS; ++i) { startbuf=start_camera[i]; for (j=1; j<=MAX_BLOBS; ++j) { /* find the next semicolon */ cptr = strchr(startbuf,';'); if (cptr==NULL) break; *cptr = '\0'; /* read the data */ if (sscanf(startbuf,"%d %d",&the_frame.blobinfo[j][i].x, &the_frame.blobinfo[j][i].y) != 2) the_frame.blobinfo[j][i].status = FALSE; else the_frame.blobinfo[j][i].status = TRUE; startbuf = cptr+1; } } return TRUE; }
/*!***************************************************************************** ******************************************************************************* \note acquire_blobs \date Oct 2000 \remarks read the current information about the blobs ******************************************************************************* Function Parameters: [in]=input,[out]=output \param[in] blobs : array of blob structures ******************************************************************************/ int acquire_blobs(Blob2D blobs[][2+1]) { int i,j; int rc; char buffer[2]; int start_time = 0; /* reset all the blobs to be non existent */ for (i = 1; i<=MAX_BLOBS; ++i) { the_frame.blobinfo[i][CAMERA_1].status = FALSE; the_frame.blobinfo[i][CAMERA_2].status = FALSE; } start_time = (int) time(NULL); while( TRUE ) { /* Wait for data in the serial buffer */ if (check_serial(serial_fd) > 0) { if (read_serial(serial_fd,1,buffer)==1) if (buffer[0] == '^') /* this is the start of frame character */ break; } nanosleep(&nsleep,NULL); if (abs(start_time - (int) time(NULL)) > 10) { printf("Error: Timeout when reading from vision hardware\n"); printf("Switch to no-hardware mode\n"); no_hardware_flag = TRUE; return TRUE; } } /* now we are at the beginning of a frame */ last_counter = the_frame.counter; /* read the entire frame */ rc = read_frame(); ++frame_counter; if (vision_servo_calls == 0) { /* synchronize the v->frame_counter and the_frame.counter */ frame_counter = the_frame.counter; last_counter = frame_counter - 1; } ++count_all_frames; /* frame_counter and the_frame.counter should always coincide, anything else counts as a lost frame */ count_lost_frames += abs(frame_counter - the_frame.counter); frame_counter = the_frame.counter; /* was the frame counter advanced and was read_frame successful ?*/ if ( (the_frame.counter == last_counter + 1) && rc ) { ; } else { /* reset all the blobs to be non existent */ for (i = 1; i<=MAX_BLOBS; ++i) { the_frame.blobinfo[i][CAMERA_1].status = FALSE; the_frame.blobinfo[i][CAMERA_2].status = FALSE; } ++count_lost_frames; } /* copy the data into the global structures */ for (i=1; i<=MAX_BLOBS; ++i) { /* if (the_frame.blobinfo[i][CAMERA_1].status && the_frame.blobinfo[i][CAMERA_2].status) { blobs[i][CAMERA_1].status = blobs[i][CAMERA_2].status = TRUE; blobs[i][CAMERA_1].x[_X_] = the_frame.blobinfo[i][CAMERA_1].x; blobs[i][CAMERA_1].x[_Y_] = the_frame.blobinfo[i][CAMERA_1].y; blobs[i][CAMERA_2].x[_X_] = the_frame.blobinfo[i][CAMERA_2].x; blobs[i][CAMERA_2].x[_Y_] = the_frame.blobinfo[i][CAMERA_2].y; } else { blobs[i][CAMERA_1].status = blobs[i][CAMERA_2].status = FALSE; } */ if (the_frame.blobinfo[i][CAMERA_1].status) { blobs[i][CAMERA_1].status = TRUE; blobs[i][CAMERA_1].x[_X_] = the_frame.blobinfo[i][CAMERA_1].x; blobs[i][CAMERA_1].x[_Y_] = the_frame.blobinfo[i][CAMERA_1].y; } else { blobs[i][CAMERA_1].status = FALSE; } if (the_frame.blobinfo[i][CAMERA_2].status) { blobs[i][CAMERA_2].status = TRUE; blobs[i][CAMERA_2].x[_X_] = the_frame.blobinfo[i][CAMERA_2].x; blobs[i][CAMERA_2].x[_Y_] = the_frame.blobinfo[i][CAMERA_2].y; } else { blobs[i][CAMERA_2].status = FALSE; } } return TRUE; }
static inline int get_char(char *ch) { return read_serial(fd, 5000, ch, 1); }
int main(void) { init_serial(); initLCD(); initRadio(); unsigned char volume = getVolume(); // tune this bitch to 102.7 seek(FM, UP, 1); tuneStatus(); char lcdStr[33]; putsLCD("Radio!", LCD_SAMELINE); enum DisplayModes dispMode; int refresh = 0; while(1) { if(available_serial() >= 6) { char current = read_serial(); if(current != 128) { continue; } refresh = 1; // read the 4-bytes length long length = (long)read_serial() << 24; length |= (long)read_serial() << 16; length |= (long)read_serial() << 8; length |= (long)read_serial(); current = read_serial(); char opcode = (current & 0xE) >> 5; switch(opcode) { case TUNE: { enum Band band = current & 0x10 >> 4; char freq_b = read_serial(); int freq = convert_freq(band, freq_b); //tuneStation(band, freq); if(band == FM) { sprintf(lcdStr, "Tune FM: %d", freq); } else { sprintf(lcdStr, "Tune AM: %d", freq); } break; } case TUNE_PRESET: { enum Band band = current & 0x10 >> 4; int preset = current & 0x0F; //tunePreset(band, preset); if(band == FM) { sprintf(lcdStr, "Tune FM Preset: %d", preset); } else { sprintf(lcdStr, "Tune AM Preset: %d", preset); } } break; case VOLUME: { enum Direction dir = current & 0x10 >> 4; if(dir == UP) { ++volume; } else { --volume; } //setVolume(volume); sprintf(lcdStr, "Volume %d", volume); } break; case BAND: { enum Band band = current & 0x10 >> 4; //tuneStation(band, getLastStation(band)); if(band == FM) { sprintf(lcdStr, "Band set to FM"); } else { sprintf(lcdStr, "Band set to AM"); } } break; case SET_PRESET: { enum Band band = current & 0x10 >> 4; int preset = current & 0x0F; char freq_b = read_serial(); int freq = convert_freq(band, freq_b); //setPreset(band, preset, freq); if(band == FM) { sprintf(lcdStr, "Set FM Preset %d: %d", preset, freq); } else { sprintf(lcdStr, "Set AM Preset %d: %d", preset, freq); } break; } break; case NEXT: { enum Direction dir = current & 0x10 >> 4; enum Mode mode = current & 0x0C >> 2; if(mode == PRESET) { currentPreset += (dir) ? 1 : -1; if(currentPreset < 0) currentPreset = 5; if(currentPreset > 5) currentPreset = 0; //tunePreset(currentBand, currentPreset); sprintf(lcdStr, "Tune preset %d", currentPreset); } else if(mode == FREQUENCY) { int currentFreq = getFrequency(); currentFreq += (dir) ? 10 : -10; if(currentBand == FM) { if(currentFreq < FM_MIN_FREQ) currentFreq = FM_MAX_FREQ; if(currentFreq > FM_MAX_FREQ) currentFreq = FM_MIN_FREQ; sprintf(lcdStr, "Tune FM %d", currentFreq); } else { if(currentFreq < AM_MIN_FREQ) currentFreq = AM_MAX_FREQ; if(currentFreq > AM_MAX_FREQ) currentFreq = AM_MIN_FREQ; sprintf(lcdStr, "Tune AM %d", currentFreq); } tuneStation(currentBand, currentFreq); } else if(mode == SCAN) { //seek(currentBand, dir); sprintf(lcdStr, "Seek activated"); } } break; case DISPLAY: { dispMode = (current & 0x1C) >> 2; sprintf(lcdStr, "Set displayMode %d", dispMode); } break; } } if(refresh) { refresh = 0; clearLCD(); putsLCD(lcdStr, LCD_NEXTLINE); LCD_DELAY(0xFFFF); LCD_DELAY(0xFFFF); LCD_DELAY(0xFFFF); } }
int acquire_blobs(Blob2D blobs[][2+1]) { int i,j,r,m; int rc; static char buffer[MAX_CHARS]; static int n_buffer = 0; char buffer2[MAX_CHARS]; int n_buffer2 = 0; int count = 0; int run = TRUE; // reset all the blobs to be non existent for (i = 1; i<=max_blobs; ++i) { the_frame.blobinfo[i][CAMERA_1].status = FALSE; the_frame.blobinfo[i][CAMERA_2].status = FALSE; } while( run ) { // check for data in the serial port buffer if ( (rc=check_serial(serial_fd)) > 0) { if (rc > MAX_CHARS-n_buffer) { rc = MAX_CHARS-n_buffer; printf("buffer overflow\n"); } rc = read_serial(serial_fd,rc,&(buffer[n_buffer])); n_buffer += rc; } // look for a complete frame in the data for (j=n_buffer-1; j>=0; --j) { if (buffer[j] == '\n') // found the end of a frame at j break; } for (i=j; i>=0; --i) { if (buffer[i] == '^') { // found the beginning of a frame at i run = FALSE; break; } } if (i<0 && j>=0) { // no beginning of frame found despite end of frame for (r = j+1; r<n_buffer; ++r) buffer[r-(j+1)] = buffer[r]; n_buffer -= j+1; printf("discard early buffer\n"); } if (!run) break; taskDelay(ns2ticks(WAIT_IN_NS)); if (++count > 10000) { printf("Error: Timeout when reading from vision hardware\n"); printf("Switch to no-hardware mode\n"); no_hardware_flag = TRUE; return TRUE; } } // re-arrange the buffer for (r = i+1; r<j; ++r) buffer2[r-(i+1)] = buffer[r]; buffer2[j-(i+1)] = '\0'; n_buffer2 = j-(i+1); for (r = j+1; r<n_buffer; ++r) buffer[r-(j+1)] = buffer[r]; n_buffer -= j+1; /* now we are at the beginning of a frame */ last_counter = the_frame.counter; /* read the entire frame */ rc = read_frame(buffer2,n_buffer2); ++frame_counter; if (vision_servo_calls < 10) { /* synchronize the v->frame_counter and the_frame.counter */ frame_counter = the_frame.counter; last_counter = frame_counter - 1; } ++count_all_frames; /* frame_counter and the_frame.counter should always coincide, anything else counts as a lost frame */ count_lost_frames += abs(frame_counter - the_frame.counter); frame_counter = the_frame.counter; /* was the frame counter advanced and was read_frame successful ?*/ if ( (the_frame.counter == last_counter + 1) && rc ) { ; } else { /* reset all the blobs to be non existent */ for (i = 1; i<=max_blobs; ++i) { the_frame.blobinfo[i][CAMERA_1].status = FALSE; the_frame.blobinfo[i][CAMERA_2].status = FALSE; } ++count_lost_frames; } /* copy the data into the global structures */ for (i=1; i<=max_blobs; ++i) { /* if (the_frame.blobinfo[i][CAMERA_1].status && the_frame.blobinfo[i][CAMERA_2].status) { blobs[i][CAMERA_1].status = blobs[i][CAMERA_2].status = TRUE; blobs[i][CAMERA_1].x[_X_] = the_frame.blobinfo[i][CAMERA_1].x; blobs[i][CAMERA_1].x[_Y_] = the_frame.blobinfo[i][CAMERA_1].y; blobs[i][CAMERA_2].x[_X_] = the_frame.blobinfo[i][CAMERA_2].x; blobs[i][CAMERA_2].x[_Y_] = the_frame.blobinfo[i][CAMERA_2].y; } else { blobs[i][CAMERA_1].status = blobs[i][CAMERA_2].status = FALSE; } */ if (the_frame.blobinfo[i][CAMERA_1].status) { blobs[i][CAMERA_1].status = TRUE; blobs[i][CAMERA_1].x[_X_] = the_frame.blobinfo[i][CAMERA_1].x; blobs[i][CAMERA_1].x[_Y_] = the_frame.blobinfo[i][CAMERA_1].y; } else { blobs[i][CAMERA_1].status = FALSE; } if (the_frame.blobinfo[i][CAMERA_2].status) { blobs[i][CAMERA_2].status = TRUE; blobs[i][CAMERA_2].x[_X_] = the_frame.blobinfo[i][CAMERA_2].x; blobs[i][CAMERA_2].x[_Y_] = the_frame.blobinfo[i][CAMERA_2].y; } else { blobs[i][CAMERA_2].status = FALSE; } } return TRUE; }
/** * @brief openac main program * * @param argc number of arguments * @param argv pointer to the argument values */ int main(int argc, char **argv) { certificate_t *attr_cert = NULL; certificate_t *userCert = NULL; certificate_t *signerCert = NULL; private_key_t *signerKey = NULL; time_t notBefore = UNDEFINED_TIME; time_t notAfter = UNDEFINED_TIME; time_t validity = 0; char *keyfile = NULL; char *certfile = NULL; char *usercertfile = NULL; char *outfile = NULL; char *groups = ""; char buf[BUF_LEN]; chunk_t passphrase = { buf, 0 }; chunk_t serial = chunk_empty; chunk_t attr_chunk = chunk_empty; int status = 1; /* enable openac debugging hook */ dbg = openac_dbg; passphrase.ptr[0] = '\0'; openlog("openac", 0, LOG_AUTHPRIV); /* initialize library */ atexit(library_deinit); if (!library_init(NULL)) { exit(SS_RC_LIBSTRONGSWAN_INTEGRITY); } if (lib->integrity && !lib->integrity->check_file(lib->integrity, "openac", argv[0])) { fprintf(stderr, "integrity check of openac failed\n"); exit(SS_RC_DAEMON_INTEGRITY); } if (!lib->plugins->load(lib->plugins, lib->settings->get_str(lib->settings, "openac.load", PLUGINS))) { exit(SS_RC_INITIALIZATION_FAILED); } /* initialize optionsfrom */ options_t *options = options_create(); /* handle arguments */ for (;;) { static const struct option long_opts[] = { /* name, has_arg, flag, val */ { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'v' }, { "optionsfrom", required_argument, NULL, '+' }, { "quiet", no_argument, NULL, 'q' }, { "cert", required_argument, NULL, 'c' }, { "key", required_argument, NULL, 'k' }, { "password", required_argument, NULL, 'p' }, { "usercert", required_argument, NULL, 'u' }, { "groups", required_argument, NULL, 'g' }, { "days", required_argument, NULL, 'D' }, { "hours", required_argument, NULL, 'H' }, { "startdate", required_argument, NULL, 'S' }, { "enddate", required_argument, NULL, 'E' }, { "out", required_argument, NULL, 'o' }, { "debug", required_argument, NULL, 'd' }, { 0,0,0,0 } }; int c = getopt_long(argc, argv, "hv+:qc:k:p;u:g:D:H:S:E:o:d:", long_opts, NULL); /* Note: "breaking" from case terminates loop */ switch (c) { case EOF: /* end of flags */ break; case 0: /* long option already handled */ continue; case ':': /* diagnostic already printed by getopt_long */ case '?': /* diagnostic already printed by getopt_long */ case 'h': /* --help */ usage(NULL); status = 1; goto end; case 'v': /* --version */ printf("openac (strongSwan %s)\n", VERSION); status = 0; goto end; case '+': /* --optionsfrom <filename> */ { char path[BUF_LEN]; if (*optarg == '/') /* absolute pathname */ { strncpy(path, optarg, BUF_LEN); path[BUF_LEN-1] = '\0'; } else /* relative pathname */ { snprintf(path, BUF_LEN, "%s/%s", OPENAC_PATH, optarg); } if (!options->from(options, path, &argc, &argv, optind)) { status = 1; goto end; } } continue; case 'q': /* --quiet */ stderr_quiet = TRUE; continue; case 'c': /* --cert */ certfile = optarg; continue; case 'k': /* --key */ keyfile = optarg; continue; case 'p': /* --key */ if (strlen(optarg) >= BUF_LEN) { usage("passphrase too long"); goto end; } strncpy(passphrase.ptr, optarg, BUF_LEN); passphrase.len = min(strlen(optarg), BUF_LEN); continue; case 'u': /* --usercert */ usercertfile = optarg; continue; case 'g': /* --groups */ groups = optarg; continue; case 'D': /* --days */ if (optarg == NULL || !isdigit(optarg[0])) { usage("missing number of days"); goto end; } else { char *endptr; long days = strtol(optarg, &endptr, 0); if (*endptr != '\0' || endptr == optarg || days <= 0) { usage("<days> must be a positive number"); goto end; } validity += 24*3600*days; } continue; case 'H': /* --hours */ if (optarg == NULL || !isdigit(optarg[0])) { usage("missing number of hours"); goto end; } else { char *endptr; long hours = strtol(optarg, &endptr, 0); if (*endptr != '\0' || endptr == optarg || hours <= 0) { usage("<hours> must be a positive number"); goto end; } validity += 3600*hours; } continue; case 'S': /* --startdate */ if (optarg == NULL || strlen(optarg) != 15 || optarg[14] != 'Z') { usage("date format must be YYYYMMDDHHMMSSZ"); goto end; } else { chunk_t date = { optarg, 15 }; notBefore = asn1_to_time(&date, ASN1_GENERALIZEDTIME); } continue; case 'E': /* --enddate */ if (optarg == NULL || strlen(optarg) != 15 || optarg[14] != 'Z') { usage("date format must be YYYYMMDDHHMMSSZ"); goto end; } else { chunk_t date = { optarg, 15 }; notAfter = asn1_to_time(&date, ASN1_GENERALIZEDTIME); } continue; case 'o': /* --out */ outfile = optarg; continue; case 'd': /* --debug */ debug_level = atoi(optarg); continue; default: usage(""); status = 0; goto end; } /* break from loop */ break; } if (optind != argc) { usage("unexpected argument"); goto end; } DBG1(DBG_LIB, "starting openac (strongSwan Version %s)", VERSION); /* load the signer's RSA private key */ if (keyfile != NULL) { mem_cred_t *mem; shared_key_t *shared; mem = mem_cred_create(); lib->credmgr->add_set(lib->credmgr, &mem->set); shared = shared_key_create(SHARED_PRIVATE_KEY_PASS, chunk_clone(passphrase)); mem->add_shared(mem, shared, NULL); signerKey = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA, BUILD_FROM_FILE, keyfile, BUILD_END); lib->credmgr->remove_set(lib->credmgr, &mem->set); mem->destroy(mem); if (signerKey == NULL) { goto end; } DBG1(DBG_LIB, " loaded private key file '%s'", keyfile); } /* load the signer's X.509 certificate */ if (certfile != NULL) { signerCert = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509, BUILD_FROM_FILE, certfile, BUILD_END); if (signerCert == NULL) { goto end; } } /* load the users's X.509 certificate */ if (usercertfile != NULL) { userCert = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509, BUILD_FROM_FILE, usercertfile, BUILD_END); if (userCert == NULL) { goto end; } } /* compute validity interval */ validity = (validity)? validity : DEFAULT_VALIDITY; notBefore = (notBefore == UNDEFINED_TIME) ? time(NULL) : notBefore; notAfter = (notAfter == UNDEFINED_TIME) ? time(NULL) + validity : notAfter; /* build and parse attribute certificate */ if (userCert != NULL && signerCert != NULL && signerKey != NULL && outfile != NULL) { /* read the serial number and increment it by one */ serial = read_serial(); attr_cert = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509_AC, BUILD_CERT, userCert, BUILD_NOT_BEFORE_TIME, notBefore, BUILD_NOT_AFTER_TIME, notAfter, BUILD_SERIAL, serial, BUILD_IETF_GROUP_ATTR, groups, BUILD_SIGNING_CERT, signerCert, BUILD_SIGNING_KEY, signerKey, BUILD_END); if (!attr_cert) { goto end; } /* write the attribute certificate to file */ if (attr_cert->get_encoding(attr_cert, CERT_ASN1_DER, &attr_chunk)) { if (chunk_write(attr_chunk, outfile, 0022, TRUE)) { DBG1(DBG_APP, " written attribute cert file '%s' (%d bytes)", outfile, attr_chunk.len); write_serial(serial); status = 0; } else { DBG1(DBG_APP, " writing attribute cert file '%s' failed: %s", outfile, strerror(errno)); } } } else { usage("some of the mandatory parameters --usercert --cert --key --out " "are missing"); } end: /* delete all dynamically allocated objects */ DESTROY_IF(signerKey); DESTROY_IF(signerCert); DESTROY_IF(userCert); DESTROY_IF(attr_cert); free(attr_chunk.ptr); free(serial.ptr); closelog(); dbg = dbg_default; options->destroy(options); exit(status); }
// ------------------------------------------------------------------------------------------------ // Run the KISS virtual TNC void kiss_run(serial_t *serial_parms, spi_parms_t *spi_parms, arguments_t *arguments) // ------------------------------------------------------------------------------------------------ { static const size_t bufsize = RADIO_BUFSIZE; uint32_t timeout_value; uint8_t rx_buffer[bufsize], tx_buffer[bufsize]; uint8_t rtx_toggle; // 1:Tx, 0:Rx uint8_t rx_trigger; uint8_t tx_trigger; uint8_t force_mode; int rx_count, tx_count, byte_count, ret; uint64_t timestamp; struct timeval tp; set_serial_parameters(serial_parms, arguments); init_radio_int(spi_parms, arguments); memset(rx_buffer, 0, bufsize); memset(tx_buffer, 0, bufsize); radio_flush_fifos(spi_parms); verbprintf(1, "Starting...\n"); force_mode = 1; rtx_toggle = 0; rx_trigger = 0; tx_trigger = 0; rx_count = 0; tx_count = 0; radio_init_rx(spi_parms, arguments); // init for new packet to receive Rx radio_turn_rx(spi_parms); // Turn Rx on while(1) { byte_count = radio_receive_packet(spi_parms, arguments, &rx_buffer[rx_count]); // check if anything was received on radio link if (byte_count > 0) { rx_count += byte_count; // Accumulate Rx gettimeofday(&tp, NULL); timestamp = tp.tv_sec * 1000000ULL + tp.tv_usec; timeout_value = arguments->tnc_radio_window; force_mode = (timeout_value == 0); if (rtx_toggle) // Tx to Rx transition { tx_trigger = 1; // Push Tx } else { tx_trigger = 0; } radio_init_rx(spi_parms, arguments); // Init for new packet to receive rtx_toggle = 0; } byte_count = read_serial(serial_parms, &tx_buffer[tx_count], bufsize - tx_count); if (byte_count > 0) { tx_count += byte_count; // Accumulate Tx gettimeofday(&tp, NULL); timestamp = tp.tv_sec * 1000000ULL + tp.tv_usec; timeout_value = arguments->tnc_serial_window; force_mode = (timeout_value == 0); if (!rtx_toggle) // Rx to Tx transition { rx_trigger = 1; } else { rx_trigger = 0; } rtx_toggle = 1; } if ((rx_count > 0) && ((rx_trigger) || (force_mode))) // Send bytes received on air to serial { radio_wait_free(); // Make sure no radio operation is in progress radio_turn_idle(spi_parms); // Inhibit radio operations verbprintf(2, "Received %d bytes\n", rx_count); ret = write_serial(serial_parms, rx_buffer, rx_count); verbprintf(2, "Sent %d bytes on serial\n", ret); radio_init_rx(spi_parms, arguments); // Init for new packet to receive Rx radio_turn_rx(spi_parms); // Put back into Rx rx_count = 0; rx_trigger = 0; } if ((tx_count > 0) && ((tx_trigger) || (force_mode))) // Send bytes received on serial to air { if (!kiss_command(tx_buffer)) { radio_wait_free(); // Make sure no radio operation is in progress radio_turn_idle(spi_parms); // Inhibit radio operations (should be superfluous since both Tx and Rx turn to IDLE after a packet has been processed) radio_flush_fifos(spi_parms); // Flush result of any Rx activity verbprintf(2, "%d bytes to send\n", tx_count); if (tnc_tx_keyup_delay) { usleep(tnc_tx_keyup_delay); } radio_send_packet(spi_parms, arguments, tx_buffer, tx_count); radio_init_rx(spi_parms, arguments); // init for new packet to receive Rx radio_turn_rx(spi_parms); // put back into Rx } tx_count = 0; tx_trigger = 0; } if (!force_mode) { gettimeofday(&tp, NULL); if ((tp.tv_sec * 1000000ULL + tp.tv_usec) > timestamp + timeout_value) { force_mode = 1; } } radio_wait_a_bit(4); } }
void serial_read(uint16_t port, uint8_t *data, size_t length) { while(length--) { *data++ = read_serial(port); } }
int init_serial (char * port){ // Attempt to open port printf("Attempting to open %s...\n", port); if ((dev = fopen(port, "r+b"))){ int dev_fd = fileno(dev); // Set stream to not block when reading fcntl(dev_fd, F_SETFL, O_NONBLOCK); int flags = fcntl(dev_fd, F_GETFL); // Set baud rate to 34800 struct termios devConfig; tcgetattr(dev_fd, &devConfig); cfsetspeed(&devConfig, B38400); int baudSet = tcsetattr(dev_fd, TCSANOW, &devConfig); if (!(flags & O_NONBLOCK) || baudSet){ printf("ERROR: Failed to open port.\n"); return -1; } printf("%s opened successfully.\n", port); // Wait for handshake printf("Waiting for \"Hello\"... "); packet * in_shake; int i = 0; while ((!(in_shake = read_serial()) || ((in_shake->type) != PKT_HELLO)) && (i < 10)){ i++; sleep(1); } if(i == 10) return -1; printf("\"Hello\" received.\n"); int j = 0; while ((!(in_shake = read_serial()) || ((in_shake->type) != PKT_RDY)) && (j < 10)){ j++; say_hello(); sleep(1); } if(i == 10) return -1; printf("Mongol is Ready!\n"); return 0; } printf("ERROR: Failed to open port.\n"); return -1; }
/** * Sign a CRL */ static int sign_crl() { cred_encoding_type_t form = CERT_ASN1_DER; private_key_t *private = NULL; public_key_t *public = NULL; certificate_t *ca = NULL, *crl = NULL; crl_t *lastcrl = NULL; x509_t *x509; hash_algorithm_t digest = HASH_UNKNOWN; signature_params_t *scheme = NULL; char *arg, *cacert = NULL, *cakey = NULL, *lastupdate = NULL, *error = NULL; char *basecrl = NULL; char serial[512], *keyid = NULL; int serial_len; crl_reason_t reason = CRL_REASON_UNSPECIFIED; time_t thisUpdate, nextUpdate, date = time(NULL); time_t lifetime = 15 * 24 * 60 * 60; char *datetu = NULL, *datenu = NULL, *dateform = NULL; linked_list_t *list, *cdps; enumerator_t *enumerator, *lastenum = NULL; x509_cdp_t *cdp; chunk_t crl_serial = chunk_empty, baseCrlNumber = chunk_empty; chunk_t encoding = chunk_empty; bool pss = lib->settings->get_bool(lib->settings, "%s.rsa_pss", FALSE, lib->ns); list = linked_list_create(); cdps = linked_list_create(); while (TRUE) { switch (command_getopt(&arg)) { case 'h': goto usage; case 'g': if (!enum_from_name(hash_algorithm_short_names, arg, &digest)) { error = "invalid --digest type"; goto usage; } continue; case 'R': if (streq(arg, "pss")) { pss = TRUE; } else if (!streq(arg, "pkcs1")) { error = "invalid RSA padding"; goto usage; } continue; case 'c': cacert = arg; continue; case 'k': cakey = arg; continue; case 'x': keyid = arg; continue; case 'a': lastupdate = arg; continue; case 'l': lifetime = atoi(arg) * 24 * 60 * 60; if (!lifetime) { error = "invalid --lifetime value"; goto usage; } continue; case 'D': dateform = arg; continue; case 'F': datetu = arg; continue; case 'T': datenu = arg; continue; case 'z': serial_len = read_serial(arg, serial, sizeof(serial)); if (serial_len < 0) { snprintf(serial, sizeof(serial), "parsing certificate '%s' failed", arg); error = serial; goto error; } add_revoked(list, chunk_create(serial, serial_len), reason, date); date = time(NULL); reason = CRL_REASON_UNSPECIFIED; continue; case 's': { chunk_t chunk; int hex_len; hex_len = strlen(arg); if ((hex_len / 2) + (hex_len % 2) > sizeof(serial)) { error = "invalid serial"; goto usage; } chunk = chunk_from_hex(chunk_create(arg, hex_len), serial); serial_len = chunk.len; add_revoked(list, chunk_create(serial, serial_len), reason, date); date = time(NULL); reason = CRL_REASON_UNSPECIFIED; continue; } case 'b': basecrl = arg; continue; case 'u': INIT(cdp, .uri = strdup(arg), ); cdps->insert_last(cdps, cdp); continue; case 'r': if (streq(arg, "key-compromise")) { reason = CRL_REASON_KEY_COMPROMISE; } else if (streq(arg, "ca-compromise")) { reason = CRL_REASON_CA_COMPROMISE; } else if (streq(arg, "affiliation-changed")) { reason = CRL_REASON_AFFILIATION_CHANGED; } else if (streq(arg, "superseded")) { reason = CRL_REASON_SUPERSEDED; } else if (streq(arg, "cessation-of-operation")) { reason = CRL_REASON_CESSATION_OF_OPERATON; } else if (streq(arg, "certificate-hold")) { reason = CRL_REASON_CERTIFICATE_HOLD; } else { error = "invalid revocation reason"; goto usage; } continue; case 'd': date = atol(arg); if (!date) { error = "invalid date"; goto usage; } continue; case 'f': if (!get_form(arg, &form, CRED_CERTIFICATE)) { error = "invalid output format"; goto usage; } continue; case EOF: break; default: error = "invalid --signcrl option"; goto usage; } break; } if (!cacert) { error = "--cacert is required"; goto usage; } if (!cakey && !keyid) { error = "--cakey or --keyid is required"; goto usage; } if (!calculate_lifetime(dateform, datetu, datenu, lifetime, &thisUpdate, &nextUpdate)) { error = "invalid --this/next-update datetime"; goto usage; } ca = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509, BUILD_FROM_FILE, cacert, BUILD_END); if (!ca) { error = "parsing CA certificate failed"; goto error; } x509 = (x509_t*)ca; if (!(x509->get_flags(x509) & (X509_CA | X509_CRL_SIGN))) { error = "CA certificate misses CA basicConstraint / CRLSign keyUsage"; goto error; } public = ca->get_public_key(ca);