Beispiel #1
1
    void EtherIPC::sendTransaction(const QString& from, const QString& to, const QString& valStr, const QString& gas) {
        QJsonArray params;
        const QString valHex = Helpers::toHexWeiStr(valStr);
        EtherLog::logMsg(QString("Trans Value: ") + valStr + QString(" HexValue: ") + valHex);

        QJsonObject p;
        p["from"] = from;
        p["to"] = to;
        p["value"] = valHex;
        if ( !gas.isEmpty() ) {
            const QString gasHex = Helpers::decStrToHexStr(gas);
            p["gas"] = gasHex;
        }

        params.append(p);

        if ( !queueRequest(RequestIPC(SendTransaction, "eth_sendTransaction", params)) ) {
            return bail(true); // softbail
        }
    }
Beispiel #2
0
    void EtherIPC::handleGetAccounts() {
        QJsonValue jv;
        if ( !readReply(jv) ) {
            return bail();
        }

        QJsonArray refs = jv.toArray();
        foreach( QJsonValue r, refs ) {
            const QString hash = r.toString("INVALID");
            fAccountList.append(AccountInfo(hash, QString(), 0));
        }

        emit getAccountsDone(fAccountList);

        // TODO: figure out a way to get account transaction history
        newFilter();

        done();
    }
Beispiel #3
0
    void EtherIPC::handleGetFilterChanges() {
        QJsonValue jv;
        if ( !readReply(jv) ) {
            return bail();
        }

        QJsonArray ar = jv.toArray();

        foreach( const QJsonValue v, ar ) {
            if ( v.isObject() ) { // event filter result
                const QJsonObject logs = v.toObject();
                emit newEvent(logs, fActiveRequest.getType() == GetFilterChanges); // get logs is not "new"
            } else { // block filter (we don't use transaction filters yet)
                const QString hash = v.toString("bogus");
                getBlockByHash(hash);
            }
        }

        done();
    }
/* quote get internal */
static int shout_get_cl( void *to, int argc, char **argv, char **coln )
{
	/* silence warnings */
	coln = 0;
	/* where to save? */
	quote_t *sq = (quote_t*)to;
	/* sanity check */
	if ( argc != 5 )
		return bail("shout_get_cl: failed sanity check\n");
	if ( sq && argv )
	{
		memset(sq,0,sizeof(quote_t));
		sq->id = atoll(argv[0]);
		sq->epoch = atoll(argv[1]);
		strncpy(sq->name,argv[2],256);
		strncpy(sq->channel,argv[3],256);
		strncpy(sq->line,argv[4],256);
	}
	return 0;
}
Beispiel #5
0
SEXP R_rsa_priv_decompose(SEXP bin){
  RSA *rsa = RSA_new();
  const unsigned char *ptr = RAW(bin);
  bail(!!d2i_RSAPrivateKey(&rsa, &ptr, LENGTH(bin)));
  const BIGNUM *e, *n, *p, *q, *d, *dmp1, *dmq1, *iqmp;
  MY_RSA_get0_key(rsa, &n, &e, &d);
  MY_RSA_get0_factors(rsa, &p, &q);
  MY_RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
  SEXP res = PROTECT(allocVector(VECSXP, 8));
  SET_VECTOR_ELT(res, 0, bignum_to_r(e));
  SET_VECTOR_ELT(res, 1, bignum_to_r(n));
  SET_VECTOR_ELT(res, 2, bignum_to_r(p));
  SET_VECTOR_ELT(res, 3, bignum_to_r(q));
  SET_VECTOR_ELT(res, 4, bignum_to_r(d));
  SET_VECTOR_ELT(res, 5, bignum_to_r(dmp1));
  SET_VECTOR_ELT(res, 6, bignum_to_r(dmq1));
  SET_VECTOR_ELT(res, 7, bignum_to_r(iqmp));
  UNPROTECT(1);
  return res;
}
Beispiel #6
0
int
main(void)
{
    struct kerberos_config *config;
    struct remctl *r;
    OM_uint32 major, minor;
    int flags, status;
    gss_buffer_desc tok;

    /* Unless we have Kerberos available, we can't really do anything. */
    config = kerberos_setup(TAP_KRB_NEEDS_KEYTAB);
    remctld_start(config, "data/conf-simple", NULL);

    plan(7);

    /* Open the connection to the site. */
    r = remctl_new();
    ok(r != NULL, "remctl_new");
    ok(remctl_open(r, "localhost", 14373, config->principal), "remctl_open");

    /* Send the no-op token. */
    tok.length = sizeof(token);
    tok.value = (char *) token;
    status = token_send_priv(r->fd, r->context, TOKEN_DATA | TOKEN_PROTOCOL,
                             &tok, 0, &major, &minor);
    if (status != TOKEN_OK)
        bail("cannot send token");

    /* Accept the remote token. */
    status = token_recv_priv(r->fd, r->context, &flags, &tok, 1024 * 64, 0,
                             &major, &minor);
    is_int(TOKEN_OK, status, "received token correctly");
    is_int(TOKEN_DATA | TOKEN_PROTOCOL, flags, "token had correct flags");
    is_int(2, tok.length, "token had correct length");
    is_int(3, ((char *) tok.value)[0], "protocol version is 3");
    is_int(MESSAGE_NOOP, ((char *) tok.value)[1], "no-op message");

    /* Close things out. */
    remctl_close(r);
    return 0;
}
Beispiel #7
0
    void EtherIPC::init() {        
        fConnectAttempts = 0;
        if ( fStarting <= 0 ) { // try to connect without starting geth
            EtherLog::logMsg("Etherwall starting", LS_Info);
            fStarting = 1;
            emit startingChanged(fStarting);
            return connectToServer();
        }

        const QSettings settings;

        const QString progStr = settings.value("geth/path", DefaultGethPath()).toString();
        const QString argStr = settings.value("geth/args", DefaultGethArgs).toString();
        const QString ddStr = settings.value("geth/datadir", DefaultDataDir).toString();
        QStringList args = (argStr + " --datadir " + ddStr).split(' ', QString::SkipEmptyParts);
        bool testnet = settings.value("geth/testnet", false).toBool();
        if ( testnet ) {
            args.append("--testnet");
        }
        bool hardfork = settings.value("geth/hardfork", true).toBool();
        if ( hardfork ) {
            args.append("--support-dao-fork");
        } else {
            args.append("--oppose-dao-fork");
        }

        QFileInfo info(progStr);
        if ( !info.exists() || !info.isExecutable() ) {
            fStarting = -1;
            emit startingChanged(-1);
            setError("Could not find Geth. Please check Geth path and try again.");
            return bail();
        }

        EtherLog::logMsg("Geth starting " + progStr + " " + args.join(" "), LS_Info);
        fStarting = 2;

        fGethLog.attach(&fGeth);
        fGeth.start(progStr, args);
        emit startingChanged(0);
    }
Beispiel #8
0
/*
 * Read a line from a file into a BUFSIZ buffer, failing if the line was too
 * long to fit into the buffer, and returns a copy of that line in newly
 * allocated memory.  Ignores blank lines and comments.  Caller is responsible
 * for freeing.  Returns NULL on end of file and fails on read errors.
 */
static char *
readline(FILE *file)
{
    char buffer[BUFSIZ];
    char *line, *first;

    do {
        line = fgets(buffer, sizeof(buffer), file);
        if (line == NULL) {
            if (feof(file))
                return NULL;
            sysbail("cannot read line from script");
        }
        if (buffer[strlen(buffer) - 1] != '\n')
            bail("script line too long");
        buffer[strlen(buffer) - 1] = '\0';
        first = skip_whitespace(buffer);
    } while (first[0] == '#' || first[0] == '\0');
    line = bstrdup(buffer);
    return line;
}
Beispiel #9
0
KReversiPos Ai::selectMove(const Engine& engine)
{
    PosList legalMoves = engine.getAllMoves();

    for(int i=0;i<legalMoves.size();i++)
        kDebug() << "move_index  " << i << legalMoves[i].row << " " <<legalMoves[i].col;

    lua_getglobal(L, "exec");
    lua_rawgeti(L, LUA_REGISTRYINDEX, profile_ref);
    lua_pushstring(L, engine.getGameStateString().c_str());

    if(lua_pcall(L, 2, 1, 0))
        bail(L, "lua_pcall() failed");          /* Error out if Lua file has an error */

    int ret = lua_tonumber(L, -1);
    lua_pop(L, 1);  /* pop returned value */
    kDebug()<<"best_move_index : " << ret;
    //because kreversigame board representation is zero-based index. we will convert move to zero-based index
    legalMoves[ret].row--;
    legalMoves[ret].col--;
    return legalMoves[ret];
}
Beispiel #10
0
    void EtherIPC::handleGetClientVersion() {
        QJsonValue jv;
        if ( !readReply(jv) ) {
            return bail();
        }

        fClientVersion = jv.toString();

        const int vn = parseVersionNum();
        if ( vn > 0 && vn < 100002 ) {
            setError("Geth version 1.0.1 and older contain a critical bug! Please update immediately.");
            emit error();
        }

        if ( vn > 0 && vn < 103005 ) {
            setError("Geth version 1.3.4 and older are Frontier versions. Please update to Homestead (1.3.5+)");
            emit error();
        }

        emit clientVersionChanged(fClientVersion);
        done();
    }
Beispiel #11
0
/* Record a return TRUE if answer is yes, FALSE if no. */
int       affirm(char *prompt)
{
    int       reply;		/* character typed in */
    int       done;		/* loop control */
    void      bail(char *msg, int status);

    if (prompt != NULL && (int) strlen(prompt) > 0) {
        printf("%s? ", prompt);
    }
    done = 0;
    while (!done) {
	reply = getchar();
	/* while (reply == ' ' || reply== '\n') reply= getchar(); */
	while (isspace(reply))
	    reply = getchar();

	if (reply == 'y' || reply == 'Y')
	    done = 1;
	else if (reply == 'n' || reply == 'N')
	    done = 2;
	else if (reply == 'q' || reply == 'Q')
	    done = 3;
	else if (reply == 'x' || reply == 'X')
	    done = 3;

	else {
	    printf("Valid responses begin with: y Y n N q Q x X\n");
	    if (prompt != NULL) printf("%s? ", prompt);
	    /* Flush rest of input line. */
	    while (reply != '\n')
		reply = getchar();
	}
    }
    if (done > 2)
	bail(NULL, 0);
    else if (done == 2)
	return (FALSE);
    return (TRUE);
}
Beispiel #12
0
/*
 * Generate a krb5.conf file for testing and set KRB5_CONFIG to point to it.
 * The [appdefaults] section will be stripped out and the default realm will
 * be set to the realm specified, if not NULL.  This will use config/krb5.conf
 * in preference, so users can configure the tests by creating that file if
 * the system file isn't suitable.
 *
 * Depends on data/generate-krb5-conf being present in the test suite.
 */
