Example #1
0
objref_t
device_core_get_vdevice_impl(L4_ThreadId_t caller, L4_ThreadId_t *thrd, 
                            L4_ThreadId_t *notify, L4_Word_t mask, char * name,
                            idl4_server_environment *env)
{
    if (strcmp(name, "timer") == 0)
        return get_timer(caller, thrd, notify, mask);
    else if (strcmp(name, "serial") == 0) 
        return get_serial(caller, thrd, notify, mask);

#if 0  // andy -3
    else if (strcmp(name, "touchscreen") == 0)
        return get_touchscreen(caller, thrd, notify, mask);
    else if (strcmp(name, "rtc") == 0)
        return get_rtc(caller, thrd, notify, mask);
    else if (strcmp(name, "mtd") == 0){
        printf("getting MTD!\n");
        return get_mtd(caller, thrd, notify, mask);
    }
    else if (strcmp(name, "lcd") == 0)
        return get_lcd(caller, thrd, notify, mask);
#endif  // andy -3

    DEBUG_TRACE(3, "Uknown device for RealView: %s\n", name);
    return 0;
}
Example #2
0
char *monome_platform_get_dev_serial(const char *path) {
	glob_t gb;
	char *buf, *device;

	assert(path);

	if( *path == '/' )
		path++;

	path = strchr(path, '/') + 1;

	asprintf(&buf, FTDI_PATH "/*/%s", path);
	glob(buf, 0, NULL, &gb);
	free(buf);

	if( !gb.gl_pathc )
		goto err_nodevs;

	device = *gb.gl_pathv + (sizeof(FTDI_PATH) * sizeof(char));
	if( !(buf = strchr(device, ':')) )
		goto err_baddev;

	*buf = '\0';
	if( !(buf = get_serial(device)) )
		goto err_baddev;

	globfree(&gb);
	return buf;

err_baddev:
		globfree(&gb);
err_nodevs:
	return NULL;
}
Example #3
0
int main(int argc, char* argv[]) 
{
    char buf[128];

    strcpy(cfg.usb, "/dev/ttyUSB0");
    cfg.sr = 53333;
    debug_level = 3;

    if (parseOptions (argc, argv, &cfg) != 0) {
        return 255;
    }

    fprintf ( stderr, "Debug level:          %d\n" ,debug_level );
    fprintf ( stderr, "Sample rate:          %d\n" ,cfg.sr      );
    fprintf ( stderr, "Serial device:        %s\n" ,cfg.usb     );

    // Init SDR-IQ
    if (open_samples(cfg.usb, "66666667.0", buf)  ) {
        puts( "No  HiqSDR hardware detected" );
        return 255;
    } else {
        fprintf ( stderr, "%s\n", buf );

        init_receivers (&cfg);
        create_listener_thread();
        fprintf (stderr, "Serial: %s\n", get_serial());

        puts( "Press q <ENTER> to exit." );
        char ch;
        while((ch = getc(stdin)) != EOF) {
            if (ch == 'q') break;
        }
        return 0;
    }
}
Example #4
0
char *monome_platform_get_dev_serial(const char *path) {
	int bus, device;
	glob_t gb;
	char *buf;

	assert(path);

	if( *path == '/' )
		path++;

	path = strchr(path, '/') + 1;

	asprintf(&buf, FTDI_PATH "/*/%s", path);
	glob(buf, 0, NULL, &gb);
	free(buf);

	if( !gb.gl_pathc )
		return NULL;

	sscanf(*gb.gl_pathv, FTDI_PATH "/%d-%d", &bus, &device);
	globfree(&gb);

	if( (buf = get_serial(bus, device)) )
		return buf;
	return NULL;
}
Example #5
0
/***********************************************************************
 * Setup function
 **********************************************************************/
static uhd::usrp::multi_usrp::sptr setup_usrp_for_cal(std::string &args, std::string &subdev, std::string &serial)
{
    std::cout << std::endl;
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);

    // Configure subdev
    if (!subdev.empty())
    {
        usrp->set_tx_subdev_spec(subdev);
        usrp->set_rx_subdev_spec(subdev);
    }
    std::cout << "Running calibration for " << usrp->get_tx_subdev_name(0);
    serial = get_serial(usrp, "tx");
    std::cout << "Daughterboard serial: " << serial;

    //set the antennas to cal
    if (not uhd::has(usrp->get_rx_antennas(), "CAL") or not uhd::has(usrp->get_tx_antennas(), "CAL"))
        throw std::runtime_error("This board does not have the CAL antenna option, cannot self-calibrate.");
    usrp->set_rx_antenna("CAL");
    usrp->set_tx_antenna("CAL");

    //fail if daughterboard has no serial
    check_for_empty_serial(usrp);

    //set optimum defaults
    set_optimum_defaults(usrp);

    return usrp;
}
void onUSBCommTask(void *pvParameters)
{
        while (1) {
                if (USB_CDC_is_initialized())
                        process_msg(get_serial(SERIAL_USB), lineBuffer, BUFFER_SIZE);
                taskYIELD();
        }
}
/**
 * Writes the specified character to the serial port.
 * The call will block until the character is written.
 *
 * Lua Params:
 * port - the serial port to write
 *        (SERIAL_USB, SERIAL_GPS, SERIAL_TELEMETRY, SERIAL_WIRELESS, SERIAL_AUX)
 * char - the character to write.
 *
 * Lua Returns:
 * no return values (nil)
 *
 */
int Lua_WriteSerialChar(lua_State *L)
{
    if (lua_gettop(L) >= 2) {
        int serialPort = lua_tointeger(L,1);
        Serial *serial = get_serial(serialPort);
        if (serial) {
            char c = (char)lua_tonumber(L, 2);
            serial->put_c((char)c);
        }
    }
    return 0;
}
Example #8
0
objref_t
device_core_get_vdevice_impl(L4_ThreadId_t caller, L4_ThreadId_t *thrd, 
                            L4_ThreadId_t *notify, L4_Word_t mask, char * name,
                            idl4_server_environment *env)
{
    if (strcmp(name, "timer") == 0) return get_timer(caller, thrd, notify, mask);
    else if  (strcmp(name, "serial") == 0)  return get_serial(caller, thrd, notify, mask);
    else if  (strcmp(name, "rtc") == 0)  return get_rtc(caller, thrd, notify, mask);

    thrd->raw = 0;
    return 0;
}
/**
 * Writes the specified line to the serial port.
 * The call will block until all characters are written.
 *
 * Lua Params:
 * port - the serial port to write
 *        (SERIAL_USB, SERIAL_GPS, SERIAL_TELEMETRY, SERIAL_WIRELESS, SERIAL_AUX)
 * line - the string to write. A newline will automatically be added at the end.
 *
 * Lua Returns:
 * no return values (nil)
 *
 */
