Exemple #1
0
/* push a bytes into the state tracker */
void telnet_recv(telnet_t *telnet, const char *buffer,
		size_t size) {
#if defined(HAVE_ZLIB)
	/* if we have an inflate (decompression) zlib stream, use it */
	if (telnet->z != 0 && !(telnet->flags & TELNET_PFLAG_DEFLATE)) {
		char inflate_buffer[1024];
		int rs;

		/* initialize zlib state */
		telnet->z->next_in = (unsigned char*)buffer;
		telnet->z->avail_in = (unsigned int)size;
		telnet->z->next_out = (unsigned char *)inflate_buffer;
		telnet->z->avail_out = sizeof(inflate_buffer);

		/* inflate until buffer exhausted and all output is produced */
		while (telnet->z->avail_in > 0 || telnet->z->avail_out == 0) {
			/* reset output buffer */

			/* decompress */
			rs = inflate(telnet->z, Z_SYNC_FLUSH);

			/* process the decompressed bytes on success */
			if (rs == Z_OK || rs == Z_STREAM_END)
				_process(telnet, inflate_buffer, sizeof(inflate_buffer) -
						telnet->z->avail_out);
			else
				_error(telnet, __LINE__, __func__, TELNET_ECOMPRESS, 1,
						"inflate() failed: %s", zError(rs));

			/* prepare output buffer for next run */
			telnet->z->next_out = (unsigned char *)inflate_buffer;
			telnet->z->avail_out = sizeof(inflate_buffer);

			/* on error (or on end of stream) disable further inflation */
			if (rs != Z_OK) {
				telnet_event_t ev;

				/* disable compression */
				inflateEnd(telnet->z);
				free(telnet->z);
				telnet->z = 0;

				/* send event */
				ev.type = TELNET_EV_COMPRESS;
				ev.compress.state = 0;
				telnet->eh(telnet, &ev, telnet->ud);

				break;
			}
		}

	/* COMPRESS2 is not negotiated, just process */
	} else
#endif /* defined(HAVE_ZLIB) */
		_process(telnet, buffer, size);
}
Exemple #2
0
process_t Process( const char * path,... )
{
	char * entry ;
	char ** args  ;
	char ** e ;
	size_t size = sizeof( char * ) ;
	int index = 1 ;
	va_list list ;
	process_t p ;

	if( path == NULL ){
		return _process( NULL ) ;
	}

	p = _process( path ) ;

	if( p == ProcessVoid ){
		return ProcessVoid ;
	}

	args = p->args ;

	va_start( list,path ) ;

	while( 1 ){

		entry = va_arg( list,char * ) ;
		e = realloc( args,( 1 + index ) * size ) ;

		if( e == NULL ){
			ProcessCleanUp( &p ) ;
			free( args ) ;
			va_end( list ) ;
			_ProcessError() ;
			return ProcessVoid ;
		}else{
			args = e ;
		}

		if( entry == NULL ){
			*( args + index ) = NULL ;
			break ;
		}else{
			*( args + index ) = entry ;
			index++ ;
		}
	}

	va_end( list ) ;

	p->args      = args ;
	p->args[ 0 ] = p->exe ;
	p->str.args  = args ;

	return p ;
}
void CSODistance::handleNotification(Field* field)
{
  ML_TRACE_IN("void CSODistance::handleNotification(Field* field)");

  if (field == _input0CSOFld){

    if (!_isInNotificationCB && _csoList0 ) { _csoList0->removeNotificationObserver(_csoListNotificationCB, this);}

    if (BASE_IS_A((static_cast<Base*>(_input0CSOFld->getBaseValue())), CSOList)){

      _csoList0 = static_cast<CSOList*>(_input0CSOFld->getBaseValue());

      if (_csoList0 != NULL){

        if (!_isInNotificationCB) { _csoList0->addNotificationObserver(_csoListNotificationCB, this); }
      }
    } else {

      _csoList0 = NULL;
    }

    if (_autoApplyFld->getBoolValue()) { _process(); }
  } else
  if (field == _input1CSOFld){

    if (!_isInNotificationCB && _csoList1 ) { _csoList1->removeNotificationObserver(_csoListNotificationCB, this);}

    if (BASE_IS_A((static_cast<Base*>(_input1CSOFld->getBaseValue())), CSOList)){

      _csoList1 = static_cast<CSOList*>(_input1CSOFld->getBaseValue());

      if (_csoList1 != NULL){

        if (!_isInNotificationCB) { _csoList1->addNotificationObserver(_csoListNotificationCB, this); }
      }
    } else {

      _csoList1 = NULL;
    }

    if (_autoApplyFld->getBoolValue()) { _process(); }
  } else
  if ( field == _applyFld || ( _autoApplyFld->getBoolValue() && 
                             ( field == _tolleranceFld || field == _curveStatistic )) ){
    _process();
  }


  BaseOp::handleNotification(field);
}
Exemple #4
0
static int _poll(kevent_loop_t *el)
{
	int nev, i;
	nev = epoll_wait(el->epd, el->events, el->event_size,
						KEVENT_POLL_TIMEOUT);
	if (nev == KEVENT_ERR) {
		el->error_handler(el, errno);
		return KEVENT_ERR;
	}

	for (i = 0; i < nev; i++) {
		kevent_t *ev;
		eventtype_t et = KEVENT_FREE;
		ev = &el->kevents[el->events[i].data.fd];

		if (el->events[i].events & EPOLLERR
				|| el->events[i].events & EPOLLHUP)
			et |= KEVENT_FAULTY;
		if (el->events[i].events & EPOLLIN)
			et |= KEVENT_READABLE;
		if (el->events[i].events & EPOLLOUT)
			et |= KEVENT_WRITABLE;

		ev->eventtype = et;
		_process(el, ev);
	}
	return nev;
}
void MeshLodGenerator::generateLodLevels(LodConfig& lodConfig,
                                         LodCollapseCostPtr cost,
                                         LodDataPtr data,
                                         LodInputProviderPtr input,
                                         LodOutputProviderPtr output,
                                         LodCollapserPtr collapser)
{
    // If we don't have generated Lod levels, we can use _generateManualLodLevels.
    bool hasGeneratedLevels = false;
    for(size_t i = 0; i < lodConfig.levels.size(); i++) {
        if(lodConfig.levels[i].manualMeshName.empty()) {
            hasGeneratedLevels = true;
            break;
        }
    }
    if(hasGeneratedLevels || (LodWorkQueueInjector::getSingletonPtr() && LodWorkQueueInjector::getSingletonPtr()->getInjectorListener())) {
        _resolveComponents(lodConfig, cost, data, input, output, collapser);
        if(lodConfig.advanced.useBackgroundQueue) {
            _initWorkQueue();
            LodWorkQueueWorker::getSingleton().addRequestToQueue(lodConfig, cost, data, input, output, collapser);
        } else {
            _process(lodConfig, cost.get(), data.get(), input.get(), output.get(), collapser.get());
        }
    } else {
        _generateManualLodLevels(lodConfig);
    }
}
Exemple #6
0
bool signerSignMsg(MyMessage &msg)
{
	bool ret;
#if defined(MY_SIGNING_FEATURE)
	// If destination is known to require signed messages and we are the sender,
	// sign this message unless it is identified as an exception
	if (DO_SIGN(msg.destination) && msg.sender == getNodeId()) {
		if (skipSign(msg)) {
			ret = true;
		} else {
			// Send nonce-request
			_signingNonceStatus=SIGN_WAITING_FOR_NONCE;
			if (!_sendRoute(build(_msgSign, msg.destination, msg.sensor, C_INTERNAL,
			                      I_NONCE_REQUEST).set(""))) {
				SIGN_DEBUG(PSTR("Failed to transmit nonce request!\n"));
				ret = false;
			} else {
				SIGN_DEBUG(PSTR("Nonce requested from %d. Waiting...\n"), msg.destination);
				// We have to wait for the nonce to arrive before we can sign our original message
				// Other messages could come in-between. We trust _process() takes care of them
				unsigned long enter = hwMillis();
				_msgSign = msg; // Copy the message to sign since message buffer might be touched in _process()
				while (hwMillis() - enter < MY_VERIFICATION_TIMEOUT_MS &&
				        _signingNonceStatus==SIGN_WAITING_FOR_NONCE) {
					_process();
				}
				if (hwMillis() - enter > MY_VERIFICATION_TIMEOUT_MS) {
					SIGN_DEBUG(PSTR("Timeout waiting for nonce!\n"));
					ret = false;
				} else {
					if (_signingNonceStatus == SIGN_OK) {
						// process() received a nonce and signerProcessInternal successfully signed the message
						msg = _msgSign; // Write the signed message back
						SIGN_DEBUG(PSTR("Message to send has been signed\n"));
						ret = true;
						// After this point, only the 'last' member of the message structure is allowed to be altered if the
						// message has been signed, or signature will become invalid and the message rejected by the receiver
					} else {
						SIGN_DEBUG(PSTR("Message to send could not be signed!\n"));
						ret = false;
					}
				}
			}
		}
	} else if (getNodeId() == msg.sender) {
		mSetSigned(msg, 0); // Message is not supposed to be signed, make sure it is marked unsigned
		SIGN_DEBUG(PSTR("Will not sign message for destination %d as it does not require it\n"),
		           msg.destination);
		ret = true;
	} else {
		SIGN_DEBUG(PSTR("Will not sign message since it was from %d and we are %d\n"), msg.sender,
		           getNodeId());
		ret = true;
	}
#else
	(void)msg;
	ret = true;
#endif // MY_SIGNING_FEATURE
	return ret;
}
void systemProcessTest::testArg() {
  y::sys::process _process("ls");
  _process.arg("-al");
  _process.run(y::sys::stdOut);
  if (!_process.success()) {
    CPPUNIT_ASSERT(false);
  }
}
Exemple #8
0
void * iothread_main( void * arg )
{
    uint32_t maxtasks = 0;

    struct iothread * thread = (struct iothread *)arg;
    struct iothreads * parent = (struct iothreads *)(thread->parent);

    sigset_t mask;
    sigfillset(&mask);
    pthread_sigmask(SIG_SETMASK, &mask, NULL);

    // 初始化队列
    struct taskqueue doqueue;
    QUEUE_INIT(taskqueue)( &doqueue, MSGQUEUE_DEFAULT_SIZE );

    for ( ; parent->runflags; )
    {
        uint32_t nprocess = 0;

        // 轮询网络事件
        evsets_dispatch( thread->sets );

        // 处理事件
        nprocess = _process( parent, thread, &doqueue );

        // 最大任务数
        maxtasks = MAX( maxtasks, nprocess );
    }

    // 清理队列中剩余数据
    _process( parent, thread, &doqueue );
    // 清空队列
    QUEUE_CLEAR(taskqueue)( &doqueue );

    // 日志
    syslog( LOG_INFO, "%s(INDEX=%d) : the Maximum Number of Requests is %d in EachFrame .",
            __FUNCTION__, thread->index, maxtasks );

    // 向主线程发送终止信号
    pthread_mutex_lock( &parent->lock );
    --parent->nrunthreads;
    pthread_cond_signal( &parent->cond );
    pthread_mutex_unlock( &parent->lock );

    return NULL;
}
Exemple #9
0
int ProcessExecute( const char * exe,... )
{
	char * entry ;
	char ** args  ;
	char ** e ;
	size_t size = sizeof( char * ) ;
	int index = 1 ;
	va_list list ;
	process_t p ;

	if( exe == NULL ){
		return -1 ;
	}

	p = _process( exe ) ;

	if( p == ProcessVoid ){
		return -1 ;
	}

	args = p->args ;

	va_start( list,exe ) ;

	while( 1 ){

		entry = va_arg( list,char * ) ;
		e = realloc( args,( 1 + index ) * size ) ;

		if( e == NULL ){
			ProcessCleanUp( &p ) ;
			free( args ) ;
			va_end( list ) ;
			_ProcessError() ;
			return -1 ;
		}else{
			args = e ;
		}

		if( entry == NULL ){
			*( args + index ) = NULL ;
			break ;
		}else{
			*( args + index ) = entry ;
			index++ ;
		}
	}

	va_end( list ) ;

	p->args      = args ;
	p->args[ 0 ] = p->exe ;
	p->str.args  = args ;

	ProcessStart( p ) ;

	return ProcessWaitUntilFinished( &p ) ;
}
Exemple #10
0
        /*
         * GO: sets the tree cursors on each term in terms,  processes the terms by advancing
         * the terms cursors and storing the partial
         * results and lastly calculates the top results
         * @param results, the priority queue containing the top results
         * @param limit, number of results in the priority queue
         */
        void FTSSearch::go(Results* results, unsigned limit ) {
            vector< shared_ptr<BtreeCursor> > cursors;

            for ( unsigned i = 0; i < _query.getTerms().size(); i++ ) {
                const string& term = _query.getTerms()[i];
                BSONObj min = FTSIndexFormat::getIndexKey( MAX_WEIGHT, term, _indexPrefix );
                BSONObj max = FTSIndexFormat::getIndexKey( 0, term, _indexPrefix );
                shared_ptr<BtreeCursor> c( BtreeCursor::make( _ns, _id, min, max, true, -1 ) );
                cursors.push_back( c );
            }

            while ( !inShutdown() ) {
                bool gotAny = false;
                for ( unsigned i = 0; i < cursors.size(); i++ ) {
                    if ( cursors[i]->eof() )
                        continue;
                    gotAny = true;
                    _process( cursors[i].get() );
                    cursors[i]->advance();
                }

                if ( !gotAny )
                    break;

                RARELY killCurrentOp.checkForInterrupt();
            }


            // priority queue using a compare that grabs the lowest of two ScoredLocations by score.
            for ( Scores::iterator i = _scores.begin(); i != _scores.end(); ++i ) {

                if ( i->second < 0 )
                    continue;

                // priority queue
                if ( results->size() < limit ) { // case a: queue unfilled

                    if ( !_ok( i->first ) )
                        continue;

                    results->push( ScoredLocation( i->first, i->second ) );

                }
                else if ( i->second > results->top().score ) { // case b: queue filled

                    if ( !_ok( i->first ) )
                        continue;

                    results->pop();
                    results->push( ScoredLocation( i->first, i->second ) );
                }
                else {
                    // else do nothing (case c)
                }

            }

        }