void
kerberos_generate_conf(const char *realm)
{
    char *path;
    const char *argv[3];

    if (tmpdir_conf != NULL)
        kerberos_cleanup_conf();
    path = test_file_path("data/generate-krb5-conf");
    if (path == NULL)
        bail("cannot find generate-krb5-conf");
    argv[0] = path;
    argv[1] = realm;
    argv[2] = NULL;
    run_setup(argv);
    test_file_path_free(path);
    tmpdir_conf = test_tmpdir();
    basprintf(&krb5_config, "KRB5_CONFIG=%s/krb5.conf", tmpdir_conf);
    putenv(krb5_config);
    if (atexit(kerberos_cleanup_conf) != 0)
        sysdiag("cannot register cleanup function");
}
Beispiel #13
0
void Update()
{
  // update the game, happens 60 times a second




  // Hit test the buttons
  if( window->mouseJustPressed( Mouse::Left ) )
  {
    window->hitTestUIObjects( window->getMouseX(), window->getMouseY() ) ;
  }

  // Quit if the user presses ESCAPE
  if( window->keyJustPressed( VK_ESCAPE ) )
  {
    bail( "game ended!" ) ;
  }



}
Beispiel #14
0
static void *cp_malloc_hook(size_t size, const void *caller)
{
    int index = 0;
    void *ptr_to_use = NULL;

    //printf("using custom malloc. request in size: %d\n", size);
    
    while ((size % sizeof(int)) != 0)
	size++;
    index = index_area_to_use(size);
    if (index == MAX_AREAS) {
	fprintf(stderr, "custom malloc memory full\n");
	return NULL;
    }
    /* calculate the real pointer to the area allocated and the size_left of the chose "areas" */
    ptr_to_use = areas[index].ptr_area + (areas[index].max - areas[index].size_left);
    areas[index].size_left -= size;
    /*printf("pointer value [dec]: %u, pointer value [x]: %x, index: %d, size_left: %d\n", 
	(unsigned int) ptr_to_use, (unsigned int) ptr_to_use, index, areas[index].size_left);*/
    if (memset(ptr_to_use, 0, size) != ptr_to_use)
	bail("[E] failed to reset memory area");

    return ptr_to_use;
}
Beispiel #15
0
//
// FUNCTION NAME: SIM_Connect
//
// DESCRIPTION: this is a wrapper for pcsclite SCardConnect function.
//              Its job is to call that function and manage error messages
//              eventually returned.
// 
// INPUT PARAMETERS: 
//   SCARDCONTEXT  hContext    connection context to the PC/SC resource manager
//   LPCSTR        szReader    reader name to connect to
//
// OUTPUT PARAMETERS:  LPSCARDHANDLE
//   If nothing goes bad, returns a handler for this card connection, otherwise
//   exits.
//
// NOTES:
//   - Possible extension will require additional parameters to be chosen by
//     the caller.
//
SCARDHANDLE SIM_Connect(SCARDCONTEXT hContext, LPSTR szReader) {
  SCARDHANDLE hCard;
  DWORD dwActiveProtocol;
  LONG rv;

  rv = SCardConnect(hContext, szReader, SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0, &hCard, &dwActiveProtocol);
  switch(rv) {
    case SCARD_E_NOT_READY: {
      bail(EXIT_FAILURE, "SIM_Connect:",ERR_PORT_NOT_READY);
    }
    case SCARD_E_INVALID_VALUE: {
      bail(EXIT_FAILURE, "SIM_Connect:",ERR_INVALID_PARAMETER_VALUE);
    }
    case SCARD_E_READER_UNAVAILABLE: {
      bail(EXIT_FAILURE, "SIM_Connect:",ERR_READER_UNAVAILABLE);
    }
    case SCARD_E_UNSUPPORTED_FEATURE: {
      bail(EXIT_FAILURE, "SIM_Connect:",ERR_PROTOCOL_UNAVAILABLE);
    }
    case SCARD_E_SHARING_VIOLATION: {
      bail(EXIT_FAILURE, "SIM_Connect:",ERR_SHARING_VIOLATION);
    }
    case SCARD_E_INVALID_HANDLE: {
      bail(EXIT_FAILURE, "SIM_Connect:",ERR_INVALID_CONTEXT_HANDLER);
    }
    case SCARD_S_SUCCESS: {
      printf("Connection with SIM card opened successfully.\n");
      return(hCard);
    }
    default: {
      int errno_saved = errno;
      printf("The card returned: %li.\n",rv);
      printf("Suggestion: maybe card name was mistyped.\n");
      bail_with_errno(EXIT_FAILURE, errno_saved, "SIM_Connect:",ERR_WRONG_RETURN_VALUE);
    }
  }
}
Beispiel #16
0
int
main (int argc, char **argv) {
  int err;
  char *srvr_addr = NULL;
  int port_num;
  int len_inet;			/* length  */
  int sockfd;			/* Socket */

  if (argc == 4) {
	  srvr_addr = argv[1];
	  port_num = atoi(argv[2]);
  } else {
	  printf("usage:%s dst_ip dst_port cicle\n", argv[0]);
	  bail("try again!");
  }

  struct sockaddr_in adr_srvr;	/* AF_INET */
  len_inet = sizeof adr_srvr;
  memset (&adr_srvr, 0, len_inet);
  adr_srvr.sin_family = AF_INET;
  adr_srvr.sin_port = htons (port_num);
  adr_srvr.sin_addr.s_addr = inet_addr (srvr_addr);

  if (adr_srvr.sin_addr.s_addr == INADDR_NONE) {
	  bail ("bad address.");
  }

  sockfd = socket (PF_INET, SOCK_STREAM, 0);
  if (sockfd == -1) bail ("socket()");

  err = connect (sockfd, (struct sockaddr *) &adr_srvr, len_inet);
  if (err == -1) bail ("connect(2)");

  int logid = 0;
  char reqbuff[100000];
  char resbuff[100000];
  memset (reqbuff, 0, sizeof(reqbuff));
  memset (resbuff, 0, sizeof(resbuff));
  xhead_t* reqxhead = (xhead_t*) reqbuff;
  xhead_t* resxhead = (xhead_t*) resbuff;

  char input[1024];
  while (fgets(input, sizeof(input), stdin))
  {
      snprintf(reqxhead->srvname, sizeof(reqxhead->srvname), "%s", "myclient");
      char* str = (char*)(reqxhead+1);
      input[strlen(input) - 1] = 0;
      strncpy(str, input, 1000);
      reqxhead->detail_len = strlen(str) + 1;

      int count = atoi(argv[3]);
      for (int i=0; i<count; i++)
      {
          reqxhead->log_id = logid++;
          int ret = 0;
          if (0 != (ret = xsend(sockfd, reqxhead, 1000)))
          {
              fprintf(stderr, "send err ret[%d] ind[%d] errno[%d] [%m]\n", ret, i, errno);
              exit(1);
          }
          memset(resxhead, 0, 100000);
          if (0 != (ret = xrecv(sockfd, resxhead, sizeof(resbuff), 1000)))
          {
              fprintf(stderr, "recv err ret[%d] ind[%d] errno[%d] [%m]\n", ret, i, errno);
              exit(1);
          }
          else
          {
              printf ("count[%u] ind[%04u] rslen[%d] logid[%u] name[%s] message[%s]\n",
                      count, i, resxhead->detail_len,resxhead->log_id, resxhead->srvname, (char*)&resxhead[1]);
          }
      }
//      for (int i=0; i<count; i++)
//      {
//          int ret = 0;
//          if (0 != (ret = xrecv(sockfd, resxhead, sizeof(resbuff), 1000)))
//          {
//              fprintf(stderr, "recv err ret[%d] ind[%d] [%m]\n", ret, i);
//              exit(1);
//          }
//          else
//          {
//              str = (char*) (resxhead+1);
////              printf ("count[%u] ind[%04u] rslen[%d] logid[%u] name[%s] message[%s]\n",
////                      count, i, resxhead->detail_len,resxhead->log_id, resxhead->srvname, str);
//          }
//      }

  }

  close (sockfd);

  return 0;
}
Beispiel #17
0
int main(int argc, char **argv)
{
	int so_timestamping_flags = 0;
	int so_timestamp = 0;
	int so_timestampns = 0;
	int siocgstamp = 0;
	int siocgstampns = 0;
	int ip_multicast_loop = 0;
	char *interface;
	int i;
	int enabled = 1;
	int sock;
	struct ifreq device;
	struct ifreq hwtstamp;
	struct hwtstamp_config hwconfig, hwconfig_requested;
	struct sockaddr_in addr;
	struct ip_mreq imr;
	struct in_addr iaddr;
	int val;
	socklen_t len;
	struct timeval next;

	if (argc < 2)
		usage(0);
	interface = argv[1];

	for (i = 2; i < argc; i++) {
		if (!strcasecmp(argv[i], "SO_TIMESTAMP"))
			so_timestamp = 1;
		else if (!strcasecmp(argv[i], "SO_TIMESTAMPNS"))
			so_timestampns = 1;
		else if (!strcasecmp(argv[i], "SIOCGSTAMP"))
			siocgstamp = 1;
		else if (!strcasecmp(argv[i], "SIOCGSTAMPNS"))
			siocgstampns = 1;
		else if (!strcasecmp(argv[i], "IP_MULTICAST_LOOP"))
			ip_multicast_loop = 1;
		else if (!strcasecmp(argv[i], "SOF_TIMESTAMPING_TX_HARDWARE"))
			so_timestamping_flags |= SOF_TIMESTAMPING_TX_HARDWARE; //No message of desired type
		else if (!strcasecmp(argv[i], "SOF_TIMESTAMPING_TX_SOFTWARE"))
			so_timestamping_flags |= SOF_TIMESTAMPING_TX_SOFTWARE; //No message of desired type
		else if (!strcasecmp(argv[i], "SOF_TIMESTAMPING_RX_HARDWARE"))
			so_timestamping_flags |= SOF_TIMESTAMPING_RX_HARDWARE;
		else if (!strcasecmp(argv[i], "SOF_TIMESTAMPING_RX_SOFTWARE"))
			so_timestamping_flags |= SOF_TIMESTAMPING_RX_SOFTWARE;
		else if (!strcasecmp(argv[i], "SOF_TIMESTAMPING_SOFTWARE"))
			so_timestamping_flags |= SOF_TIMESTAMPING_SOFTWARE;
		else if (!strcasecmp(argv[i], "SOF_TIMESTAMPING_RAW_HARDWARE"))
			so_timestamping_flags |= SOF_TIMESTAMPING_RAW_HARDWARE;
		else
			usage(argv[i]);
	}

	sock = socket(PF_INET, SOCK_DGRAM/*SOCK_RAW*/, /*IPPROTO_UDP*/0);
	if (sock < 0)
		bail("socket");

	memset(&device, 0, sizeof(device));
	strncpy(device.ifr_name, interface, sizeof(device.ifr_name));
	if (ioctl(sock, SIOCGIFADDR, &device) < 0)
		bail("getting interface IP address");

	memset(&hwtstamp, 0, sizeof(hwtstamp));
	strncpy(hwtstamp.ifr_name, interface, sizeof(hwtstamp.ifr_name));
	hwtstamp.ifr_data = (void *)&hwconfig;
	memset(&hwconfig, 0, sizeof(hwconfig));
	hwconfig.tx_type =
		(so_timestamping_flags & SOF_TIMESTAMPING_TX_HARDWARE) ?
		HWTSTAMP_TX_ON : HWTSTAMP_TX_OFF;
	hwconfig.rx_filter =
		(so_timestamping_flags & SOF_TIMESTAMPING_RX_HARDWARE) ?
		HWTSTAMP_FILTER_PTP_V1_L4_SYNC : HWTSTAMP_FILTER_NONE;
	hwconfig_requested = hwconfig;
	if (ioctl(sock, SIOCSHWTSTAMP, &hwtstamp) < 0) {
		if ((errno == EINVAL || errno == ENOTSUP) &&
		    hwconfig_requested.tx_type == HWTSTAMP_TX_OFF &&
		    hwconfig_requested.rx_filter == HWTSTAMP_FILTER_NONE)
			printf("SIOCSHWTSTAMP: disabling hardware time stamping not possible\n");
		else
			bail("SIOCSHWTSTAMP");
	}
	printf("SIOCSHWTSTAMP: tx_type %d requested, got %d; rx_filter %d requested, got %d\n",
	       hwconfig_requested.tx_type, hwconfig.tx_type,
	       hwconfig_requested.rx_filter, hwconfig.rx_filter);

	/* bind to PTP port */
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	addr.sin_port = htons(319 /* PTP event port */);
	if (bind(sock,
		 (struct sockaddr *)&addr,
		 sizeof(struct sockaddr_in)) < 0)
		bail("bind");

	/* set multicast group for outgoing packets */
	inet_aton("224.0.1.130", &iaddr); /* alternate PTP domain 1 */
	addr.sin_addr = iaddr;
	imr.imr_multiaddr.s_addr = iaddr.s_addr;
	imr.imr_interface.s_addr =
		((struct sockaddr_in *)&device.ifr_addr)->sin_addr.s_addr;
	if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF,
		       &imr.imr_interface.s_addr, sizeof(struct in_addr)) < 0)
		bail("set multicast");

	/* join multicast group, loop our own packet */
	if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
		       &imr, sizeof(struct ip_mreq)) < 0)
		bail("join multicast group");

	if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP,
		       &ip_multicast_loop, sizeof(enabled)) < 0) {
		bail("loop multicast");
	}

	/* set socket options for time stamping */
	if (so_timestamp &&
		setsockopt(sock, SOL_SOCKET, SO_TIMESTAMP,
			   &enabled, sizeof(enabled)) < 0)
		bail("setsockopt SO_TIMESTAMP");

	if (so_timestampns &&
		setsockopt(sock, SOL_SOCKET, SO_TIMESTAMPNS,
			   &enabled, sizeof(enabled)) < 0)
		bail("setsockopt SO_TIMESTAMPNS");

	if (so_timestamping_flags &&
		setsockopt(sock, SOL_SOCKET, SO_TIMESTAMPING,
			   &so_timestamping_flags,
			   sizeof(so_timestamping_flags)) < 0)
		bail("setsockopt SO_TIMESTAMPING");

	/* request IP_PKTINFO for debugging purposes */
	if (setsockopt(sock, SOL_IP, IP_PKTINFO,
		       &enabled, sizeof(enabled)) < 0)
		printf("%s: %s\n", "setsockopt IP_PKTINFO", strerror(errno));

	/* verify socket options */
	len = sizeof(val);
	if (getsockopt(sock, SOL_SOCKET, SO_TIMESTAMP, &val, &len) < 0)
		printf("%s: %s\n", "getsockopt SO_TIMESTAMP", strerror(errno));
	else
		printf("SO_TIMESTAMP %d\n", val);

	if (getsockopt(sock, SOL_SOCKET, SO_TIMESTAMPNS, &val, &len) < 0)
		printf("%s: %s\n", "getsockopt SO_TIMESTAMPNS",
		       strerror(errno));
	else
		printf("SO_TIMESTAMPNS %d\n", val);

	if (getsockopt(sock, SOL_SOCKET, SO_TIMESTAMPING, &val, &len) < 0) {
		printf("%s: %s\n", "getsockopt SO_TIMESTAMPING",
		       strerror(errno));
	} else {
		printf("SO_TIMESTAMPING %d\n", val);
		if (val != so_timestamping_flags)
			printf("   not the expected value %d\n",
			       so_timestamping_flags);
	}

	/* send packets forever every five seconds */
	gettimeofday(&next, 0);
	next.tv_sec = (next.tv_sec + 1) / 5 * 5;
	next.tv_usec = 0;
	while (1) {
		struct timeval now;
		struct timeval delta;
		long delta_us;
		int res;
		fd_set readfs, errorfs;

		gettimeofday(&now, 0);
		delta_us = (long)(next.tv_sec - now.tv_sec) * 1000000 +
			(long)(next.tv_usec - now.tv_usec);
		if (delta_us > 0) {
			/* continue waiting for timeout or data */
			delta.tv_sec = delta_us / 1000000;
			delta.tv_usec = delta_us % 1000000;

			FD_ZERO(&readfs);
			FD_ZERO(&errorfs);
			FD_SET(sock, &readfs);
			FD_SET(sock, &errorfs);
			printf("%ld.%06ld: select %ldus\n",
			       (long)now.tv_sec, (long)now.tv_usec,
			       delta_us);
			res = select(sock + 1, &readfs, 0, &errorfs, &delta);
			gettimeofday(&now, 0);
			printf("%ld.%06ld: select returned: %d, %s\n",
			       (long)now.tv_sec, (long)now.tv_usec,
			       res,
			       res < 0 ? strerror(errno) : "success");
			if (res > 0) {
				if (FD_ISSET(sock, &readfs))
					printf("ready for reading\n");
				if (FD_ISSET(sock, &errorfs))
					printf("has error\n");

//				printf("read from socket error queue...\n");
//				recvpacket(sock, MSG_ERRQUEUE,
//						siocgstamp,
//						siocgstampns);

				printf("read from socket queue...\n");
				print_sock_buff_opt(sock);
				recvpacket(sock, 0,
					   siocgstamp,
					   siocgstampns);
//				print_sock_buff_opt(sock);
				printf("read from socket error queue...\n");
				print_sock_buff_opt(sock);
				recvpacket(sock, MSG_ERRQUEUE,
					   siocgstamp,
					   siocgstampns);
//				print_sock_buff_opt(sock);
			}
		} else {
			/* write one packet */
			printf("write to socket queue...\n");
//			print_sock_buff_opt(sock);
			sendpacket(sock,
				   (struct sockaddr *)&addr,
				   sizeof(addr));
			sendpacket(sock,
				   (struct sockaddr *)&addr,
				   sizeof(addr));
//			print_sock_buff_opt(sock);
			next.tv_sec += 2;

			continue;
		}
	}

	return 0;
}
Beispiel #18
0
void
keyboard(unsigned char key, int x, int y)
{
    static int fullscreen = 0;
    static int old_x = 50;
    static int old_y = 50;
    static int old_width = 512;
    static int old_height = 512;
    static int s = 0;

	if(key=='w'||key=='W')
		glClearColor(0.0,1.0,0.0,1.0);
	if(key=='p'||key=='P')
		glClearColor(0.0,0.0,1.0,1.0);
	if(key=='e'||key=='E')
		glClearColor(0.5,0.0,1.0,1.0);
	if(key=='r'||key=='R')
		glClearColor(0.4,1.0,0.5,1.0);
	if(key=='t'||key=='T')
		glClearColor(0.8,0.9,0.6,1.0);
	if(key=='y'||key=='Y')
		glClearColor(0.5,0.4,0.0,1.0);
	if(key=='u'||key=='U')
		glClearColor(1.0,1.0,0.0,1.0);
	if(key=='i'||key=='I')
		glClearColor(1.0,1.4,2.0,1.0);
	if(key=='o'||key=='O')
		glClearColor(0.0,0.0,0.0,1.0);
	if(key=='q'||key=='Q')
		glClearColor(1.0,0.0,0.0,1.0);

    switch (key) {
    case 27:
        bail(0);
	break;

    case 'f':
	if (type == PS_WATERFALL)
	    type = PS_FOUNTAIN;
	else if (type == PS_FOUNTAIN)
	    type = PS_WATERFALL;
	break;

    case 's':
	draw_spheres++;
	if (draw_spheres > NUM_SPHERES)
	    draw_spheres = 0;
	break;

    case 'S':
	printf("PSsphere spheres[NUM_SPHERES] = {/* position of spheres */\n");
	for (s = 0; s < NUM_SPHERES; s++) {
	    printf("  { %g, %g, %g, %g },\n", 
		   spheres[s].x, spheres[s].y,
		   spheres[s].z, spheres[s].radius);
	}
	printf("};\n");
	break;

    case 'l':
	points = !points;
	break;

    case 'c':
	point_size++;
	glPointSize(point_size);/*specifies the rasterized diameter of both aliased and antialiased points*/
	break;
	
    case 'k':
	point_size--;
	if (point_size < 1)
	    point_size = 1;
	glPointSize(point_size);
	break;
	
    case '+':
	flow += 100;
	if (flow > num_particles)
	    flow = num_particles;
	printf("%g particles/second\n", flow);
	break;

    case '-':
	flow -= 100;
	if (flow < 0)
	    flow = 0;
	printf("%g particles/second\n", flow);
	break;

    case '#':
	frame_rate = !frame_rate;
	break;

    case '~':
	fullscreen = !fullscreen;
	if (fullscreen) {
	    old_x = glutGet(GLUT_WINDOW_X);
	    old_y = glutGet(GLUT_WINDOW_Y);
	    old_width = glutGet(GLUT_WINDOW_WIDTH);
	    old_height = glutGet(GLUT_WINDOW_HEIGHT);
	    glutFullScreen();
	} else {
	    glutReshapeWindow(old_width, old_height);
	    glutPositionWindow(old_x, old_y);
	}
	break;

    case 'z':
	s++;
	if (s >= NUM_SPHERES)
	    s = 0;
	break;

    case '4':
	spheres[s].x -= 0.05;
	break;

    case '6':
	spheres[s].x += 0.05;
	break;

    case '2':
	spheres[s].y -= 0.05;
	break;

    case '8':
	spheres[s].y += 0.05;
	break;

    case '7':
	spheres[s].z -= 0.05;
	break;

    case '3':
	spheres[s].z += 0.05;
	break;

    case '9':
	spheres[s].radius += 0.05;
	break;

    case '1':
	spheres[s].radius -= 0.05;
	break;

    }
}
Beispiel #19
0
void
ss_mouse(int button, int state, int x, int y)
{
    bail(0);
}
Beispiel #20
0
void
ss_keyboard(char key, int x, int y)
{
    bail(0);
}
Beispiel #21
0
int main(void)
{
	lua_State *L;

	L = luaL_newstate();                        /* Create Lua state variable */
	luaL_openlibs(L);                           /* Load Lua libraries */

	if (luaL_loadfile(L, "callfuncscript.lua")) /* Load but don't run the Lua script */
		bail(L, "luaL_loadfile() failed");      /* Error out if file can't be read */

	/* ABOVE HERE IS HELLO WORLD CODE */

	// All over the Internet, including on some of the Lua project's own documentation, you'll see hints basically telling you that to call a C subroutine you do:
	// 
	// lua_getglobals(L, "subroutine_name")
	// push_args_to_subroutine
	// if(lua_pcall(L, num_of_args, num_of_returns, 0)
	//    error_routine();
	// 
	// These Internet instructions say nothing about doing a priming lua_pcall(), and if you do not do a priming lua_pcall(), you'll get an error message something like this:
	// 
	// attempt to call a nil value
	// 
	// If you get the preceding error message and don't know it's caused by lack of a priming lua_pcall() (or priming lua_call() or priming dofile()), you're about to have several hours or maybe even days of frustration. Mailing list threads old and new about this error basically tell you RTFM or RTFW, but of course we locals know it was reading the web that got you into this problem in the first place.
	// 
	// I saw one guy who took the opportunity to tell the asker "I'm trying to help you help yourself but you won't take the help, so now I'm putting you on my list of people I won't help." All for what we locals know was probably a simple lack of a priming run THAT SEEMS NOT TO BE DOCUMENTED ANYWHERE!
	// 
	// Before calling a function in a Lua script, do that priming run first!!!!!!
	// 这个是必须的,不然报错
	// 在这里会运行所有非函数的lua语句
	// FATAL ERROR:
	// lua_pcall() failed: attempt to call a nil value

	if (lua_pcall(L, 0, 0, 0))                  /* PRIMING RUN. FORGET THIS AND YOU'RE TOAST */
	{
		bail(L, "lua_pcall() failed");          /* Error out if Lua file has an error */
		printf("error.......\n");
	}
	else
	{
		printf("success.......\n");
	}


	// void lua_getglobal (lua_State *L, const char *name);
	// Pushes onto the stack the value of the global name. It is defined as a macro:

    // #define lua_getglobal(L,s)  lua_getfield(L, LUA_GLOBALSINDEX, s)
	printf("-------------------\n");
	// 此时 把tellme 函数放入栈上 ,调用lua_pcall 执行这个函数
	//  push that function on the stack with lua_getglobal(),
	lua_getglobal(L, "tellme");                 /* Tell what function to run */

	/* BELOW HERE IS THE HELLO WORLD CODE */
	printf("In C, calling Lua\n");

	// The only change over the Hello World code is a priming run and pushing the tellme() Lua function via the lua_getglobal() call. Note that the second lua_pcall() still has its second arg, number_of_args, of 0, because you're not sending an argument to the Lua function tellme().
	if (lua_pcall(L, 0, 0, 0))                  /* Run the function */
		bail(L, "lua_pcall() failed");          /* Error out if Lua file has an error */
	printf("Back in C again\n");

	lua_close(L);                               /* Clean up, free the Lua state var */

	return 0;
}
Beispiel #22
0
int ParseJSON(cJSON *node, const char *box_id)
{
	FILE *stream = NULL;
	char buf[512] = {0};
	char *result_url;
	cJSON *cmdArray = cJSON_GetObjectItem(node, "remote_control");
        ghttp_request *req_remotectl_feedback;
        char *id = NULL, *content = NULL;
        char *command = NULL, *ptr = NULL, *p = NULL;

        if(!cmdArray)
	{
                bail("parse result : json has no node named remote_control");
		return 0;
	}

        char *errorMsg = NULL;
        cJSON *cmdList = cmdArray->child;
        while(cmdList != NULL)
        {
                if(cJSON_GetObjectItem(cmdList, "id")->valuestring != NULL)
                {
                        id = cJSON_GetObjectItem(cmdList, "id")->valuestring;
                        printf("id : %s\n", id);
                }
		
		if(cJSON_GetObjectItem(cmdList, "content")->valuestring != NULL)
                {
                        content = cJSON_GetObjectItem(cmdList, "content")->valuestring; 
                        printf("content : %s\n", content);
                }
                 
		stream = NULL;
		
                if(strcmp(content, "reboot") == 0)
		{
			printf("command : reboot\n");
                        printf("send http feedback...\n");
                        result_url = (char *)malloc(150);
        	        req_remotectl_feedback = ghttp_request_new();
                	sprintf(result_url, "http://www.ailvgobox.com/box_manage/remote_feedback.php?box_id=%s&id=%s&result=reboot_ok", box_id, id);
                        printf("result_url : %s\n", result_url);
                        result_url[149] = '\0';
                        send_http_request(req_remotectl_feedback, result_url);
                        ghttp_request_destroy(req_remotectl_feedback);
                        free(result_url);
                        printf("command : reboot, run!\n");
			stream = popen(content, "r");
                        pclose(stream);
		}
		
                ptr = strstr(content, "@");

                if(!ptr)
                {
                        printf("content : one command!\n");
                    
                        printf("command : %s, run!\n", content);

                        stream = popen(content, "r");
		        memset(buf, 0, 512);
                        fread(buf, sizeof(char), sizeof(buf), stream);
                        buf[511] = '\0';
                        printf("buf : %s\n", buf);
                        pclose(stream);
			str_rep(buf, '\n', ',');
                        str_rep(buf, ' ', '-');
			if(strlen(buf) == 0)
                              strcpy(buf, "no_result"); 
 
                        printf("send http feedback...\n");
			result_url = (char *)malloc(strlen(buf)+150);
			memset(result_url, 0, strlen(buf)+150);
			req_remotectl_feedback = ghttp_request_new();
			sprintf(result_url, "http://www.ailvgobox.com/box_manage/remote_feedback.php?box_id=%s&id=%s&result=%s", box_id, id, buf);
			printf("result_url : %s\n", result_url);
			result_url[strlen(buf)+150-1] = '\0';
			send_http_request(req_remotectl_feedback, result_url);
			ghttp_request_destroy(req_remotectl_feedback);
			free(result_url);
                }
                else
                {
                        printf("content : multiple command!\n");
                        
                        command = strtok_r(content, "@", &p);

                        while(command)
                        {  
                              printf("command : %s\n", command);

                              if(strcmp(command, "reboot") == 0)
                              {
                                      printf("command : reboot\n");
                                      printf("send http feedback...\n");
                                      result_url = (char *)malloc(150);
                                      req_remotectl_feedback = ghttp_request_new();
                                      sprintf(result_url, "http://www.ailvgobox.com/box_manage/remote_feedback.php?box_id=%s&id=%s&result=reboot_ok", box_id, id);
                                      printf("result_url : %s\n", result_url);
                                      result_url[149] = '\0';
                                      send_http_request(req_remotectl_feedback, result_url);
                                      ghttp_request_destroy(req_remotectl_feedback);
                                      free(result_url);
                                      printf("command : reboot, run!\n");
                                      stream = popen(command, "r");
                                      pclose(stream);
                               }
                              else
                              {
                                      printf("command : %s, run!\n", command);
                                      stream = popen(command, "r");
                                      memset(buf, 0, 512);
                                      fread(buf, sizeof(char), sizeof(buf), stream);
                                      buf[511] = '\0';
                                      printf("buf : %s\n", buf);
                                      pclose(stream);
                                      str_rep(buf, '\n', ',');
                                      str_rep(buf, ' ', '-');
                                      if(strlen(buf) == 0)
                                              strcpy(buf, "no_result");
                                      printf("send http feedback...\n");
                                      result_url = (char *)malloc(strlen(buf)+150);
                                      memset(result_url, 0, strlen(buf)+150);
                                      req_remotectl_feedback = ghttp_request_new();
                                      sprintf(result_url, "http://www.ailvgobox.com/box_manage/remote_feedback.php?box_id=%s&id=%s&result=%s", box_id, id, buf);
                                      printf("result_url : %s\n", result_url);
                                      result_url[strlen(buf)+150-1] = '\0';
                                      send_http_request(req_remotectl_feedback, result_url);
                                      ghttp_request_destroy(req_remotectl_feedback);
                                      free(result_url);
                               }  
                              
                              command = strtok_r(NULL, "@", &p);  
                        }
                }
                
		cmdList = cmdList->next;
      }
}
Beispiel #23
0
char *send_http_request(ghttp_request *req, char *uri)
{
	#define malloc_size 5120
	ghttp_status req_status;
	unsigned long rec_bytes_total = 0;
	unsigned long buffer_size = 0;
	unsigned long rec_bytes_current = 0;

	char *buffer = (char *)malloc(sizeof(char) * malloc_size);
	if(!buffer)
	{
		bail("malloc space error");
		return NULL;
	}
	else
	{
		memset(buffer, 0, malloc_size);
		buffer_size = malloc_size;
	}

	if(ghttp_set_uri(req, uri) < 0)
	{
		bail("ghttp_set_uri");
		return NULL;
	}
	if(ghttp_prepare(req) < 0)
	{
		bail("ghttp_prepare");
		return NULL;
	}
	if(ghttp_set_type(req, ghttp_type_get) == -1)
	{
		bail("ghttp_set_type");
		return NULL;
	}
	if(ghttp_set_sync(req, ghttp_async) < 0)
	{
		bail("ghttp_set_sync");
		return NULL;
	}
	
	do {
                status(req, "conn");
                req_status = ghttp_process(req);

                if(req_status == ghttp_error)
                {
                        fprintf(stderr, "ghttp_process: %s\n", ghttp_get_error(req));
                        return NULL;
                }

                if(req_status != ghttp_error && ghttp_get_body_len(req) > 0)
                {
                        rec_bytes_current = ghttp_get_body_len(req);
                        rec_bytes_total += rec_bytes_current;
			
			while(rec_bytes_total > buffer_size)
			{
				buffer = (char *)realloc(buffer, buffer_size + malloc_size);
				if(!buffer)
				{
					bail("realloc error");
					return NULL;
				}
				buffer_size += malloc_size;
			}
			
			strncat(buffer, ghttp_get_body(req), rec_bytes_current);
                        buffer[rec_bytes_total] = '\0';
                        ghttp_flush_response_buffer(req);
		}
	} while(req_status == ghttp_not_done);  
	
	ghttp_clean(req);
	return buffer;
}
Beispiel #24
0
int
main(void)
{
    struct kerberos_config *config;
    const char *cache;
    struct remctl *r;
    struct remctl_output *output;
    int status;
    const char *command[] = { "test", "test", NULL };

    /* Set up Kerberos and remctld. */
    config = kerberos_setup(TAP_KRB_NEEDS_KEYTAB);
    remctld_start(config, "data/conf-simple", (char *) 0);

    plan(12);

    /* Get the current ticket cache and then change KRB5CCNAME. */
    cache = getenv("KRB5CCNAME");
    if (cache == NULL)
        bail("failed to set KRB5CCNAME");
    putenv((char *) "KRB5CCNAME=./nonexistent-file");

    /* Connecting without setting the ticket cache should fail. */
    r = remctl_new();
    ok(r != NULL, "remctl_new");
    ok(!remctl_open(r, "127.0.0.1", 14373, config->principal),
       "remctl_open to 127.0.0.1");

    /* Set the ticket cache and connect to 127.0.0.1 and run a command. */
    status = remctl_set_ccache(r, cache);
    if (!status) {
        is_string("setting credential cache not supported", remctl_error(r),
                  "remctl_set_ccache failed with correct error");
        skip_block(9, "credential cache setting not supported");
    } else {
        ok(remctl_set_ccache(r, cache), "remctl_set_ccache");
        ok(remctl_open(r, "127.0.0.1", 14373, config->principal),
           "remctl_open to 127.0.0.1");
        ok(remctl_command(r, command), "remctl_command");
        output = remctl_output(r);
        ok(output != NULL, "remctl_output #1");
        if (output == NULL)
            ok_block(3, 0, "remctl_output failed");
        else {
            is_int(REMCTL_OUT_OUTPUT, output->type, "output token");
            ok(memcmp("hello world\n", output->data,
                      strlen("hello world\n")) == 0,
               "correct output");
            is_int(strlen("hello world\n"), output->length, "correct length");
        }
        output = remctl_output(r);
        ok(output != NULL, "remctl_output #2");
        if (output == NULL)
            ok_block(2, 0, "remctl_output failed");
        else {
            is_int(REMCTL_OUT_STATUS, output->type, "status token");
            is_int(0, output->status, "status is correct");
        }
    }
    remctl_close(r);

    return 0;
}
Beispiel #25
0
//
// FUNCTION NAME: gsm_verify_chv
//
// DESCRIPTION: this is a wrapper for pcsclite SCardTransmit function, arranged
//              to transmit a VERIFY CHV command to the card so that the access
//              status CHV1 can be reached.
// 
// INPUT PARAMETERS: 
//   SCARDHANDLE       hCard               handle for a connection to the card.
//   SCARD_IO_REQUEST* dwActiveProtocol    pointer to the pcsclite defined
//                                         structure that implement the desired
//                                         protocol.
//   BYTE_LIST         chv1                value of chv1 to be verified.
//
// OUTPUT PARAMETERS: RESPONSE*
//   Returns the response from the SIM card.
//
// NOTES:
//   - This function verifies exclusively CHV1. If CHV2 verification will be
//     needed in the future, then the function could be easily changed.
//   - This function doesn't work because CHV1 value has to be coded as
//     specified in CCITT T.50 (ISO 646 - 1983)
//
RESPONSE* gsm_verify_chv(SCARDHANDLE hCard, SCARD_IO_REQUEST* dwActiveProtocol,
                         BYTE_LIST* chv1) {

  int i;
  LONG rv;
  RESPONSE* response = create_b_list();

  DWORD dwSendLength, pcbRecvLength;
  SCARD_IO_REQUEST pioRecvPci;

  //We're about to verify CHV1
  BYTE pbSendBuffer[13] = {GSM_CLASS, VERIFY_CHV, 0x00, 0x01, 0x08,
                           blist_get_element(chv1,0),
                           blist_get_element(chv1,1),
                           blist_get_element(chv1,2),
                           blist_get_element(chv1,3),
                           blist_get_element(chv1,4),
                           blist_get_element(chv1,5),
                           blist_get_element(chv1,6),
                           blist_get_element(chv1,7)};
  BYTE pbRecvBuffer[12]; //SW1 e SW2 included

  dwSendLength = sizeof(pbSendBuffer);
  pcbRecvLength = sizeof(pbRecvBuffer);

  printf("\nDEBUG: pcbRecvLength = %i\n", pcbRecvLength);

  inizializza_array(pbRecvBuffer,(int)sizeof(pbRecvBuffer));

  rv = SCardTransmit(hCard, SCARD_PCI_T0, pbSendBuffer, dwSendLength,
                     &pioRecvPci, pbRecvBuffer, &pcbRecvLength);

  printf("\nDEBUG: pcbRecvLength = %i\n", pcbRecvLength);
  printf("\nDEBUG: rv = %i\n", rv);

  switch(rv) {
    case SCARD_E_NOT_TRANSACTED: {
      int errno_saved = errno;
      printf("Summary of input data:\n");
      printf("SENT APDU GET RESPONSE: ");
      print_array(pbSendBuffer,(int)sizeof(pbSendBuffer));
      printf("\nLength of sent APDU GET RESPONSE: %i\n", dwSendLength);
      printf("RECEIVED RESPONSE: ");
      print_array(pbRecvBuffer,pcbRecvLength);
      printf("\n");
      printf("Length of received response: %i.\n", pcbRecvLength);
      bail_with_errno(EXIT_FAILURE, errno_saved, "gsm_verify_chv: ", ERR_APDU_EXCHANGE_FAILED);
    }
    case SCARD_E_INVALID_VALUE: {
      bail(EXIT_FAILURE, "gsm_verify_chv: ", ERR_INVALID_PARAMETER_VALUE);
    }
    case SCARD_E_READER_UNAVAILABLE: {
      bail(EXIT_FAILURE, "gsm_verify_chv: ", ERR_READER_UNAVAILABLE);
    }
    case SCARD_E_PROTO_MISMATCH: {
      bail(EXIT_FAILURE, "gsm_verify_chv: ", ERR_PROTOCOL_DIFFERENT);
    }
    case SCARD_W_RESET_CARD: {
      bail(EXIT_FAILURE, "gsm_verify_chv: ", ERR_CARD_RESET);
    }
    case SCARD_W_REMOVED_CARD: {
      bail(EXIT_FAILURE, "gsm_verify_chv: ", ERR_CARD_REMOVED);
    }
    case SCARD_E_INVALID_HANDLE: {
      bail(EXIT_FAILURE, "gsm_verify_chv: ", ERR_INVALID_CONTEXT_HANDLER);
    }
    case SCARD_S_SUCCESS: {
      printf("APDU VERIFY CHV successfully transmitted.\n");
      printf("Summary of input data:\n");
      printf("SENT APDU VERIFY CHV: ");
      print_array(pbSendBuffer,dwSendLength);
      printf("\nLength of sent APDU VERIFY CHV: %i\n", dwSendLength);
      printf("RECEIVED RESPONSE: ");
      print_array(pbRecvBuffer,pcbRecvLength);
      printf("\n");
      printf("Length of received response: %i.\n", pcbRecvLength);
      getchar();
      getchar();
      break;
    }
    default: {
      int errno_saved = errno;
      printf("The value returned is: %.2X",rv);
      bail_with_errno(EXIT_FAILURE, errno_saved, "gsm_verify_chv: ", ERR_WRONG_RETURN_VALUE);
    }
  }

  for (i=0; i<pcbRecvLength; i++) {
    blist_add_element(response, pbRecvBuffer[i]);
  }

  printf("\nDEBUG: EXIT gsm_verify_chv.\n");

  return(response);
}
Beispiel #26
0
//
// FUNCTION NAME: SIM_Status
//
// DESCRIPTION: this is a wrapper for pcsclite SCardStatus function.
//              Its job is to call that function and manage error messages
//              eventually returned.
//
// INPUT PARAMETERS: 
//   SCARDHANDLE hCard    connection handler for this card.
//
// OUTPUT PARAMETERS: RESPONSE*
//   If nothing goes wrong, atr from the card is returned.
//
RESPONSE* SIM_Status(SCARDHANDLE hCard) {
  LONG rv;
  DWORD pcchReaderLen, dwState, dwProtocol;
  BYTE pbAtr[MAX_ATR_SIZE];
  DWORD pcbAtrLen;

  int const buf_size = 1024;
  LPSTR lettori = (LPSTR)malloc(sizeof(char) * buf_size);
  pcchReaderLen = buf_size;
  
  rv = SCardStatus(hCard, lettori, &pcchReaderLen, &dwState, &dwProtocol, pbAtr, &pcbAtrLen);
  switch(rv) {
    case SCARD_E_READER_UNAVAILABLE: {
      bail(EXIT_FAILURE, "SIM_Status:", ERR_READER_REMOVED);
    }
    case SCARD_E_INSUFFICIENT_BUFFER: {
      bail(EXIT_FAILURE, "SIM_Status:",ERR_INSUFFICIENT_BUFFER);
    }
    case SCARD_E_INVALID_HANDLE: {
      bail(EXIT_FAILURE, "SIM_Status:",ERR_INVALID_CONTEXT_HANDLER);
    }
    case SCARD_S_SUCCESS: {
      printf("\n\nCARD STATUS = :\n");
      switch(dwState) {
        case SCARD_ABSENT: {
          printf("\tThere is no card into the reader.");
          break;
        }
        case SCARD_PRESENT: {
          printf("\tCard present but not ready to be used.");
          break;
        }
        case SCARD_SWALLOWED: {
          printf("\tCard present and ready to be used, but not powered.");
          break;
        }
        case SCARD_POWERED: {
          printf("\tCard powered, but mode not recognized by the driver.");
          break;
        }
        case SCARD_NEGOTIABLE: {
          printf("\tCard reset and waiting PTS negotiation.");
          break;
        }
        case SCARD_SPECIFIC: {
          printf("\tCard reset and specific communication protocols established.");
          break;
        }
        default: {
          printf("\tCARD ANSWERED WITH AN UNKNOWN STATE: %.2X.",dwState);
        }
      }

      printf("\n\nCommunication protocol is:\n");
      switch(dwProtocol) {
        case SCARD_PROTOCOL_T0: {
          printf("\tT=0.\n");
          break;
        }
        case SCARD_PROTOCOL_T1: {
          printf("\tT=1.\n");
          break;
        }
        default: {
          printf("\tCARD ANSWERED WITH AN UNKNOWN PROTOCOL.\n");
        }
      }

      printf("\n\nATR = ");
      print_array(pbAtr,pcbAtrLen);
      printf("\n\nATR length = %i.\n",pcbAtrLen);

      RESPONSE* resp = create_b_list();
      int i;
      for(i=0; i<pcbAtrLen; i++) {
        blist_add_element(resp,pbAtr[i]);
      }

      return(resp);
    }
    default: {
      int errno_saved = errno;
      printf("\nValue returned =  %.2X\n",rv);
      bail_with_errno(EXIT_FAILURE, errno_saved, "SIM_Status:",ERR_WRONG_RETURN_VALUE);
    }
  }
}
Beispiel #27
0
//
// FUNCTION NAME: gsm_select
//
// DESCRIPTION: this is a wrapper for pcsclite SCardTransmit function, arranged
//              to transmit a SELECT command to the card.
//
// INPUT PARAMETERS: 
//   SCARDHANDLE hCard                     handle for a connection to the card.
//   SCARD_IO_REQUEST* dwActiveProtocol    pointer to the pcsclite defined
//                                         structure that implement the desired
//                                         protocol.
//   int id_file                           file of the card to select.
//
// OUTPUT PARAMETERS: RESPONSE*
//   Returns a pointer to the raw response to the SELECT command from the card.
//
// NOTES:
//   - For the pcsclite manual is not complete on values returned by its API
//     functions, further cases may be included in the switch(rv) in the
//     future.
//   - Error handling is up to this function: every time something goes wrong,
//     it exits.
//
RESPONSE* gsm_select(SCARDHANDLE hCard, SCARD_IO_REQUEST* dwActiveProtocol,
                     long int id_file) {

  int i;
  LONG rv;
  BYTE pbRecvBuffer[2]; // I expect a response composed only by the status
                        // words
  BYTE pbSendBuffer[7] = {GSM_CLASS, SELECT, 0x00, 0x00, 0x02,
                          (BYTE)((id_file & 0xFF00)>>8), // this is the msb of
                                                         // the address
                          (BYTE)(id_file & 0x00FF)};     // this is the lsb
  DWORD dwSendLength = (int)sizeof(pbSendBuffer);
  DWORD pcbRecvLength = (int)sizeof(pbRecvBuffer);
  SCARD_IO_REQUEST pioRecvPci;
  RESPONSE* response = create_b_list();
  
  if ((id_file < 0x0000) || (id_file > 0xFFFF)) {
    bail(EXIT_FAILURE, "gsm_select: ","id_file passed was out of range. It must remain into the interval 0x0000 - 0xFFFF");
    exit(EXIT_FAILURE);
  }

  rv = SCardTransmit(hCard, dwActiveProtocol, pbSendBuffer, dwSendLength,
                     &pioRecvPci, pbRecvBuffer, &pcbRecvLength);
  switch(rv) {
    case SCARD_E_NOT_TRANSACTED: {
      bail(EXIT_FAILURE, "SCardTransmit:", ERR_APDU_EXCHANGE_FAILED);
    }
    case SCARD_E_INVALID_VALUE: {
      bail(EXIT_FAILURE, "SCardTransmit", ERR_INVALID_PARAMETER_VALUE);
    }
    case SCARD_E_READER_UNAVAILABLE: {
      bail(EXIT_FAILURE, "SCardTransmit", ERR_READER_UNAVAILABLE);
    }
    case SCARD_E_PROTO_MISMATCH: {
      bail(EXIT_FAILURE, "SCardTransmit", ERR_PROTOCOL_DIFFERENT);
    }
    case SCARD_W_RESET_CARD: {
      bail(EXIT_FAILURE, "SCardTransmit", ERR_CARD_RESET);
    }
    case SCARD_W_REMOVED_CARD: {
      bail(EXIT_FAILURE, "SCardTransmit", ERR_CARD_REMOVED);
    }
    case SCARD_E_INVALID_HANDLE: {
      bail(EXIT_FAILURE, "SCardTransmit", ERR_INVALID_CONTEXT_HANDLER);
    }
    case SCARD_S_SUCCESS: { //DEBUG
      //printf("APDU SELECT successfully transmitted.\n");
      //printf("Summary of input data:\n");
      //printf("SENT APDU SELECT: ");
      //print_array(pbSendBuffer,dwSendLength);
      //printf("\nLength of sent APDU SELECT: %i\n", dwSendLength);
      //printf("RECEIVED RESPONSE: ");
      //print_array(pbRecvBuffer,pcbRecvLength);
      //printf("\n");
      //printf("Length of received response: %i.\n", pcbRecvLength);
      break;

    }
    default: {
      bail(EXIT_FAILURE, "SCardTransmit", ERR_WRONG_RETURN_VALUE);
    }
  }

  for (i=0; i<pcbRecvLength; i++) {
    blist_add_element(response, pbRecvBuffer[i]);
  }

  if((*response).b_list_length != pcbRecvLength) {
    bail(EXIT_FAILURE, "gsm_select: ", PEB_WRONG_LIST_LENGTH);
    exit(EXIT_FAILURE);
  }
  
  return(response);
}