int Lua_WriteSerialLine(lua_State *L)
{
    if (lua_gettop(L) >= 2) {
        int serialPort = lua_tointeger(L,1);
        Serial *serial = get_serial(serialPort);
        if (serial) {
            const char * data = lua_tostring(L, 2);
            serial->put_s(data);
            serial->put_s("\n");
        }
    }
    return 0;
}
static void do_temp_sens_save_logical_numbers()
{
    uint8_t record[EEPROM_MAP_REC_SZ];
    uint8_t s;


    for(s = 0; s < N_TEMPERATURE_IN; s++)
    {
        get_serial( record, gTempSensorIDs[s] );
        uint8_t logNumber = gTempSensorLogicalNumber[s];
        record[SENS_ID_BYTE] = logNumber;
        temp_sens_write_record( logNumber, record );
    }
}
/**
 * Read a single newline terminated line from the specified serial port
 * Lua Params:
 * port - the serial port to initialize
 *        (SERIAL_USB, SERIAL_GPS, SERIAL_TELEMETRY, SERIAL_WIRELESS, SERIAL_AUX)
 * timeout - the read timeout, in ms.
 *
 * Lua Returns:
 * the character read, or nil if no characters received (receive timeout)
 *
 */
int Lua_ReadSerialLine(lua_State *L)
{
    size_t params = lua_gettop(L);
    if (!params)
        return 0;

    int serialPort = lua_tointeger(L,1);
    size_t timeout = params >= 2 ? lua_tointeger(L, 2) : DEFAULT_SERIAL_TIMEOUT;
    Serial *serial = get_serial(serialPort);
    if (serial) {
        serial->get_line_wait(g_tempBuffer, TEMP_BUFFER_LEN, timeout);
        lua_pushstring(L,g_tempBuffer);
        return 1;
    }
    return 0;
}
Example #12
0
/*
 * Store the SSL/TLS certificate after asking the user to accept/reject it.
 */
int
store_cert(X509 *cert)
{
	FILE *fd;
	char c, buf[LINE_MAX];
	char *certf;
	char *s;

	do {
		printf("(R)eject, accept (t)emporarily or "
		    "accept (p)ermanently? ");
		if (fgets(buf, LINE_MAX, stdin) == NULL)
			return -1;
		c = tolower((int)(*buf));
	} while (c != 'r' && c != 't' && c != 'p');

	if (c == 'r')
		return -1;
	else if (c == 't')
		return 0;

	certf = get_filepath("certificates");
	create_file(certf, S_IRUSR | S_IWUSR);
	fd = fopen(certf, "a");
	xfree(certf);
	if (fd == NULL)
		return -1;

	s = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
	fprintf(fd, "Subject: %s\n", s);
	xfree(s);
	s = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
	fprintf(fd, "Issuer: %s\n", s);
	xfree(s);
	s = get_serial(cert);
	fprintf(fd, "Serial: %s\n", s);
	xfree(s);

	PEM_write_X509(fd, cert);

	fprintf(fd, "\n");
	fclose(fd);

	return 0;
}
/**
 * Read a character from the specified serial port
 * Lua Params:
 * port - the serial port to initialize
 *        (SERIAL_USB, SERIAL_GPS, SERIAL_TELEMETRY, SERIAL_WIRELESS, SERIAL_AUX)
 * timeout - the read timeout, in ms.
 *
 * Lua Returns:
 * the character read, or nil if no characters received (receive timeout)
 *
 */
int Lua_ReadSerialChar(lua_State *L)
{
    int params = lua_gettop(L);
    if (!params)
        return 0;

    serial_id_t port = lua_tointeger(L,1);
    size_t timeout = params >= 2 ? lua_tointeger(L, 2) : DEFAULT_SERIAL_TIMEOUT;
    Serial *serial = get_serial(port);
    if (serial) {
        char c;
        if (serial->get_c_wait(&c, timeout)) {
            lua_pushnumber(L, c);
            return 1;
        }
    }
    return 0;
}
Example #14
0
File: main.c Project: monolli/ee109
int main(void){
	
	init_serial();
	init_ISR();				//initialize all functions, ports...
	init_led();
	init_buttons();
	init_temp();
	get_temp();
	ht=temp;
	lt=temp;
	init_lcd();

	while(1){
		get_temp();				//recieve the temp, convert and print
		led_on();				//turn the led functions on
		get_serial();			//recieve the temp through serial
	}
	
	return 0;
}
Example #15
0
/*
 * Print information about the SSL/TLS certificate.
 */