Exemple #11
0
void wait(unsigned long ms) {
	unsigned long enter = hwMillis();
	while (hwMillis() - enter < ms) {
		_process();
		#if defined(MY_GATEWAY_ESP8266)
			yield();
		#endif
	}
}
Exemple #12
0
void wait(unsigned long ms, uint8_t cmd, uint8_t msgtype) {
	unsigned long enter = hwMillis();
	// invalidate msg type
	_msg.type = !msgtype;
	while ( (hwMillis() - enter < ms) && !(mGetCommand(_msg)==cmd && _msg.type==msgtype) ) {
		_process();
		#if defined(MY_GATEWAY_ESP8266)
			yield();
		#endif
	}
}
Exemple #13
0
void
assert_msg_matches_and_output_message_has_tag_with_timeout(const gchar *pattern, gint timeout, gint ndx, const gchar *tag, gboolean set)
{
  LogMessage *msg;

  msg = _construct_message("prog2", pattern);
  _process(msg);
  _advance_time(timeout);
  assert_output_message_has_tag(ndx, tag, set);
  log_msg_unref(msg);
}
Exemple #14
0
void
assert_msg_matches_and_no_such_output_message(const gchar *pattern, gint ndx)
{
  LogMessage *msg;

  msg = _construct_message("prog2", pattern);
  _process(msg);

  assert_no_such_output_message(ndx);
  log_msg_unref(msg);
}
Exemple #15
0
void
assert_msg_matches_and_output_message_nvpair_equals_with_timeout(const gchar *pattern, gint timeout, gint ndx, const gchar *name, const gchar *value)
{
  LogMessage *msg;

  msg = _construct_message("prog2", pattern);
  _process(msg);
  _advance_time(timeout);

  assert_output_message_nvpair_equals(ndx, name, value);
  log_msg_unref(msg);
}
//----------------------------------------------------------------------------------
//! Handle field changes of the field field.
//----------------------------------------------------------------------------------
void SegmentationEvaluationMetric::handleNotification (Field *field)
{
  ML_TRACE_IN("SegmentationEvaluationMetric::handleNotification ()");

  if (_isAutoApplyFld->isOn() || (field == _applyFld)) {
    if (getUpdatedInImg(0) && getUpdatedInImg(1) ) {
	    _process();
    } else {
      _reset();
    }
  }
}
Exemple #17
0
static void loop_wrapper() {
	static bool setup_done = false;
	preloop_update_frequency();
	if (!setup_done) {
		_begin();		// Startup MySensors library
		setup_done = true;
	}
	_process();			// Process incoming data
	loop();
	run_scheduled_functions();
	esp_schedule();
}
Exemple #18
0
static void
_feed_message_to_correllation_state(const gchar *program, const gchar *message, const gchar *name, const gchar *value)
{
  LogMessage *msg;
  gboolean result;

  msg = _construct_message_with_nvpair(program, message, name, value);
  result = _process(msg);
  log_msg_unref(msg);
  assert_true(result, "patterndb expected to match but it didn't");
  _dont_reset_patterndb_state_for_the_next_call();
}
Exemple #19
0
int main(int argc, char *argv[])
{
	int opt, log_opts, debug = 0, foreground = 1;

	/* register the signal handler */
	signal(SIGINT, handle_sigint);
	signal(SIGTERM, handle_sigint);

	while ((opt = getopt(argc, argv, "hdb")) != -1) {
		switch (opt) {
			case 'h':
				print_usage();
				exit(0);
			case 'd':
				debug = 1;
				break;
			case 'b':
				foreground = 0;
				break;
			default:
				print_usage();
				exit(0);
		}
	}

	log_opts = LOG_CONS;
	if (foreground && isatty(STDIN_FILENO)) {
		// Also print syslog to stderror
		log_opts |= LOG_PERROR;
	}
	if (!debug) {
		setlogmask(LOG_UPTO (LOG_INFO));
	}
	openlog(NULL, log_opts, LOG_USER);

	if (!foreground && !debug) {
		if (daemonize() != 0) {
			exit(EXIT_FAILURE);
		}
	}

	mys_log(LOG_INFO, "Starting gateway...\n");
	mys_log(LOG_INFO, "Protocol version - %s\n", MYSENSORS_LIBRARY_VERSION);

	_begin(); // Startup MySensors library

	for (;;) {
		_process();  // Process incoming data
		if (loop) loop(); // Call sketch loop
	}
	return 0;
}
Exemple #20
0
static void
assert_msg_with_program_matches_and_nvpair_equals(const gchar *program, const gchar *message,
                                                  const gchar *name, const gchar *expected_value)
{
  LogMessage *msg;
  gboolean result;

  msg = _construct_message(program, message);
  result = _process(msg);
  assert_true(result, "patterndb expected to match but it didn't");
  assert_log_message_value(msg, log_msg_get_value_handle(name), expected_value);
  log_msg_unref(msg);
}
Exemple #21
0
static void
assert_msg_doesnot_match(const gchar *message)
{
  LogMessage *msg;
  gboolean result;

  msg = _construct_message("prog1", message);
  result = _process(msg);
  assert_false(result, "patterndb expected to match but it didn't");
  assert_log_message_value(msg, log_msg_get_value_handle(".classifier.class"), "unknown");
  assert_log_message_has_tag(msg, ".classifier.unknown");
  log_msg_unref(msg);
}
Exemple #22
0
std::string LSystem::_process(const std::string &state, unsigned depth) {
   if (depth <= 0)
      return state;
   
   std::string next = "";
   
   for(unsigned i = 0; i < state.length(); ++i) {
      const char cur = state[i];
      
      if (m_rules.find(cur) != std::string::npos)
         next += _processRule(cur);
      else next += cur;
   }
   
   return _process(next, depth - 1);
}
Exemple #23
0
static void
assert_msg_matches_and_has_tag(const gchar *pattern, const gchar *tag, gboolean set)
{
  LogMessage *msg;
  gboolean result;

  msg = _construct_message("prog1", pattern);
  result = _process(msg);
  assert_true(result, "patterndb expected to match but it didn't");

  if (set)
    assert_log_message_has_tag(msg, tag);
  else
    assert_log_message_doesnt_have_tag(msg, tag);
  log_msg_unref(msg);
}
void EyesStatesDetectorApp::run(int argc, const char* argv[])
{
	for (int i = 1; i < argc; ++i)
	{
		if (_parseCmdArgs(i, argc, argv))
			continue;

		//        if (_parseHelpCmdArg(i, argc, argv))
		//            return;

		std::ostringstream msg;
		msg << "Unknown command line argument: " << argv[i];
		throw std::runtime_error(msg.str());
	}

	_process();
}
void NaughtyProcessMonitor::slotTimeout()
{
    uint cpu = cpuLoad();

    emit(load(cpu));

    if(cpu > d->triggerLevel_ * (d->interval_ / 1000))
    {
        uint load;
        QValueList< ulong > l(pidList());

        for(QValueList< ulong >::ConstIterator it(l.begin()); it != l.end(); ++it)
            if(getLoad(*it, load))
                _process(*it, load);
    }

    d->timer_->start(d->interval_, true);
}
Exemple #26
0
int main(void)
{
	init();
#if defined(USBCON)
	USBDevice.attach();
#endif
	_begin(); // Startup MySensors library
	for(;;) {
		_process();  // Process incoming data
		if (loop) {
			loop(); // Call sketch loop
		}
		if (serialEventRun) {
			serialEventRun();
		}
	}
	return 0;
}
Exemple #27
0
Fichier : tw.c Projet : Andux/jack2
static void* jack_thread(void *arg)
{
	jack_client_t* client = (jack_client_t*) arg;

	while (1) {

		jack_nframes_t frames = jack_cycle_wait (client);
		int status = _process(frames);
		jack_cycle_signal (client, status);

        /*
            Possibly do something else after signaling next clients in the graph
        */

        /* End condition */
        if (status != 0)
            return 0;
	}

    /* not reached*/
	return 0;
}
Exemple #28
0
void
rq_add_line(request_t *h, const char *line)
{
	size_t len = strlen(line);
	int res;
	
	switch (h->state)
	{
		case ST_START:
			res = parse_request_line(h, line);
			if (res == 0)
			{
				h->error = 1;
				return;
			}
			h->state = ST_HEADER;
			h->line[0] = '\0';
			break;
		case ST_HEADER:
			if (len == 0)
			{
				h->done = 1;
			}
			if ( (len == 0) || ( (len > 0) && !isspace(line[0]) ) )
			{
				if (strlen(h->line) > 0)
				{
					/* We have a full line of header, now we can analyze it. */
					char *colon = strchr(h->line, ':');
					size_t keylen;
					char *key;
					char *value;
					if (colon == NULL)
					{
						/* We didn't find a colon. */
						h->error = 1;
						return;
					}
					keylen = colon - h->line;
					key = strndup(h->line, keylen);
					if (key == NULL)
					{
						/* Allocation error */
						h->error = 1;
						return;
					}
					value = strdup(colon + 1);
		
					/* Now we have key and value, process them */
					_process(h, key, value);
				}
			}
			if (len > 0)
			{
				if ( !isspace(line[0]) )
					h->line[0] = '\0';
				else
					line++; /* skip the starting space */
			}
			if (len > 0)
			{
				int plen = strlen(h->line);
				int left = LINE_BUFFER_SIZE - plen - 1;
				char *to = h->line + plen;
				strncpy(to, line, left);
			}
		default:
			break;
	}
}
Exemple #29
0
static void _process(telnet_t *telnet, const char *buffer, size_t size) {
	telnet_event_t ev;
	unsigned char byte;
	size_t i, start;
	for (i = start = 0; i != size; ++i) {
		byte = buffer[i];
		switch (telnet->state) {
		/* regular data */
		case TELNET_STATE_DATA:
			/* on an IAC byte, pass through all pending bytes and
			 * switch states */
			if (byte == TELNET_IAC) {
				if (i != start) {
					ev.type = TELNET_EV_DATA;
					ev.data.buffer = buffer + start;
					ev.data.size = i - start;
					telnet->eh(telnet, &ev, telnet->ud);
				}
				telnet->state = TELNET_STATE_IAC;
			}
			break;

		/* IAC command */
		case TELNET_STATE_IAC:
			switch (byte) {
			/* subnegotiation */
			case TELNET_SB:
				telnet->state = TELNET_STATE_SB;
				break;
			/* negotiation commands */
			case TELNET_WILL:
				telnet->state = TELNET_STATE_WILL;
				break;
			case TELNET_WONT:
				telnet->state = TELNET_STATE_WONT;
				break;
			case TELNET_DO:
				telnet->state = TELNET_STATE_DO;
				break;
			case TELNET_DONT:
				telnet->state = TELNET_STATE_DONT;
				break;
			/* IAC escaping */
			case TELNET_IAC:
				/* event */
				ev.type = TELNET_EV_DATA;
				ev.data.buffer = (char*)&byte;
				ev.data.size = 1;
				telnet->eh(telnet, &ev, telnet->ud);

				/* state update */
				start = i + 1;
				telnet->state = TELNET_STATE_DATA;
				break;
			/* some other command */
			default:
				/* event */
				ev.type = TELNET_EV_IAC;
				ev.iac.cmd = byte;
				telnet->eh(telnet, &ev, telnet->ud);

				/* state update */
				start = i + 1;
				telnet->state = TELNET_STATE_DATA;
			}
			break;

		/* negotiation commands */
		case TELNET_STATE_WILL:
		case TELNET_STATE_WONT:
		case TELNET_STATE_DO:
		case TELNET_STATE_DONT:
			_negotiate(telnet, byte);
			start = i + 1;
			telnet->state = TELNET_STATE_DATA;
			break;

		/* subnegotiation -- determine subnegotiation telopt */
		case TELNET_STATE_SB:
			telnet->sb_telopt = byte;
			telnet->buffer_pos = 0;
			telnet->state = TELNET_STATE_SB_DATA;
			break;

		/* subnegotiation -- buffer bytes until end request */
		case TELNET_STATE_SB_DATA:
			/* IAC command in subnegotiation -- either IAC SE or IAC IAC */
			if (byte == TELNET_IAC) {
				telnet->state = TELNET_STATE_SB_DATA_IAC;
			} else if (telnet->sb_telopt == TELNET_TELOPT_COMPRESS && byte == TELNET_WILL) {
				/* In 1998 MCCP used TELOPT 85 and the protocol defined an invalid
				 * subnegotiation sequence (IAC SB 85 WILL SE) to start compression.
				 * Subsequently MCCP version 2 was created in 2000 using TELOPT 86
				 * and a valid subnegotiation (IAC SB 86 IAC SE). libtelnet for now
				 * just captures and discards MCCPv1 sequences.
				 */
				start = i + 2;
				telnet->state = TELNET_STATE_DATA;
			/* buffer the byte, or bail if we can't */
			} else if (_buffer_byte(telnet, byte) != TELNET_EOK) {
				start = i + 1;
				telnet->state = TELNET_STATE_DATA;
			}
			break;

		/* IAC escaping inside a subnegotiation */
		case TELNET_STATE_SB_DATA_IAC:
			switch (byte) {
			/* end subnegotiation */
			case TELNET_SE:
				/* return to default state */
				start = i + 1;
				telnet->state = TELNET_STATE_DATA;

				/* process subnegotiation */
				if (_subnegotiate(telnet) != 0) {
					/* any remaining bytes in the buffer are compressed.
					 * we have to re-invoke telnet_recv to get those
					 * bytes inflated and abort trying to process the
					 * remaining compressed bytes in the current _process
					 * buffer argument
					 */
					telnet_recv(telnet, &buffer[start], size - start);
					return;
				}
				break;
			/* escaped IAC byte */
			case TELNET_IAC:
				/* push IAC into buffer */
				if (_buffer_byte(telnet, TELNET_IAC) !=
						TELNET_EOK) {
					start = i + 1;
					telnet->state = TELNET_STATE_DATA;
				} else {
					telnet->state = TELNET_STATE_SB_DATA;
				}
				break;
			/* something else -- protocol error.  attempt to process
			 * content in subnegotiation buffer, then evaluate the
			 * given command as an IAC code.
			 */
			default:
				_error(telnet, __LINE__, __func__, TELNET_EPROTOCOL, 0,
						"unexpected byte after IAC inside SB: %d",
						byte);

				/* enter IAC state */
				start = i + 1;
				telnet->state = TELNET_STATE_IAC;

				/* process subnegotiation; see comment in
				 * TELNET_STATE_SB_DATA_IAC about invoking telnet_recv()
				 */
				if (_subnegotiate(telnet) != 0) {
					telnet_recv(telnet, &buffer[start], size - start);
					return;
				} else {
					/* recursive call to get the current input byte processed
					 * as a regular IAC command.  we could use a goto, but
					 * that would be gross.
					 */
					_process(telnet, (char *)&byte, 1);
				}
				break;
			}
			break;
		}
	}

	/* pass through any remaining bytes */ 
	if (telnet->state == TELNET_STATE_DATA && i != start) {
		ev.type = TELNET_EV_DATA;
		ev.data.buffer = buffer + start;
		ev.data.size = i - start;
		telnet->eh(telnet, &ev, telnet->ud);
	}
}
Exemple #30
0
vector<unsigned char> DESCoder::decode(vector<unsigned char> data)
{
	return _process(data, false);
}