//
// FUNCTION NAME: gsm_get_response
//
// DESCRIPTION: this is a wrapper for pcsclite SCardTransmit function, arranged
//              to transmit a GET RESPONSE command to the card.
// 
// INPUT PARAMETERS: 
//   SCARDHANDLE hCard                     handle for a connection to the card.
//   SCARD_IO_REQUEST* dwActiveProtocol    pointer to the pcsclite defined
//                                         structure that implement the desired
//                                         protocol.
//   BYTE resp_lgth                        length of the response as learned
//                                         from a previous successfully SELECT.
//
// OUTPUT PARAMETERS:  RESPONSE*
//   Returns a pointer to the raw response to GET RESPONSE from the card.
//
// NOTES:
//   - For the pcsclite manual is not complete on values returned by its API
//     functions, further cases may be included in the switch(rv) in the
//     future.
//   - Error handling is up to this function: every time something goes wrong,
//     it exits.
//
RESPONSE* gsm_get_response(SCARDHANDLE hCard,
                           SCARD_IO_REQUEST* dwActiveProtocol,
                           BYTE resp_lgth) {

  int i;
  LONG rv;
  BYTE pbSendBuffer[5] = {GSM_CLASS, GET_RESPONSE, 0x00, 0x00, resp_lgth};
  BYTE pbRecvBuffer[resp_lgth+2]; //Buffer must contain SW1 and SW2 also
  DWORD dwSendLength = sizeof(pbSendBuffer);
  DWORD pcbRecvLength = sizeof(pbRecvBuffer);
  SCARD_IO_REQUEST pioRecvPci;
  RESPONSE* response = create_b_list();
  
  inizializza_array(pbRecvBuffer,(int)sizeof(pbRecvBuffer));

  rv = SCardTransmit(hCard, dwActiveProtocol, pbSendBuffer, dwSendLength,
                     &pioRecvPci, pbRecvBuffer, &pcbRecvLength);

  switch(rv) {
    case SCARD_E_NOT_TRANSACTED: {
      int errno_saved = errno;
      printf("Summary of input data:\n");
      printf("SENT APDU GET RESPONSE: ");
      print_array(pbSendBuffer,(int)sizeof(pbSendBuffer));
      printf("\nLength of sent APDU GET RESPONSE: %i\n", dwSendLength);
      printf("RECEIVED RESPONSE: ");
      print_array(pbRecvBuffer,pcbRecvLength);
      printf("\n");
      printf("Length of received response: %i.\n", pcbRecvLength);
      bail_with_errno(EXIT_FAILURE, errno_saved, "SCardTransmit", ERR_APDU_EXCHANGE_FAILED);
    }
    case SCARD_E_INVALID_VALUE: {
      bail(EXIT_FAILURE, "SCardTransmit", ERR_INVALID_PARAMETER_VALUE);
    }
    case SCARD_E_READER_UNAVAILABLE: {
      bail(EXIT_FAILURE, "SCardTransmit", ERR_READER_UNAVAILABLE);
    }
    case SCARD_E_PROTO_MISMATCH: {
      bail(EXIT_FAILURE, "SCardTransmit", ERR_PROTOCOL_DIFFERENT);
    }
    case SCARD_W_RESET_CARD: {
      bail(EXIT_FAILURE, "SCardTransmit", ERR_CARD_RESET);
    }
    case SCARD_W_REMOVED_CARD: {
      bail(EXIT_FAILURE, "SCardTransmit", ERR_CARD_REMOVED);
    }
    case SCARD_E_INVALID_HANDLE: {
      bail(EXIT_FAILURE, "SCardTransmit", ERR_INVALID_CONTEXT_HANDLER);
    }
    case SCARD_S_SUCCESS: {
      /*
      // DEBUG MESSAGES
      printf("APDU GET RESPONSE successfully transmitted.\n");
      printf("Summary of input data:\n");
      printf("SENT APDU GET RESPONSE: ");
      print_array(pbSendBuffer,dwSendLength);
      printf("\nLength of sent APDU GET RESPONSE: %i\n", dwSendLength);
      printf("RECEIVED RESPONSE: ");
      print_array(pbRecvBuffer,pcbRecvLength);
      printf("\n");
      printf("Length of received response: %i.\n", pcbRecvLength);
      */
      break;
    }
    default: {
      printf("The value returned is: %.2X",rv);
      bail(EXIT_FAILURE, "SCardTransmit", ERR_WRONG_RETURN_VALUE);
    }
  }

  for (i=0; i<pcbRecvLength; i++) {
    blist_add_element(response, pbRecvBuffer[i]);
  }

  return(response);
}
Beispiel #28
0
int main(int argc, char **argv)
{
	char pppLocal[16];		/* local IP to pass to pppd */
	char pppRemote[16];		/* remote IP address to pass to pppd */
	struct sockaddr_in addr;	/* client address */
	socklen_t addrlen;
	int arg = 1;
	int flags;
	struct in_addr inetaddrs[2];
	char *pppaddrs[2] = { pppLocal, pppRemote };

        gargc = argc;
        gargv = argv;

	/* fail if argument count invalid */
	if (argc < 7) {
		fprintf(stderr, "pptpctrl: insufficient arguments, see man pptpctrl\n");
		exit(2);
	}

	/* open a connection to the syslog daemon */
	openlog("pptpd", LOG_PID, PPTP_FACILITY);

	/* autoreap if supported */
	signal(SIGCHLD, SIG_IGN);

	/* note: update pptpctrl.8 if the argument list format is changed */
	GETARG_INT(pptpctrl_debug);
	GETARG_INT(noipparam);
	GETARG_VALUE(pppdxfig);
	GETARG_VALUE(speed);
	GETARG_VALUE(pppLocal);
	GETARG_VALUE(pppRemote);
	if (arg < argc) GETARG_INT(unique_call_id);
	if (arg < argc) GETARG_STRING(ppp_binary);
	if (arg < argc) GETARG_INT(pptp_logwtmp);
	
	if (pptpctrl_debug) {
		if (*pppLocal)
			syslog(LOG_DEBUG, "CTRL: local address = %s", pppLocal);
		if (*pppRemote)
			syslog(LOG_DEBUG, "CTRL: remote address = %s", pppRemote);
		if (*speed)
			syslog(LOG_DEBUG, "CTRL: pppd speed = %s", speed);
		if (*pppdxfig)
			syslog(LOG_DEBUG, "CTRL: pppd options file = %s", pppdxfig);
	}

	addrlen = sizeof(addr);
	if (getsockname(clientSocket, (struct sockaddr *) &addr, &addrlen) != 0) {
		syslog(LOG_ERR, "CTRL: getsockname() failed");
		syslog_perror("getsockname");
		close(clientSocket);
		bail(0);	/* NORETURN */
	}
	inetaddrs[0] = addr.sin_addr;

	addrlen = sizeof(addr);
	if (getpeername(clientSocket, (struct sockaddr *) &addr, &addrlen) != 0) {
		syslog(LOG_ERR, "CTRL: getpeername() failed");
		syslog_perror("getpeername");
		close(clientSocket);
		bail(0);	/* NORETURN */
	}
	inetaddrs[1] = addr.sin_addr;

	/* Set non-blocking */
	if ((flags = fcntl(clientSocket, F_GETFL, arg /* ignored */)) == -1 ||
	    fcntl(clientSocket, F_SETFL, flags|OUR_NB_MODE) == -1) {
		syslog(LOG_ERR, "CTRL: Failed to set client socket non-blocking");
		syslog_perror("fcntl");
		close(clientSocket);
		bail(0);	/* NORETURN */
	}

	
	/* Fiddle with argv */
        my_setproctitle(gargc, gargv, "pptpd [%s]%20c",
            inet_ntoa(addr.sin_addr), ' ');

	/* be ready for a grisly death */
	sigpipe_create();
	sigpipe_assign(SIGTERM);
	NOTE_VALUE(PAC, call_id_pair, htons(-1));
	NOTE_VALUE(PNS, call_id_pair, htons(-1));

	syslog(LOG_INFO, "CTRL: Client %s control connection started", inet_ntoa(addr.sin_addr));
	pptp_handle_ctrl_connection(pppaddrs, inetaddrs);
	syslog(LOG_DEBUG, "CTRL: Reaping child PPP[%i]", pppfork);
	if (pppfork > 0)
		waitpid(pppfork, NULL, 0);
	syslog(LOG_INFO, "CTRL: Client %s control connection finished", inet_ntoa(addr.sin_addr));

	bail(0);		/* NORETURN */
	return 1;		/* make gcc happy */
}
Beispiel #29
0
//
// FUNCTION NAME: gsm_read_transparent_file
//
// DESCRIPTION: this is a wrapper for pcsclite SCardTransmit function, arranged
//              to transmit a READ BINARY command to the card so that the
//              entire contents of the currently selected binary file can be
//              read.
// 
// INPUT PARAMETERS: 
//   SCARDHANDLE hCard                     handle for a connection to the card.
//   SCARD_IO_REQUEST* dwActiveProtocol    pointer to the pcsclite defined
//                                         structure that implement the desired
//                                         protocol.
//   BYTE block_dim                        length in byte of the block to read.
//
// OUTPUT PARAMETERS:  RESPONSE*
//   Returns a pointer to the raw content of the specified file.
//
// NOTES:
//   - For the pcsclite manual is not complete on values returned by its API
//     functions, further cases may be included in the switch(rv) in the
//     future.
//   - Changes need to be implemented to manage transparent files bigger
//     than 256 bytes.
//
RESPONSE* gsm_read_transparent_file (SCARDHANDLE hCard,
                                     SCARD_IO_REQUEST* dwActiveProtocol,
                                     BYTE block_dim) {

  int i;
  LONG rv;
  RESPONSE* response = create_b_list();

  DWORD dwSendLength, pcbRecvLength;
  SCARD_IO_REQUEST pioRecvPci;

  //Offset is hardcoded to 0x0000 because we are only interested in the
  //reading of the entire file
  BYTE pbSendBuffer[5] = {GSM_CLASS, READ_BINARY, 0, 0, block_dim};
  BYTE pbRecvBuffer[block_dim+2]; //SW1 e SW2 included

  dwSendLength = sizeof(pbSendBuffer);
  pcbRecvLength = sizeof(pbRecvBuffer);

  printf("\nDEBUG: pcbRecvLength = %i\n", pcbRecvLength);

  inizializza_array(pbRecvBuffer,(int)sizeof(pbRecvBuffer));

  rv = SCardTransmit(hCard, SCARD_PCI_T0, pbSendBuffer, dwSendLength,
                     &pioRecvPci, pbRecvBuffer, &pcbRecvLength);
  switch(rv) {
    case SCARD_E_NOT_TRANSACTED: {
      int errno_saved = errno;
      printf("Summary of input data:\n");
      printf("SENT APDU GET RESPONSE: ");
      print_array(pbSendBuffer,(int)sizeof(pbSendBuffer));
      printf("\nLength of sent APDU GET RESPONSE: %i\n", dwSendLength);
      printf("RECEIVED RESPONSE: ");
      print_array(pbRecvBuffer,pcbRecvLength);
      printf("\n");
      printf("Length of received response: %i.\n", pcbRecvLength);
      bail_with_errno(EXIT_FAILURE, errno_saved, "gsm_read_transparent_file: ", ERR_APDU_EXCHANGE_FAILED);
    }
    case SCARD_E_INVALID_VALUE: {
      bail(EXIT_FAILURE, "gsm_read_transparent_file: ", ERR_INVALID_PARAMETER_VALUE);
    }
    case SCARD_E_READER_UNAVAILABLE: {
      bail(EXIT_FAILURE, "gsm_read_transparent_file: ", ERR_READER_UNAVAILABLE);
    }
    case SCARD_E_PROTO_MISMATCH: {
      bail(EXIT_FAILURE, "gsm_read_transparent_file: ", ERR_PROTOCOL_DIFFERENT);
    }
    case SCARD_W_RESET_CARD: {
      bail(EXIT_FAILURE, "gsm_read_transparent_file: ", ERR_CARD_RESET);
    }
    case SCARD_W_REMOVED_CARD: {
      bail(EXIT_FAILURE, "gsm_read_transparent_file: ", ERR_CARD_REMOVED);
    }
    case SCARD_E_INVALID_HANDLE: {
      bail(EXIT_FAILURE, "gsm_read_transparent_file: ", ERR_INVALID_CONTEXT_HANDLER);
    }
    case SCARD_S_SUCCESS: {
      printf("APDU GET RESPONSE successfully transmitted.\n");
      printf("Summary of input data:\n");
      printf("SENT APDU GET RESPONSE: ");
      print_array(pbSendBuffer,dwSendLength);
      printf("\nLength of sent APDU GET RESPONSE: %i\n", dwSendLength);
      printf("RECEIVED RESPONSE: ");
      print_array(pbRecvBuffer,pcbRecvLength);
      printf("\n");
      printf("Length of received response: %i.\n", pcbRecvLength);
      break;
    }
    default: {
      int errno_saved = errno;
      printf("The value returned is: %.2X",rv);
      bail_with_errno(EXIT_FAILURE, errno_saved, "gsm_read_transparent_file: ", ERR_WRONG_RETURN_VALUE);
    }
  }

  for (i=0; i<pcbRecvLength; i++) {
    blist_add_element(response, pbRecvBuffer[i]);
  }

  return(response);
}
Beispiel #30
0
/*
 * pptp_handle_ctrl_connection
 *
 * 1. read a packet (should be start_ctrl_conn_rqst)
 * 2. reply to packet (send a start_ctrl_conn_rply)
 * 3. proceed with GRE and CTRL connections
 *
 * args: pppaddrs - ppp local and remote addresses (strings)
 *       inetaddrs - local and client socket address
 * retn: 0 success, -1 failure
 */