void
print_cert(X509 *cert, unsigned char *md, unsigned int *mdlen)
{
	unsigned int i;
	char *s;

	s = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
	printf("Server certificate subject: %s\n", s);
	xfree(s);

	s = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
	printf("Server certificate issuer: %s\n", s);
	xfree(s);

	s = get_serial(cert);
	printf("Server certificate serial: %s\n", s);
	xfree(s);

	printf("Server key fingerprint: ");
	for (i = 0; i < *mdlen; i++)
		printf(i != *mdlen - 1 ? "%02X:" : "%02X\n", md[i]);
}
Example #16
0
gpg_error_t cmd_serialno (assuan_context_t ctx, char *line)
{
	gpg_err_code_t error = GPG_ERR_GENERAL;
	char *serial = NULL;

	if (
		(error = get_serial(ctx, &serial)) != GPG_ERR_NO_ERROR
	) {
		goto cleanup;
	}

	if (serial != NULL) {
		char buffer[1024];

		sprintf(buffer, "%s 0", serial);

		if (
			(error = assuan_write_status (
				ctx,
				"SERIALNO",
				buffer
			)) != GPG_ERR_NO_ERROR
		) {
			goto cleanup;
		}
	}

	error = GPG_ERR_NO_ERROR;

cleanup:

	if (serial != NULL) {
		free(serial);
		serial = NULL;
	}

	return gpg_error (error);
}
Example #17
0
static int fastboot_oem_key_chk(void)
{
    int ret = B_OK;
    u32 chip_code = 0x0;
    char serial_number[SERIAL_NUMBER_SIZE+1] = {0};
    u64 key;
    char cal_serial_number[SERIAL_NUMBER_SIZE+1] = {0};

    /* Check for the unlock key */
    if(UNLOCK_KEY_SIZE != strlen(fb_unlock_key_str))
    {
        //fastboot_fail("Unlock key length is incorrect!");
        ret = ERR_UNLOCK_KEY_WRONG_LENGTH;
        return ret;
    }

    /* Get the device serial number */
    key = get_devinfo_with_index(13);
    key = (key << 32) | get_devinfo_with_index(12);
    chip_code = DRV_Reg32(APHW_CODE);
    if (key != 0)
        get_serial(key, chip_code, serial_number);
    else
        memcpy(serial_number, DEFAULT_SERIAL_NUM, SERIAL_NUMBER_SIZE);

    /* Calculate the serial number from the unlock key */
    sec_get_serial_number_from_unlock_key((u8 *)fb_unlock_key_str, UNLOCK_KEY_SIZE, (u8 *)cal_serial_number, SERIAL_NUMBER_SIZE);

    /* Compare the results */
    if(0 != memcmp(serial_number, cal_serial_number, SERIAL_NUMBER_SIZE))
    {
        //fastboot_fail("Unlock key code is incorrect!");
        ret = ERR_UNLOCK_WRONG_KEY_CODE;
        return ret;
    }

    return ret;
}
Example #18
0
int
pk_gencert(int argc, char *argv[])
{
	int rv;
	int opt;
	extern int	optind_av;
	extern char	*optarg_av;
	KMF_KEYSTORE_TYPE kstype = 0;
	char *subject = NULL;
	char *tokenname = NULL;
	char *dir = NULL;
	char *prefix = NULL;
	char *keytype = PK_DEFAULT_KEYTYPE;
	int keylen = PK_DEFAULT_KEYLENGTH;
	char *trust = NULL;
	char *lifetime = NULL;
	char *certlabel = NULL;
	char *outcert = NULL;
	char *outkey = NULL;
	char *format = NULL;
	char *serstr = NULL;
	char *altname = NULL;
	char *keyusagestr = NULL;
	char *ekustr = NULL;
	char *hashname = NULL;
	KMF_GENERALNAMECHOICES alttype = 0;
	KMF_BIGINT serial = { NULL, 0 };
	uint32_t ltime;
	KMF_HANDLE_T kmfhandle = NULL;
	KMF_ENCODE_FORMAT fmt = KMF_FORMAT_ASN1;
	KMF_KEY_ALG keyAlg = KMF_RSA;
	KMF_ALGORITHM_INDEX sigAlg = KMF_ALGID_SHA1WithRSA;
	boolean_t interactive = B_FALSE;
	char *subname = NULL;
	KMF_CREDENTIAL tokencred = { NULL, 0 };
	uint16_t kubits = 0;
	int altcrit = 0, kucrit = 0;
	EKU_LIST *ekulist = NULL;
	KMF_OID *curveoid = NULL; /* ECC */
	KMF_OID *hashoid = NULL;
	int y_flag = 0;

	while ((opt = getopt_av(argc, argv,
	    "ik:(keystore)s:(subject)n:(nickname)A:(altname)"
	    "T:(token)d:(dir)p:(prefix)t:(keytype)y:(keylen)"
	    "r:(trust)L:(lifetime)l:(label)c:(outcert)e:(eku)"
	    "K:(outkey)S:(serial)F:(format)u:(keyusage)C:(curve)"
	    "E(listcurves)h:(hash)")) != EOF) {

		if (opt != 'i' && opt != 'E' && EMPTYSTRING(optarg_av))
			return (PK_ERR_USAGE);

		switch (opt) {
			case 'A':
				altname = optarg_av;
				break;
			case 'i':
				if (interactive || subject)
					return (PK_ERR_USAGE);
				else
					interactive = B_TRUE;
				break;
			case 'k':
				kstype = KS2Int(optarg_av);
				if (kstype == 0)
					return (PK_ERR_USAGE);
				break;
			case 's':
				if (interactive || subject)
					return (PK_ERR_USAGE);
				else
					subject = optarg_av;
				break;
			case 'l':
			case 'n':
				if (certlabel)
					return (PK_ERR_USAGE);
				certlabel = optarg_av;
				break;
			case 'T':
				if (tokenname)
					return (PK_ERR_USAGE);
				tokenname = optarg_av;
				break;
			case 'd':
				if (dir)
					return (PK_ERR_USAGE);
				dir = optarg_av;
				break;
			case 'p':
				if (prefix)
					return (PK_ERR_USAGE);
				prefix = optarg_av;
				break;
			case 't':
				keytype = optarg_av;
				break;
			case 'u':
				keyusagestr = optarg_av;
				break;
			case 'y':
				if (sscanf(optarg_av, "%d",
				    &keylen) != 1) {
					cryptoerror(LOG_STDERR,
					    gettext("key length must be"
					    "a numeric value (%s)\n"),
					    optarg_av);
					return (PK_ERR_USAGE);
				}
				y_flag++;
				break;
			case 'r':
				if (trust)
					return (PK_ERR_USAGE);
				trust = optarg_av;
				break;
			case 'L':
				if (lifetime)
					return (PK_ERR_USAGE);
				lifetime = optarg_av;
				break;
			case 'c':
				if (outcert)
					return (PK_ERR_USAGE);
				outcert = optarg_av;
				break;
			case 'K':
				if (outkey)
					return (PK_ERR_USAGE);
				outkey = optarg_av;
				break;
			case 'S':
				serstr = optarg_av;
				break;
			case 'F':
				if (format)
					return (PK_ERR_USAGE);
				format = optarg_av;
				break;
			case 'e':
				ekustr = optarg_av;
				break;
			case 'C':
				curveoid = ecc_name_to_oid(optarg_av);
				if (curveoid == NULL) {
					cryptoerror(LOG_STDERR,
					    gettext("Unrecognized ECC "
					    "curve.\n"));
					return (PK_ERR_USAGE);
				}
				break;
			case 'E':
				/*
				 * This argument is only to be used
				 * by itself, no other options should
				 * be present.
				 */
				if (argc != 2) {
					cryptoerror(LOG_STDERR,
					    gettext("listcurves has no other "
					    "options.\n"));
					return (PK_ERR_USAGE);
				}
				show_ecc_curves();
				return (0);
			case 'h':
				hashname = optarg_av;
				hashoid = ecc_name_to_oid(optarg_av);
				if (hashoid == NULL) {
					cryptoerror(LOG_STDERR,
					    gettext("Unrecognized hash.\n"));
					return (PK_ERR_USAGE);
				}
				break;
			default:
				return (PK_ERR_USAGE);
		}
	}

	/* No additional args allowed. */
	argc -= optind_av;
	argv += optind_av;
	if (argc) {
		return (PK_ERR_USAGE);
	}

	if ((rv = kmf_initialize(&kmfhandle, NULL, NULL)) != KMF_OK) {
		cryptoerror(LOG_STDERR, gettext("Error initializing KMF\n"));
		return (PK_ERR_USAGE);
	}

	/* Assume keystore = PKCS#11 if not specified. */
	if (kstype == 0)
		kstype = KMF_KEYSTORE_PK11TOKEN;

	if ((kstype == KMF_KEYSTORE_NSS || kstype == KMF_KEYSTORE_PK11TOKEN)) {
		if (interactive && EMPTYSTRING(certlabel)) {
			(void) get_certlabel(&certlabel);
		}
		/* It better not be empty now */
		if (EMPTYSTRING(certlabel)) {
			cryptoerror(LOG_STDERR, gettext("A label must be "
			    "specified to create a self-signed certificate."
			    "\n"));
			return (PK_ERR_USAGE);
		}
	} else if (kstype == KMF_KEYSTORE_OPENSSL && EMPTYSTRING(outcert)) {
		cryptoerror(LOG_STDERR, gettext("A certificate filename must "
		    "be specified to create a self-signed certificate.\n"));
		return (PK_ERR_USAGE);
	}

	DIR_OPTION_CHECK(kstype, dir);

	if (format && (fmt = Str2Format(format)) == KMF_FORMAT_UNDEF) {
		cryptoerror(LOG_STDERR,
		    gettext("Error parsing format string (%s).\n"),
		    format);
		return (PK_ERR_USAGE);
	}

	if (Str2Lifetime(lifetime, &ltime) != 0) {
		cryptoerror(LOG_STDERR,
		    gettext("Error parsing lifetime string\n"));
		return (PK_ERR_USAGE);
	}

	if (Str2KeyType(keytype, hashoid, &keyAlg, &sigAlg) != 0) {
		cryptoerror(LOG_STDERR,
		    gettext("Unsupported key/hash combination (%s/%s).\n"),
		    keytype, (hashname ? hashname : "none"));
		return (PK_ERR_USAGE);
	}
	if (curveoid != NULL && keyAlg != KMF_ECDSA) {
		cryptoerror(LOG_STDERR, gettext("EC curves are only "
		    "valid for EC keytypes.\n"));
		return (PK_ERR_USAGE);
	}
	if (keyAlg == KMF_ECDSA && curveoid == NULL) {
		cryptoerror(LOG_STDERR, gettext("A curve must be "
		    "specifed when using EC keys.\n"));
		return (PK_ERR_USAGE);
	}
	/* Adjust default keylength for NSS and DSA */
	if (keyAlg == KMF_DSA && !y_flag && kstype == KMF_KEYSTORE_NSS)
		keylen = 1024;

	/*
	 * Check the subject name.
	 * If interactive is true, get it now interactively.
	 */
	if (interactive) {
		subname = NULL;
		if (get_subname(&subname) != KMF_OK || subname == NULL) {
			cryptoerror(LOG_STDERR, gettext("Failed to get the "
			    "subject name interactively.\n"));
			return (PK_ERR_USAGE);
		}
		if (serstr == NULL) {
			(void) get_serial(&serstr);
		}
	} else {
		if (EMPTYSTRING(subject)) {
			cryptoerror(LOG_STDERR, gettext("A subject name or "
			    "-i must be specified to create a self-signed "
			    "certificate.\n"));
			return (PK_ERR_USAGE);
		} else {
			subname = strdup(subject);
			if (subname == NULL) {
				cryptoerror(LOG_STDERR,
				    gettext("Out of memory.\n"));
				return (PK_ERR_SYSTEM);
			}
		}
	}

	if (serstr == NULL) {
		(void) fprintf(stderr, gettext("A serial number "
		    "must be specified as a hex number when creating"
		    " a self-signed certificate "
		    "(ex: serial=0x0102030405feedface)\n"));
		rv = PK_ERR_USAGE;
		goto end;
	} else {
		uchar_t *bytes = NULL;
		size_t bytelen;

		rv = kmf_hexstr_to_bytes((uchar_t *)serstr, &bytes, &bytelen);
		if (rv != KMF_OK || bytes == NULL) {
			(void) fprintf(stderr, gettext("serial number "
			    "must be specified as a hex number "
			    "(ex: 0x0102030405ffeeddee)\n"));
			rv = PK_ERR_USAGE;
			goto end;
		}
		serial.val = bytes;
		serial.len = bytelen;
	}

	if (altname != NULL) {
		rv = verify_altname(altname, &alttype, &altcrit);
		if (rv != KMF_OK) {
			(void) fprintf(stderr, gettext("Subject AltName "
			    "must be specified as a name=value pair. "
			    "See the man page for details.\n"));
			rv = PK_ERR_USAGE;
			goto end;
		} else {
			/* advance the altname past the '=' sign */
			char *p = strchr(altname, '=');
			if (p != NULL)
				altname = p + 1;
		}
	}

	if (keyusagestr != NULL) {
		rv = verify_keyusage(keyusagestr, &kubits, &kucrit);
		if (rv != KMF_OK) {
			(void) fprintf(stderr, gettext("KeyUsage "
			    "must be specified as a comma-separated list. "
			    "See the man page for details.\n"));
			rv = PK_ERR_USAGE;
			goto end;
		}
	}
	if (ekustr != NULL) {
		rv = verify_ekunames(ekustr, &ekulist);
		if (rv != KMF_OK) {
			(void) fprintf(stderr, gettext("EKUs must "
			    "be specified as a comma-separated list. "
			    "See the man page for details.\n"));
			rv = PK_ERR_USAGE;
			goto end;
		}
	}
	if (keyAlg == KMF_ECDSA && kstype == KMF_KEYSTORE_OPENSSL) {
		(void) fprintf(stderr, gettext("ECC certificates are"
		    "only supported with the pkcs11 and nss keystores\n"));
		rv = PK_ERR_USAGE;
		goto end;
	}

	if (kstype == KMF_KEYSTORE_NSS || kstype == KMF_KEYSTORE_PK11TOKEN) {
		if (tokenname == NULL || !strlen(tokenname)) {
			if (kstype == KMF_KEYSTORE_NSS) {
				tokenname = "internal";
			} else  {
				tokenname = PK_DEFAULT_PK11TOKEN;
			}
		}

		(void) get_token_password(kstype, tokenname, &tokencred);
	}

	if (kstype == KMF_KEYSTORE_NSS) {
		if (dir == NULL)
			dir = PK_DEFAULT_DIRECTORY;

		rv = gencert_nss(kmfhandle,
		    tokenname, subname, altname, alttype, altcrit,
		    certlabel, dir, prefix, keyAlg, sigAlg, keylen,
		    trust, ltime, &serial, kubits, kucrit, &tokencred,
		    ekulist, curveoid);

	} else if (kstype == KMF_KEYSTORE_PK11TOKEN) {
		rv = gencert_pkcs11(kmfhandle,
		    tokenname, subname, altname, alttype, altcrit,
		    certlabel, keyAlg, sigAlg, keylen, ltime,
		    &serial, kubits, kucrit, &tokencred, ekulist,
		    curveoid);

	} else if (kstype == KMF_KEYSTORE_OPENSSL) {
		rv = gencert_file(kmfhandle,
		    keyAlg, sigAlg, keylen, fmt,
		    ltime, subname, altname, alttype, altcrit,
		    &serial, kubits, kucrit, outcert, outkey,
		    ekulist);
	}

	if (rv != KMF_OK)
		display_error(kmfhandle, rv,
		    gettext("Error creating certificate and keypair"));
end:
	if (ekulist != NULL)
		free_eku_list(ekulist);
	if (subname)
		free(subname);
	if (tokencred.cred != NULL)
		free(tokencred.cred);

	if (serial.val != NULL)
		free(serial.val);

	(void) kmf_finalize(kmfhandle);
	return (rv);
}
void connectivityTask(void *params)
{

    char * buffer = (char *)portMalloc(BUFFER_SIZE);
    size_t rxCount = 0;

    ConnParams *connParams = (ConnParams*)params;
    LoggerMessage msg;

    Serial *serial = get_serial(connParams->serial);

    xQueueHandle sampleQueue = connParams->sampleQueue;
    uint32_t connection_timeout = connParams->connection_timeout;

    DeviceConfig deviceConfig;
    deviceConfig.serial = serial;
    deviceConfig.buffer = buffer;
    deviceConfig.length = BUFFER_SIZE;

    const LoggerConfig *logger_config = getWorkingLoggerConfig();

    bool logging_enabled = false;

    while (1) {
        bool should_stream = logging_enabled ||
                             logger_config->ConnectivityConfigs.telemetryConfig.backgroundStreaming ||
                             connParams->always_streaming;

        while (should_stream && connParams->init_connection(&deviceConfig) != DEVICE_INIT_SUCCESS) {
            pr_info("conn: not connected. retrying\r\n");
            vTaskDelay(INIT_DELAY);
        }

        serial->flush();
        rxCount = 0;
        size_t badMsgCount = 0;
        size_t tick = 0;
        size_t last_message_time = getUptimeAsInt();
        bool should_reconnect = false;

        while (1) {
            if ( should_reconnect )
                break; /*break out and trigger the re-connection if needed */

            should_stream =
                    logging_enabled ||
                    connParams->always_streaming ||
                    logger_config->ConnectivityConfigs.telemetryConfig.backgroundStreaming;

            const char res = receive_logger_message(sampleQueue, &msg,
                                                    IDLE_TIMEOUT);

            /*///////////////////////////////////////////////////////////
            // Process a pending message from logger task, if exists
            ////////////////////////////////////////////////////////////*/
            if (pdFALSE != res) {
                switch(msg.type) {
                case LoggerMessageType_Start: {
                    api_sendLogStart(serial);
                    put_crlf(serial);
                    tick = 0;
                    logging_enabled = true;
                    /* If we're not already streaming trigger a re-connect */
                    if (!should_stream)
                        should_reconnect = true;
                    break;
                }
                case LoggerMessageType_Stop: {
                    api_sendLogEnd(serial);
                    put_crlf(serial);
                    if (! (logger_config->ConnectivityConfigs.telemetryConfig.backgroundStreaming ||
                           connParams->always_streaming))
                        should_reconnect = true;
                    logging_enabled = false;
                    break;
                }
                case LoggerMessageType_Sample: {
                        if (!should_stream)
                                break;

                        const int send_meta = tick == 0 ||
                                (connParams->periodicMeta &&
                                 (tick % METADATA_SAMPLE_INTERVAL == 0));
                        api_send_sample_record(serial, msg.sample, tick, send_meta);

                        if (connParams->isPrimary)
                                toggle_connectivity_indicator();

                        put_crlf(serial);
                        tick++;
                        break;
                }
                default:
                    break;
                }
            }

            /*//////////////////////////////////////////////////////////
            // Process incoming message, if available
            ////////////////////////////////////////////////////////////
            //read in available characters, process message as necessary*/
            int msgReceived = processRxBuffer(serial, buffer, &rxCount);
            /*check the latest contents of the buffer for something that might indicate an error condition*/
            if (connParams->check_connection_status(&deviceConfig) != DEVICE_STATUS_NO_ERROR) {
                pr_info("conn: disconnected\r\n");
                break;
            }
            /*now process a complete message if available*/
            if (msgReceived) {
                last_message_time = getUptimeAsInt();
                pr_debug(connParams->connectionName);
                pr_debug_str_msg(": rx: ", buffer);
                int msgRes = process_api(serial, buffer, BUFFER_SIZE);

                int msgError = (msgRes == API_ERROR_MALFORMED);
                if (msgError) {
                    pr_debug("(failed)\r\n");
                }
                if (msgError) {
                    badMsgCount++;
                } else {
                    badMsgCount = 0;
                }
                if (badMsgCount >= BAD_MESSAGE_THRESHOLD) {
                    pr_warning_int_msg("re-connecting- empty/bad msgs :", badMsgCount );
                    break;
                }
                rxCount = 0;
            }

            /*disconnect if a timeout is configured and
            // we haven't heard from the other side for a while */
            const size_t timeout = getUptimeAsInt() - last_message_time;
            if (connection_timeout && timeout > connection_timeout ) {
                pr_info_str_msg(connParams->connectionName, ": timeout");
                should_reconnect = true;
            }
        }
        clear_connectivity_indicator();
        connParams->disconnect(&deviceConfig);
    }
}
Example #20
0
/** TODO: handle --force option! */
gpg_error_t cmd_learn (assuan_context_t ctx, char *line)
{
	gpg_err_code_t error = GPG_ERR_GENERAL;
	pkcs11h_certificate_id_list_t user_certificates = NULL;
	pkcs11h_certificate_id_list_t issuer_certificates = NULL;
	char *serial = NULL;

	(void)line;

	if (
		(error = get_serial(ctx, &serial)) != GPG_ERR_NO_ERROR
	) {
		goto cleanup;
	}

	if (
		(error = assuan_write_status (
			ctx,
			"SERIALNO",
			serial
		)) != GPG_ERR_NO_ERROR ||
		(error = assuan_write_status (
			ctx,
			"APPTYPE",
			"PKCS11"
		)) != GPG_ERR_NO_ERROR
	) {
		goto cleanup;
	}

	if (
		(error = common_map_pkcs11_error (
			pkcs11h_certificate_enumCertificateIds (
				PKCS11H_ENUM_METHOD_CACHE_EXIST,
				ctx,
				PKCS11H_PROMPT_MASK_ALLOW_ALL,
				&issuer_certificates,
				&user_certificates
			)
		)) != GPG_ERR_NO_ERROR ||
		(error = send_certificate_list (
			ctx,
			user_certificates,
			0
		)) != GPG_ERR_NO_ERROR ||
		(error = send_certificate_list (
			ctx,
			issuer_certificates,
			1
		)) != GPG_ERR_NO_ERROR
	) {
		goto cleanup;
	}

	error = GPG_ERR_NO_ERROR;

cleanup:

	if (issuer_certificates != NULL) {
		pkcs11h_certificate_freeCertificateIdList (issuer_certificates);
		issuer_certificates = NULL;
	}

	if (user_certificates != NULL) {
		pkcs11h_certificate_freeCertificateIdList (user_certificates);
		user_certificates = NULL;
	}

	if (serial != NULL) {
		free(serial);
		serial = NULL;
	}

	return gpg_error (error);
}
Example #21
0
gpg_error_t cmd_getattr (assuan_context_t ctx, char *line)
{
	pkcs11h_certificate_id_list_t user_certificates = NULL;
	char *serial = NULL;
	gpg_err_code_t error = GPG_ERR_GENERAL;

	if (!strcmp (line, "SERIALNO")) {
		if (
			(error = get_serial(ctx, &serial)) != GPG_ERR_NO_ERROR
		) {
			goto cleanup;
		}

		if (serial != NULL) {
			if (
				(error = assuan_write_status (
					ctx,
					"SERIALNO",
					serial
				)) != GPG_ERR_NO_ERROR
			) {
				goto cleanup;
			}
		}
	}
	else if (!strcmp (line, "KEY-FPR")) {
		if (
			(error = common_map_pkcs11_error (
				pkcs11h_certificate_enumCertificateIds (
					PKCS11H_ENUM_METHOD_CACHE_EXIST,
					ctx,
					PKCS11H_PROMPT_MASK_ALLOW_ALL,
					NULL,
					&user_certificates
				)
			)) != GPG_ERR_NO_ERROR ||
			(error = send_certificate_list (
				ctx,
				user_certificates,
				0
			)) != GPG_ERR_NO_ERROR
		) {
			goto cleanup;
		}
	}
	else if (!strcmp (line, "CHV-STATUS")) {
		if (
			(error = assuan_write_status(
				ctx,
				"CHV-STATUS",
				"1 1 1 1 1 1 1"
			)) != GPG_ERR_NO_ERROR
		) {
			goto cleanup;
		}
	}
	else if (!strcmp (line, "DISP-NAME")) {
		if (
			(error = assuan_write_status(
				ctx,
				"DISP-NAME",
				"PKCS#11"
			)) != GPG_ERR_NO_ERROR
		) {
			goto cleanup;
		}
	}
	else if (!strcmp (line, "KEY-ATTR")) {
		int i;
		for (i=0;i<3;i++) {
			char buffer[1024];

			/* I am not sure 2048 is right here... */
			snprintf(buffer, sizeof(buffer), "%d 1 %u %u %d", i+1, GCRY_PK_RSA, 2048, 0);

			if (
				(error = assuan_write_status(
					ctx,
					"KEY-ATTR",
					buffer
				)) != GPG_ERR_NO_ERROR
			) {
				goto cleanup;
			}
		}
	}
	else if (!strcmp (line, "EXTCAP")) {
		int i;
		for (i=0;i<3;i++) {
			char buffer[1024];

			/* I am not sure what these are... */
			snprintf(buffer, sizeof(buffer), "gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d sm=%d",
				0, 0, 0, 0, 2048, 0, 0);

			if (
				(error = assuan_write_status(
					ctx,
					"EXTCAP",
					buffer
				)) != GPG_ERR_NO_ERROR
			) {
				goto cleanup;
			}
		}
	}
	else {
		error = GPG_ERR_INV_DATA;
		goto cleanup;
	}

	error = GPG_ERR_NO_ERROR;

cleanup:

	if (user_certificates != NULL) {
		pkcs11h_certificate_freeCertificateIdList (user_certificates);
		user_certificates = NULL;
	}

	if (serial != NULL) {
		free(serial);
		serial = NULL;
	}

	return gpg_error (error);
}
Example #22
0
main(int argc, char **argv)
{
	int	get_flag = 0, wild_intr_flag = 0;
	int	c;
	extern int optind;
	extern char *optarg;
	
	progname = argv[0];
	if (argc == 1)
		usage();
	while ((c = getopt(argc, argv, "abgGqvVWz")) != EOF) {
		switch (c) {
		case 'a':
			verbosity = 2;
			break;
		case 'b':
			verbosity = 0;
			break;
		case 'q':
			quiet_flag++;
			break;
		case 'v':
			verbose_flag++;
			break;
		case 'g':
			get_flag++;
			break;
		case 'G':
			verbosity = -1;
			break;
		case 'V':
			fprintf(stderr, "%s\n", version_str);
			exit(0);
		case 'W':
			wild_intr_flag++;
			break;
		case 'z':
			zero_flag++;
			break;
		default:
			usage();
		}
	}
	if (get_flag) {
		argv += optind;
		while (*argv)
			get_serial(*argv++);
		exit(0);
	}
	if (argc == optind)
		usage();
	if (wild_intr_flag) {
		do_wild_intr(argv[optind]);
		exit(0);
	}
	if (argc-optind == 1)
		get_serial(argv[optind]);
	else
		set_serial(argv[optind], argv+optind+1);
	exit(0);
}
Example #23
0
/* Creates an X509 certificate from a certificate request. */
EXPORT int IssueUserCertificate(unsigned char *certbuf, int *certlen, unsigned char *reqbuf, int reqlen)
{
	X509_REQ *req = NULL;
	EVP_PKEY *cakey = NULL, *rakey = NULL, *usrkey = NULL;
	X509 *cacert = NULL, *racert = NULL, *usrcert = NULL;
	X509_NAME *subject = NULL, *issuer = NULL;
	unsigned char *p = NULL;
	int ret = OPENSSLCA_NO_ERR, len;

	if (certbuf == NULL || certlen == NULL || reqbuf == NULL || reqlen == 0)
		return OPENSSLCA_ERR_ARGS;

	/* Decode request */
	if ((req = X509_REQ_new()) == NULL) {
		ret = OPENSSLCA_ERR_REQ_NEW;
		goto err;
	}
	p = reqbuf;
	if (d2i_X509_REQ(&req, &p, reqlen) == NULL) {
		ret = OPENSSLCA_ERR_REQ_DECODE;
		goto err;
	}

	/* Get public key from request */
	if ((usrkey = X509_REQ_get_pubkey(req)) == NULL) {
		ret = OPENSSLCA_ERR_REQ_GET_PUBKEY;
		goto err;
	}

	if (caIni.verifyRequests) {
		/* Get RA's public key */
		/* TODO: Validate RA certificate */
		ret = read_cert(&racert, CA_PATH(caIni.raCertFile));
		if (ret != OPENSSLCA_NO_ERR)
			goto err;
		if ((rakey = X509_get_pubkey(racert)) == NULL) {
			ret = OPENSSLCA_ERR_CERT_GET_PUBKEY;
			goto err;
		}

		/* Verify signature on request */
		if (X509_REQ_verify(req, rakey) != 1) {
			ret = OPENSSLCA_ERR_REQ_VERIFY;
			goto err;
		}
	}

	/* Get CA certificate */
	/* TODO: Validate CA certificate */
	ret = read_cert(&cacert, CA_PATH(caIni.caCertFile));
	if (ret != OPENSSLCA_NO_ERR)
		goto err;

	/* Get CA private key */
	ret = read_key(&cakey, CA_PATH(caIni.caKeyFile), caIni.caKeyPasswd);
	if (ret != OPENSSLCA_NO_ERR)
		goto err;

	/* Create user certificate */
	if ((usrcert = X509_new()) == NULL)
		return OPENSSLCA_ERR_CERT_NEW;

	/* Set version and serial number for certificate */
	if (X509_set_version(usrcert, 2) != 1) { /* V3 */
		ret = OPENSSLCA_ERR_CERT_SET_VERSION;
		goto err;
	}
	if (ASN1_INTEGER_set(X509_get_serialNumber(usrcert), get_serial()) != 1) {
		ret = OPENSSLCA_ERR_CERT_SET_SERIAL;
		goto err;
	}

	/* Set duration for certificate */
	if (X509_gmtime_adj(X509_get_notBefore(usrcert), 0) == NULL) {
		ret = OPENSSLCA_ERR_CERT_SET_NOTBEFORE;
		goto err;
	}
	if (X509_gmtime_adj(X509_get_notAfter(usrcert), EXPIRE_SECS(caIni.daysTillExpire)) == NULL) {
		ret = OPENSSLCA_ERR_CERT_SET_NOTAFTER;
		goto err;
	}

	/* Set public key */
	if (X509_set_pubkey(usrcert, usrkey) != 1) {
		ret = OPENSSLCA_ERR_CERT_SET_PUBKEY;
		goto err;
	}

	/* Set subject name */
	subject = X509_REQ_get_subject_name(req);
	if (subject == NULL) {
		ret = OPENSSLCA_ERR_REQ_GET_SUBJECT;
		goto err;
	}
	if (X509_set_subject_name(usrcert, subject) != 1) {
		ret = OPENSSLCA_ERR_CERT_SET_SUBJECT;
		goto err;
	}

	/* Set issuer name */
	issuer = X509_get_issuer_name(cacert);
	if (issuer == NULL) {
		ret = OPENSSLCA_ERR_CERT_GET_ISSUER;
		goto err;
	}
	if (X509_set_issuer_name(usrcert, issuer) != 1) {
		ret = OPENSSLCA_ERR_CERT_SET_ISSUER;
		goto err;
	}

	/* Add extensions */
	ret = add_ext(cacert, usrcert);
	if (ret != OPENSSLCA_NO_ERR)
		goto err;

	/* Sign user certificate with CA's private key */
	if (!X509_sign(usrcert, cakey, EVP_sha1()))
		return OPENSSLCA_ERR_CERT_SIGN;

	if (caIni.verifyAfterSign) {
		if (X509_verify(usrcert, cakey) != 1) {
			ret = OPENSSLCA_ERR_CERT_VERIFY;
			goto err;
		}
	}

#ifdef _DEBUG /* Output certificate in DER and PEM format */
	{
		FILE *fp = fopen(DBG_PATH("usrcert.der"), "wb");
		if (fp != NULL) {
			i2d_X509_fp(fp, usrcert);
			fclose(fp);
		}
		fp = fopen(DBG_PATH("usrcert.pem"), "w");
		if (fp != NULL) {
			X509_print_fp(fp, usrcert);
			PEM_write_X509(fp, usrcert);
			fclose(fp);
		}
	}
#endif

	/* Encode user certificate into DER format */
	len = i2d_X509(usrcert, NULL);
	if (len < 0) {
		ret = OPENSSLCA_ERR_CERT_ENCODE;
		goto err;
	}
	if (len > *certlen) {
		ret = OPENSSLCA_ERR_BUF_TOO_SMALL;
		goto err;
	}
	*certlen = len;
	p = certbuf;
	i2d_X509(usrcert, &p);

	if (caIni.addToIndex)
		add_to_index(usrcert);

	if (caIni.addToNewCerts)
		write_cert(usrcert);

err:
	print_err("IssueUserCertificate()", ret);

	/* Clean up */
	if (cacert)
		X509_free(cacert);
	if (cakey)
		EVP_PKEY_free(cakey);
	if (racert)
		X509_free(racert);
	if (rakey)
		EVP_PKEY_free(rakey);
	if (req)
		X509_REQ_free(req);
	if (usrcert != NULL)
		X509_free(usrcert);
	if (usrkey)
		EVP_PKEY_free(usrkey);

	return ret;
}
Example #24
0
/* finds entry in list, or returns NULL */
struct entry* 
find_match(struct entry* entries, ldns_pkt* query_pkt,
	enum transport_type transport)
{
	struct entry* p = entries;
	ldns_pkt* reply = NULL;
	for(p=entries; p; p=p->next) {
		verbose(3, "comparepkt: ");
		reply = p->reply_list->reply;
		if(p->match_opcode && ldns_pkt_get_opcode(query_pkt) != 
			ldns_pkt_get_opcode(reply)) {
			verbose(3, "bad opcode\n");
			continue;
		}
		if(p->match_qtype && get_qtype(query_pkt) != get_qtype(reply)) {
			verbose(3, "bad qtype\n");
			continue;
		}
		if(p->match_qname) {
			if(!get_owner(query_pkt) || !get_owner(reply) ||
				ldns_dname_compare(
				get_owner(query_pkt), get_owner(reply)) != 0) {
				verbose(3, "bad qname\n");
				continue;
			}
		}
		if(p->match_subdomain) {
			if(!get_owner(query_pkt) || !get_owner(reply) ||
				(ldns_dname_compare(get_owner(query_pkt), 
				get_owner(reply)) != 0 &&
				!ldns_dname_is_subdomain(
				get_owner(query_pkt), get_owner(reply))))
			{
				verbose(3, "bad subdomain\n");
				continue;
			}
		}
		if(p->match_serial && get_serial(query_pkt) != p->ixfr_soa_serial) {
				verbose(3, "bad serial\n");
				continue;
		}
		if(p->match_do && !ldns_pkt_edns_do(query_pkt)) {
			verbose(3, "no DO bit set\n");
			continue;
		}
		if(p->match_noedns && ldns_pkt_edns(query_pkt)) {
			verbose(3, "bad; EDNS OPT present\n");
			continue;
		}
		if(p->match_transport != transport_any && p->match_transport != transport) {
			verbose(3, "bad transport\n");
			continue;
		}
		if(p->match_all && !match_all(query_pkt, reply, p->match_ttl)) {
			verbose(3, "bad allmatch\n");
			continue;
		}
		verbose(3, "match!\n");
		return p;
	}
	return NULL;
}
Example #25
0
void set_serial(char *device, char ** arg)
{
	struct serial_struct old_serinfo, new_serinfo;
	struct	flag_type_table	*p;
	int	fd;
	int	do_invert = 0;
	char	*word;
	

	if ((fd = open(device, O_RDWR |O_NONBLOCK)) < 0) {
		if (verbosity==0 && errno==ENOENT)
			exit(201);
		perror(device);
		exit(201);
	}
	if (ioctl(fd, TIOCGSERIAL, &old_serinfo) < 0) {
		perror("Cannot get serial info");
		exit(1);
	}
	new_serinfo = old_serinfo;
	if (zero_flag)
		new_serinfo.flags = 0;
	while (*arg) {
		do_invert = 0;
		word = *arg++;
		if (*word == '^') {
			do_invert++;
			word++;
		}
		for (p = flag_type_tbl; p->name; p++) {
			if (!strcasecmp(p->name, word))
				break;
		}
		if (!p->name) {
			fprintf(stderr, "Invalid flag: %s\n", word);
			exit(1);
		}
		if (do_invert && !(p->flags & FLAG_CAN_INVERT)) {
			fprintf(stderr, "This flag can not be inverted: %s\n", word);
			exit(1);
		}
		if ((p->flags & FLAG_NEED_ARG) && !*arg) {
			fprintf(stderr, "Missing argument for %s\n", word);
			exit(1);
		}
		switch (p->cmd) {
		case CMD_FLAG:
			new_serinfo.flags &= ~p->mask;
			if (!do_invert)
				new_serinfo.flags |= p->bits;
			break;
		/*
		case CMD_PORT:
			new_serinfo.port = atonum(*arg++);
			break;
		case CMD_IRQ:
			new_serinfo.irq = atonum(*arg++);
			break;
		case CMD_DIVISOR:
			new_serinfo.custom_divisor = atonum(*arg++);
			break;
		case CMD_TYPE:
			new_serinfo.type = uart_type(*arg++);
			if (new_serinfo.type < 0) {
				fprintf(stderr, "Illegal UART type: %s", *--arg);
				exit(1);
			}
			break;
		case CMD_BASE:
			new_serinfo.baud_base = atonum(*arg++);
			break;
		*/
		case CMD_DELAY:
			new_serinfo.close_delay = atonum(*arg++);
			break;
		case CMD_WAIT:
			if (!strcasecmp(*arg, "infinite"))
				new_serinfo.closing_wait = ASYNC_CLOSING_WAIT_INF;
			else if (!strcasecmp(*arg, "none"))
				new_serinfo.closing_wait = ASYNC_CLOSING_WAIT_NONE;
			else
				new_serinfo.closing_wait = atonum(*arg);
			arg++;
			break;
		case CMD_WAIT2:
			if (!strcasecmp(*arg, "infinite"))
				new_serinfo.closing_wait2 = ASYNC_CLOSING_WAIT_INF;
			else if (!strcasecmp(*arg, "none"))
				new_serinfo.closing_wait2 = ASYNC_CLOSING_WAIT_NONE;
			else
				new_serinfo.closing_wait2 = atonum(*arg);
			arg++;
			break;
		case CMD_CONFIG:
			if (ioctl(fd, TIOCSSERIAL, &new_serinfo) < 0) {
				perror("Cannot set serial info");
				exit(1);
			}
			if (ioctl(fd, TIOCSERCONFIG) < 0) {
				perror("Cannot autoconfigure port");
				exit(1);
			}
			if (ioctl(fd, TIOCGSERIAL, &new_serinfo) < 0) {
				perror("Cannot get serial info");
				exit(1);
			}
			break;
			
#ifdef BRAINBOXES_IOCGCONF
		case CMD_RX_TRIG:
		case CMD_TX_TRIG:
		case CMD_AFC_TRIG:
		case CMD_DUPLEX:
		case CMD_CTS_TRUE:
			set_bbconfig(fd, p->cmd, atonum(*arg++));
			break;
#endif
		default:
			fprintf(stderr, "Internal error: unhandled cmd #%d\n", p->cmd);
			exit(1);
		}
	}
	if (ioctl(fd, TIOCSSERIAL, &new_serinfo) < 0) {
		perror("Cannot set serial info");
		exit(1);
	}
	close(fd);
	if (verbose_flag)
		get_serial(device);
}
Example #26
0
void monkey_ep_init(void)
{
  int pos, idx;
  uint16_t packet_buf_base;
  char serial[32];

  get_serial(serial, sizeof(serial));
  monkey_set_string_descriptor(0x0301, 0x0409, "Sapphire Zhao");
  monkey_set_string_descriptor(0x0302, 0x0409, "Aikon");
  monkey_set_string_descriptor(0x0303, 0x0409, serial);

  ep_conf_list[0].direct = EP_IN | EP_OUT;
  ep_conf_list[0].attr = 1;
  ep_conf_list[0].rx_max = 64;
  ep_conf_list[0].tx_max = 64;
  ep_conf_list[0].rx_status = EP_RX_VALID;
  ep_conf_list[0].tx_status = EP_TX_STALL;
  packet_buf_base = 8;

	for(pos=0; pos<sizeof(config1_descriptor); pos+=config1_descriptor[pos]) {
		if(config1_descriptor[pos+1] == 0x5) { // ep descriptor
      uint8_t no, direct, attr;
      uint16_t max_packet;

      no = config1_descriptor[pos+2]&0x7;
      direct = config1_descriptor[pos+2]&0x80 ? EP_IN : EP_OUT;
      attr = config1_descriptor[pos+3]&3;
      max_packet = config1_descriptor[pos+4]+config1_descriptor[pos+5]*0x100;
      if(ep_conf_list[no].direct == 0) {
        ep_conf_list[no].tx_status = EP_TX_NAK;
        ep_conf_list[no].rx_status = EP_RX_VALID;
        ep_conf_list[no].attr = attr;
      }
      
      ep_conf_list[no].direct |= direct;
      if(direct & EP_IN) {
        ep_conf_list[no].tx_max = max_packet;
      } else {
        ep_conf_list[no].rx_max = max_packet;
      }

      packet_buf_base += 8;
		}
	}
#ifdef EP_OUT_DEFAULT
  for(idx=0; idx<8; ++idx) {
    if(ep_conf_list[idx].direct == EP_IN) {
        ep_conf_list[idx].direct |= EP_OUT;
        ep_conf_list[idx].rx_max = ep_conf_list[idx].tx_max;
        packet_buf_base += 8;
    }
  }
#endif      
  for(idx=0; idx<8; ++idx) {
    if(ep_conf_list[idx].direct) {
      if(ep_conf_list[idx].direct & EP_IN) {
        ep_conf_list[idx].tx_addr = packet_buf_base;
        packet_buf_base += (ep_conf_list[idx].tx_max+3)&~3;
      }
      
      if(ep_conf_list[idx].direct & EP_OUT) {
        ep_conf_list[idx].rx_addr = packet_buf_base;
        packet_buf_base += (ep_conf_list[idx].rx_max+3)&~3;
      }
    }
  }
}