static void pptp_handle_ctrl_connection(char **pppaddrs, struct in_addr *inetaddrs)
{

	/* For echo requests used to check link is alive */
	int echo_wait = FALSE;		/* Waiting for echo? */
	u_int32_t echo_count = 0;	/* Sequence # of echo */
	time_t echo_time = 0;		/* Time last echo req sent */
	struct timeval idleTime;	/* How long to select() */

	/* General local variables */
	ssize_t rply_size;		/* Reply packet size */
	fd_set fds;			/* For select() */
	int maxfd = clientSocket;	/* For select() */
	int send_packet;		/* Send a packet this time? */
#if BSDUSER_PPP || SLIRP
/* not needed by stuff which uses socketpair() in startCall() */
#define init 1
#else
	int init = 0;			/* Has pppd initialized the pty? */
#endif
	int pty_fd = -1;		/* File descriptor of pty */
	int gre_fd = -1;		/* Network file descriptor */
	int sig_fd = sigpipe_fd();	/* Signal pipe descriptor	*/

	unsigned char packet[PPTP_MAX_CTRL_PCKT_SIZE];
	unsigned char rply_packet[PPTP_MAX_CTRL_PCKT_SIZE];

	for (;;) {

		FD_ZERO(&fds);
		FD_SET(sig_fd, &fds);
		FD_SET(clientSocket, &fds);
		if (pty_fd != -1)
			FD_SET(pty_fd, &fds);
		if (gre_fd != -1 && init)
			FD_SET(gre_fd, &fds);

		/* set timeout */
		if (encaps_gre(-1, NULL, 0) || decaps_hdlc(-1, NULL, 0)) {
			idleTime.tv_sec = 0;
			idleTime.tv_usec = 50000; /* don't ack immediately */
		} else {
			idleTime.tv_sec = IDLE_WAIT;
			idleTime.tv_usec = 0;
		}

		/* default: do nothing */
		send_packet = FALSE;

		switch (select(maxfd + 1, &fds, NULL, NULL, &idleTime)) {
		case -1:	/* Error with select() */
			if (errno != EINTR)
				syslog(LOG_ERR, "CTRL: Error with select(), quitting");
			goto leave_clear_call;

		case 0:
			if (decaps_hdlc(-1, NULL, 0)) {
				if(decaps_hdlc(-1, encaps_gre, gre_fd))
					syslog(LOG_ERR, "CTRL: GRE re-xmit failed");
			} else if (encaps_gre(-1, NULL, 0))
				/* Pending ack and nothing else to do */
				encaps_gre(gre_fd, NULL, 0);	/* send ack with no payload */
			else if (echo_wait != TRUE) {
				/* Timeout. Start idle link detection. */
				echo_count++;
				if (pptpctrl_debug)
					syslog(LOG_DEBUG, "CTRL: Sending ECHO REQ id %d", echo_count);
				time(&echo_time);
				make_echo_req_packet(rply_packet, &rply_size, echo_count);
				echo_wait = TRUE;
				send_packet = TRUE;
			}
			break;

		default:
			break;
		}

		/* check for pending SIGTERM delivery */
		if (FD_ISSET(sig_fd, &fds)) {
			if (sigpipe_read() == SIGTERM)
				bail(SIGTERM);
		}

		/* detect startup of pppd */
#ifndef init
		if (!init && pty_fd != -1 && FD_ISSET(pty_fd, &fds))
			init = 1;
#endif

		/* handle actual packets */

		/* send from pty off via GRE */
		if (pty_fd != -1 && FD_ISSET(pty_fd, &fds) && decaps_hdlc(pty_fd, encaps_gre, gre_fd) < 0) {
			syslog(LOG_ERR, "CTRL: PTY read or GRE write failed (pty,gre)=(%d,%d)", pty_fd, gre_fd);
			break;
		}
		/* send from GRE off to pty */
		if (gre_fd != -1 && FD_ISSET(gre_fd, &fds) && decaps_gre(gre_fd, encaps_hdlc, pty_fd) < 0) {
			if (gre_fd == 6 && pty_fd == 5) {
				syslog(LOG_ERR, "CTRL: GRE-tunnel has collapsed (GRE read or PTY write failed (gre,pty)=(%d,%d))", gre_fd, pty_fd);
			} else {
				syslog(LOG_ERR, "CTRL: GRE read or PTY write failed (gre,pty)=(%d,%d)", gre_fd, pty_fd);
			}
			break;
		}
		/* handle control messages */

		if (FD_ISSET(clientSocket, &fds)) {
			send_packet = TRUE;
			switch (read_pptp_packet(clientSocket, packet, rply_packet, &rply_size)) {
			case 0:
				syslog(LOG_ERR, "CTRL: CTRL read failed");
				goto leave_drop_call;

			case -1:
				send_packet = FALSE;
				break;

			case STOP_CTRL_CONN_RQST:
				if (pptpctrl_debug)
					syslog(LOG_DEBUG, "CTRL: Received STOP CTRL CONN request (disconnecting)");
				if (gre_fd != -1 || pty_fd != -1)
					syslog(LOG_WARNING, "CTRL: Request to close control connection when call is open, closing");
				send_pptp_packet(clientSocket, rply_packet, rply_size);
				goto leave_drop_call;

			case CALL_CLR_RQST:
				if(pptpctrl_debug)
					syslog(LOG_DEBUG, "CTRL: Received CALL CLR request (closing call)");
				if (gre_fd == -1 || pty_fd == -1)
					syslog(LOG_WARNING, "CTRL: Request to close call but call not open");
				if (gre_fd != -1) {
					FD_CLR(gre_fd, &fds);
					close(gre_fd);
					gre_fd = -1;
				}
				if (pty_fd != -1) {
					FD_CLR(pty_fd, &fds);
					close(pty_fd);
					pty_fd = -1;
				}
				/* violating RFC */
                                goto leave_drop_call;

			case OUT_CALL_RQST:
				/* for killing off the link later (ugly) */
				NOTE_VALUE(PAC, call_id_pair, ((struct pptp_out_call_rply *) (rply_packet))->call_id);
				NOTE_VALUE(PNS, call_id_pair, ((struct pptp_out_call_rply *) (rply_packet))->call_id_peer);
				if (gre_fd != -1 || pty_fd != -1) {
					syslog(LOG_WARNING, "CTRL: Request to open call when call is already open, closing");
					if (gre_fd != -1) {
						FD_CLR(gre_fd, &fds);
						close(gre_fd);
						gre_fd = -1;
					}
					if (pty_fd != -1) {
						FD_CLR(pty_fd, &fds);
						close(pty_fd);
						pty_fd = -1;
					}
				}
                                /* change process title for accounting and status scripts */
                                my_setproctitle(gargc, gargv,
                                      "pptpd [%s:%04X - %04X]",
                                      inet_ntoa(inetaddrs[1]),
                                      ntohs(((struct pptp_out_call_rply *) (rply_packet))->call_id_peer),
                                      ntohs(((struct pptp_out_call_rply *) (rply_packet))->call_id));
				/* start the call, by launching pppd */
				syslog(LOG_INFO, "CTRL: Starting call (launching pppd, opening GRE)");
				pty_fd = startCall(pppaddrs, inetaddrs);
				if (pty_fd > maxfd) maxfd = pty_fd;
				if ((gre_fd = pptp_gre_init(call_id_pair, pty_fd, inetaddrs)) > maxfd)
					maxfd = gre_fd;
				break;

			case ECHO_RPLY:
				if (echo_wait == TRUE && ((struct pptp_echo_rply *) (packet))->identifier == echo_count)
					echo_wait = FALSE;
				else
					syslog(LOG_WARNING, "CTRL: Unexpected ECHO REPLY packet");
				/* FALLTHRU */
			case SET_LINK_INFO:
				send_packet = FALSE;
				break;

#ifdef PNS_MODE
			case IN_CALL_RQST:
			case IN_CALL_RPLY:
			case IN_CALL_CONN:
#endif

			case CALL_DISCONN_NTFY:
			case STOP_CTRL_CONN_RPLY:
				/* These don't generate replies.  Also they come from things we don't send in this section. */
				syslog(LOG_WARNING, "CTRL: Got a reply to a packet we didn't send");
				send_packet = FALSE;
				break;

			/* Otherwise, the already-formed reply will do fine, so send it */
			}
		}

		/* send reply packet - this may block, but it should be very rare */
		if (send_packet == TRUE && send_pptp_packet(clientSocket, rply_packet, rply_size) < 0) {
			syslog(LOG_ERR, "CTRL: Error sending GRE, aborting call");
			goto leave_clear_call;
		}

		/* waiting for echo reply and curtime - echo_time > max wait */
		if (echo_wait == TRUE && (time(NULL) - echo_time) > MAX_ECHO_WAIT) {
			syslog(LOG_INFO, "CTRL: Session timed out, ending call");
			goto leave_clear_call;
		}
	}
	/* Finished! :-) */
leave_drop_call:
	NOTE_VALUE(PAC, call_id_pair, htons(-1));
	NOTE_VALUE(PNS, call_id_pair, htons(-1));
	close(clientSocket);
leave_clear_call:
	/* leave clientSocket and call_id_pair alone for bail() */
	if (gre_fd != -1)
		close(gre_fd);
	gre_fd = -1;
	if (pty_fd != -1)
		close(pty_fd);
	pty_fd = -1;
	return;
#ifdef init
#undef init
#endif
}