Example #1
0
static void
test_read_and_write_complex_types (void)
{
  int status;
  pid_t pid;
  ThriftSocket *tsocket = NULL;
  ThriftTransport *transport = NULL;
  ThriftCompactProtocol *tc = NULL;
  ThriftProtocol *protocol = NULL;
  int port = TEST_PORT;

  /* fork a server from the client */
  pid = fork ();
  assert (pid >= 0);

  if (pid == 0)
  {
    /* child listens */
    thrift_server_complex_types (port);
    exit (0);
  } else {
    /* parent.  wait a bit for the socket to be created. */
    sleep (1);

    /* create a ThriftSocket */
    tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost",
                            "port", port, NULL);
    transport = THRIFT_TRANSPORT (tsocket);
    thrift_transport_open (transport, NULL);
    assert (thrift_transport_is_open (transport));

    /* create a ThriftCompactTransport */
    tc = g_object_new (THRIFT_TYPE_COMPACT_PROTOCOL, "transport",
                       tsocket, NULL);
    protocol = THRIFT_PROTOCOL (tc);
    assert (protocol != NULL);

    /* test structures */
    assert (thrift_compact_protocol_write_struct_begin (protocol,
                                                       NULL, NULL) == 0);
    assert (thrift_compact_protocol_write_struct_end (protocol, NULL) == 0);

    /* test field state w.r.t. deltas */

    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE, 1, NULL) == 1);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       16, NULL) == 1);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       17, NULL) == 1);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       15, NULL) > 1);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       30, NULL) == 1);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       46, NULL) > 1);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       47, NULL) == 1);

    /* test fields */
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       1, NULL) > 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);

    /* test field state w.r.t. structs */

    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       1, NULL) > 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       16, NULL) == 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);

    assert (thrift_compact_protocol_write_struct_begin (protocol,
                                                       NULL, NULL) == 0);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       17, NULL) > 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);

    assert (thrift_compact_protocol_write_struct_begin (protocol,
                                                       NULL, NULL) == 0);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       18, NULL) > 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       19, NULL) == 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
    assert (thrift_compact_protocol_write_struct_end (protocol, NULL) == 0);

    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       18, NULL) == 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       25, NULL) == 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
    assert (thrift_compact_protocol_write_struct_end (protocol, NULL) == 0);

    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       17, NULL) == 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);

    /* test field state w.r.t. bools */

    /* deltas */
    /* non-bool field -> bool field -> non-bool field */
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       18, NULL) == 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_BOOL,
                                                       19, NULL) == 0);
    assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL,
                                                NULL) == 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       20, NULL) == 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
    /* bool -> bool field -> bool */
    assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_BOOL,
                                                       21, NULL) == 0);
    assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL,
                                                NULL) == 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
    assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0);

    /* no deltas */
    /* non-bool field -> bool field -> non-bool field */
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       1, NULL) > 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_BOOL,
                                                      1, NULL) == 0);
    assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       1, NULL) > 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
    /* bool -> bool field -> bool */
    assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0);
    assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_BOOL,
                                                      1, NULL) == 0);
    assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 1);
    assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
    assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0);

    /* test write error */
    transport_write_error = 1;
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       1, NULL) == -1);
    transport_write_error = 0;

    /* test 2nd write error */
    transport_write_count = 0;
    transport_write_error_at = 1;
    assert (thrift_compact_protocol_write_field_begin (protocol, "test",
                                                       T_DOUBLE,
                                                       1, NULL) == -1);
    transport_write_error_at = -1;

    /* test 2nd read failure on a field */
    thrift_compact_protocol_write_byte (protocol, T_DOUBLE, NULL);

    /* test write_field_stop */
    assert (thrift_compact_protocol_write_field_stop (protocol, NULL) > 0);

    /* write a map */
    assert (thrift_compact_protocol_write_map_begin (protocol, T_DOUBLE,
                                                     T_DOUBLE,
                                                     1, NULL) > 0);
    assert (thrift_compact_protocol_write_map_end (protocol, NULL) == 0);

    /* test 1st read failure on map---nothing to do on our side */

    /* test 2nd read failure on a map */
    thrift_compact_protocol_write_byte (protocol, T_DOUBLE, NULL);

    /* test 1st write failure on a map */
    transport_write_error = 1;
    assert (thrift_compact_protocol_write_map_begin (protocol, T_DOUBLE,
                                                     T_DOUBLE,
                                                     1, NULL) == -1);
    transport_write_error = 0;

    /* test 2nd write failure on a map */
    transport_write_count = 0;
    transport_write_error_at = 1;
    assert (thrift_compact_protocol_write_map_begin (protocol, T_DOUBLE,
                                                     T_DOUBLE,
                                                     1, NULL) == -1);
    transport_write_error_at = -1;

    /* test negative map size */
    thrift_compact_protocol_write_varint32 (tc, -10, NULL);
    thrift_compact_protocol_write_byte (protocol, T_DOUBLE, NULL);

    /* test list operations */
    assert (thrift_compact_protocol_write_list_begin (protocol, T_DOUBLE,
                                                     15, NULL) > 0);
    assert (thrift_compact_protocol_write_list_end (protocol, NULL) == 0);

    /* test 1st read failure on a small list---nothing to do on our end */

    /* test 1st read failure on a big list---nothing to do on our end */

    /* test 2nd read failure on a big list */
    thrift_compact_protocol_write_byte (protocol, (gint8) 0xf0, NULL);

    /* test negative list size */
    thrift_compact_protocol_write_byte (protocol, (gint8) 0xf0, NULL);
    thrift_compact_protocol_write_varint32 (tc, -10, NULL);

    /* test first write error on a small list */
    transport_write_error = 1;
    assert (thrift_compact_protocol_write_list_begin (protocol, T_DOUBLE,
                                                     14, NULL) == -1);
    transport_write_error = 0;

    /* test first write error on a big list */
    transport_write_error = 1;
    assert (thrift_compact_protocol_write_list_begin (protocol, T_DOUBLE,
                                                     15, NULL) == -1);
    transport_write_error = 0;

    /* test 2nd write error on a big list */
    transport_write_count = 0;
    transport_write_error_at = 1;
    assert (thrift_compact_protocol_write_list_begin (protocol, T_DOUBLE,
                                                     15, NULL) == -1);
    transport_write_error_at = -1;

    /* test set operation s*/
    assert (thrift_compact_protocol_write_set_begin (protocol, T_DOUBLE,
                                                    1, NULL) > 0);
    assert (thrift_compact_protocol_write_set_end (protocol, NULL) == 0);

    /* invalid protocol */
    assert (thrift_compact_protocol_write_byte (protocol, 0, NULL) > 0);

    /* invalid version */
    assert (thrift_compact_protocol_write_byte (protocol, (gint8) 0x82u,
                                                NULL) > 0);
    assert (thrift_compact_protocol_write_byte (protocol, 0, NULL) > 0);

    /* send a valid message */
    assert (thrift_compact_protocol_write_byte (protocol, (gint8) 0x82u,
                                                NULL) > 0);
    assert (thrift_compact_protocol_write_byte (protocol, 0x01u, NULL) > 0);
    thrift_compact_protocol_write_varint32 (tc, 1, NULL);
    thrift_compact_protocol_write_string (protocol, "test", NULL);

    /* broken 2nd read */
    thrift_compact_protocol_write_byte (protocol, (gint8) 0x82u, NULL);

    /* send a broken 3rd read */
    thrift_compact_protocol_write_byte (protocol, (gint8) 0x82u, NULL);
    thrift_compact_protocol_write_byte (protocol, 0x01u, NULL);

    /* send a broken 4th read */
    thrift_compact_protocol_write_byte (protocol, (gint8) 0x82u, NULL);
    thrift_compact_protocol_write_byte (protocol, 0x01u, NULL);
    thrift_compact_protocol_write_varint32 (tc, 1, NULL);

    /* send a valid message */
    assert (thrift_compact_protocol_write_message_begin (protocol, "test",
                                                        T_CALL, 1, NULL) > 0);

    assert (thrift_compact_protocol_write_message_end (protocol, NULL) == 0);

    /* send broken writes */
    transport_write_error = 1;
    assert (thrift_compact_protocol_write_message_begin (protocol, "test",
                                                        T_CALL, 1, NULL) == -1);
    transport_write_error = 0;

    transport_write_count = 0;
    transport_write_error_at = 1;
    assert (thrift_compact_protocol_write_message_begin (protocol, "test",
                                                        T_CALL, 1, NULL) == -1);
    transport_write_error_at = -1;

    transport_write_count = 0;
    transport_write_error_at = 2;
    assert (thrift_compact_protocol_write_message_begin (protocol, "test",
                                                        T_CALL, 1, NULL) == -1);
    transport_write_error_at = -1;

    transport_write_count = 0;
    transport_write_error_at = 3;
    assert (thrift_compact_protocol_write_message_begin (protocol, "test",
                                                        T_CALL, 1, NULL) == -1);
    transport_write_error_at = -1;

    /* clean up */
    thrift_transport_close (transport, NULL);
    g_object_unref (tsocket);
    g_object_unref (protocol);
    assert (wait (&status) == pid);
    assert (status == 0);
  }
}
Example #2
0
int main(int argc, char *argv[]) {
    int server_coid, self_coid, chid, rcvid;
    struct reg_msg msg;

    setvbuf (stdout, NULL, _IOLBF, 0);

    /* look for server */
    server_coid = name_open( RECV_NAME, 0 );
    while( server_coid == -1 )
    {
        sleep(1);
        server_coid = name_open( RECV_NAME, 0 );
    }

    chid = ChannelCreate(0);
    if( -1 == chid)
    {
        perror( PROGNAME "ChannelCreate");
        exit( EXIT_FAILURE );
    }
    self_coid = ConnectAttach( 0, 0, chid, _NTO_SIDE_CHANNEL, 0 );
    if( -1 == self_coid )
    {
        perror( PROGNAME "ConnectAttach");
        exit( EXIT_FAILURE );
    }

    msg.type = REG_MSG;

    /* class: Initialize the sigevent structure (msg.ev) in the message
     * to be sent to the server.
     */

    if (MsgSend( server_coid, &msg, sizeof( msg ), NULL, 0 ) == -1)
    {
        perror(PROGNAME "MsgSend");
        exit( EXIT_FAILURE );
    }

    while( 1 )
    {
        rcvid = MsgReceive( chid, &recv_buf, sizeof(recv_buf), NULL );
        if( -1 == rcvid )
        {
            perror(PROGNAME "MsgReceive");
            continue;
        }
        if ( 0 == rcvid )
        {
            if (MY_PULSE_CODE == recv_buf.pulse.code )
            {
                printf(PROGNAME "got my pulse\n");
            } else
            {
                printf(PROGNAME "got unexpected pulse with code %d\n",
                       recv_buf.pulse.code );
            }
            continue;
        }
        printf(PROGNAME "got unexpected message, type: %d\n", recv_buf.type );
        MsgError( rcvid, ENOSYS );
    }
}
Example #3
0
int main (int argc, char *argv[]){

///altre variabili
	int cont = 0;           ///contatore che tiene conto delle cpu, serve per fare cont di fork di processori


 ///variabili pthread_create
	int statusThread;
	int statusRam;

/// converto i dati in ingresso forniti dall'utente
	numCpu = atoi(argv[1]);
	ramDim = atoi(argv[2]);

///una stampa a video per avvertire che i dati immessi dall'utente sono stati acquisiti
	if(write(1,"Ho acquisito il numero di processori e la memoria della ram\n",61) == -1) {
		write(2,"Write fallita\n",15);
		exit(1);
    }


    ///variabili thread
    pthread_t threads[numCpu + 1];       /// per tenere traccia degli identificatori delle thread
	int *buffers = (int*) malloc((sizeof (int)) * 3);

    ///inizializzo i semafori
    if(pthread_mutex_init(&mutexRam, NULL) != 0){
        write(2,"Init fallita\n",14);
		exit(1);
    }
    if(pthread_mutex_init(&mutexProc, NULL) != 0){
        write(2,"Init fallita\n",14);
		exit(1);
    }
    if(pthread_mutex_init(&mutexAllProc, NULL) != 0){
        write(2,"Init fallita\n",14);
		exit(1);
    }

    if(pthread_mutex_lock(&mutexRam) != 0){
        write(2,"Lock fallita\n",14);
		exit(1);
    }
///valore per far terminare la ram, se 0 non eseguirà mai l'if, se 1 lo esegue ed esce
    killRam = 0;

///alloco mememoria e inizializzo le variabili della struct che passarò come argomento quando farò la pthread_create
	struttura *parametri = (struttura *)malloc(sizeof(struttura));
    parametri->ramDim = ramDim;
	parametri->buffer = buffers;


///Creo la thread della ram
    if((statusRam = pthread_create(&threads[0], NULL, ram, parametri)) != 0){
      write(2,"Non sono riuscito a creare la thread della Ram\n",48);
      exit(1);
    }

    sleep(1);   ///aspetto un secondo affinchè la ram posso inizializzare tutti i dati e fermarsi al semaforo in attesa di essere sbloccata
///Creo i numCpu thread
    while(cont < numCpu) {
		struttura *p = (struttura *)malloc(sizeof(struttura));
        p->nProc = cont;
		p->buffer = buffers;
        if((statusThread = pthread_create(&threads[cont + 1], NULL, processore2, p)) != 0) {
            write(2,"Non sono riuscito a creare la thread\n",38);
            exit(1);
        }
        cont++;
    }


///il processo padre aspetta che tutti le thread figlie terminino per poter terminare pure lui
	for(cont = 0; cont < numCpu; cont++)
		if(pthread_join(threads[cont + 1], NULL) != 0){
        write(2,"Join fallita\n",14);
        exit(1);
    }

    killRam = 1;
    if(pthread_mutex_unlock(&mutexRam) != 0){
        write(2,"Unlock fallita\n",16);
        exit(1);
    }
    if(pthread_join(threads[0], NULL) != 0){
        write(2,"Join fallita\n",14);
        exit(1);
    }

    int i;
    ///distruggo i semafori
    if((i = pthread_mutex_destroy(&mutexRam)) != 0){
        //write(2,"Destroy fallita\n",17);
		exit(1);
    }

    if((i = pthread_mutex_destroy(&mutexProc)) != 0){
        write(2,"Destroy fallita\n",17);
		exit(1);
    }

    if((i = pthread_mutex_destroy(&mutexAllProc)) != 0){
        write(2,"Destroy fallita\n",17);
		exit(1);
    }

    ///libero la memoria
    free(parametri);

	exit(1);
}
Example #4
0
void Socket::socketThread() {
    Json::Reader reader;
    
	bool running = true;
    int addrinfo_status, connect_status, socket_status = 0;
    
	while ( running ) {
        
		
        
		if ( !socketfd || socket_status ) {
			struct addrinfo host_info;
			struct addrinfo *host_info_list;
            
			// Close the existing socket, if it has been left open.
			if ( socketfd ) {
				close( socketfd );
				socketfd = NULL;
			}
            
			// Establish connection
			memset( &host_info, 0, sizeof host_info );
            
			host_info.ai_family = AF_UNSPEC;
			host_info.ai_socktype = SOCK_STREAM;
            
			addrinfo_status = getaddrinfo( hostname, port, &host_info, &host_info_list );
            
			if ( addrinfo_status ) {
				std::cout << "couldn't get address" << std::endl ;
				sleep(1);
				continue;
			}
            
			socketfd = socket( host_info_list->ai_family, host_info_list->ai_socktype, host_info_list->ai_protocol );
            
			if ( socketfd == -1 ) {
				socket_status = -1;
				std::cout << "socket error" << std::endl ;
				sleep(1);
				continue;
			}
            
			connect_status = connect( socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen );
            
			if ( connect_status ) {
				socket_status = -1;
				std::cout << "connect error" << std::endl ;
				sleep(1);
				continue;
			}
            
			socket_status = 0;
		}
        
		int max_message_size = 1000000;
        
		ssize_t bytes_recieved;
        
		struct hss_header header;
		string buffer;
        
		bytes_recieved = recv( socketfd, &header, sizeof header, 0 );
		
		//std::cout << "received " << bytes_recieved << std::endl;
        
		if ( bytes_recieved == sizeof header ) {
            
			// Parse the header ( what there is of it )
			header.string_bytes = ntohl( header.string_bytes );
            
			if ( header.string_bytes > max_message_size ) {
				// Bad header, fuck it.
				socket_status = -3;
				std::cout << "bad header, disconnecting";
				continue;
			}
            
			buffer.resize( header.string_bytes );
            
			size_t b = recv( socketfd, (void * ) buffer.c_str(), header.string_bytes, MSG_WAITALL );
            
			if ( b != header.string_bytes ) {
                
			}
            
            Json::Value msg;
            
			//std::cout << buffer << std::endl;
            reader.parse( buffer, msg );
            
            Json::Value set = msg["set"];
            if ( set.isObject() ) {
                
                Json::Value set = msg["set"];
                for ( Json::ValueIterator i = set.begin(); i != set.end(); i ++ ) {
                    string k = (string) i.memberName();
                    horten->set( set[k], k, flags );
                }
            }

		} else if (bytes_recieved == 0) {
			std::cout << "host shut down." << std::endl ;
			socket_status = -3;
			sleep(1);
		} else if (bytes_recieved == -1 ) {
			std::cout << "receive error! " << errno << std::endl ;
			socket_status = -4;
			sleep(1);
		}
	}
}
Example #5
0
shellcmd xsh_suspend( int nargs, char *args[] )
{
    tid_typ tid;	/* tid for thread to suspend */

    /* Output help, if '--help' argument was supplied */
    if( nargs == 2 && strncmp( args[1], "--help", 7 ) == 0)
    {
        printf("Usage: %s <TID>\n\n", args[0]);
        printf("Description:\n");
        printf("\tSuspends thread with the identifier TID.\n");
        printf("Options:\n");
        printf("\t<TID>\tID of thread to suspend.\n");
        printf("\t--help\tdisplay this help and exit\n");
        return 0;
    }

    /* Check for correct number of arguments */
    if( nargs < 2 )
    {
    	fprintf(stderr, "%s: missing operand\n", args[0]);
    	fprintf(stderr, "Try '%s --help' for more information.\n", args[0]);

    	return 1;
    }

    if( nargs > 2 )
    {
    	fprintf(stderr, "%s: too many arguments.\n", args[0]);
    	fprintf(stderr, "Try '%s --help' for more information.\n", args[0]);

    	return 1;
    }

    tid = atoi( args[1] );

    /* Don't try to suspend a null thread */
    if( tid == NULLTHREAD )
    {
    	fprintf( stderr, "%s: (%d) Operation not permitted.\n", args[0], tid);

    	return 1;
    }


   	 //If shell is being suspended, print notice to shell. 
   	 if( tid == gettid() )
   	 {
		fprintf( stderr, "%s: Shell suspended.\n", args[0] );
       		sleep(2000);
    	 }

   	 //Suspend thread, nothing is suspend failed. 
   	 if( suspend( tid ) == SYSERR )
    	{
    		fprintf( stderr, "%s : (%d) No such thread.\n", args[0], tid);
    		return -1;
    	}

    return 0;

}
//---------------------------------------------------
//    自动返回控制器器IP主函数
//---------------------------------------------------
//int main(int argc, char *argv[])
int configpalen_ipdetaup(void)
{
    int s_fd=0;
    int ret = 0;
    int i = 0;
    unsigned char sys_id[6];
    unsigned char buf[64];
    unsigned char request_buf[13];
    unsigned char h_ip[4];
    unsigned char s_ip[16];
    unsigned char s_gw[16];
    //unsigned char *ip="192.172.1.125";
    unsigned char setip[32] = "ifconfig eth0 ";
    int s_len = strlen(setip);

    unsigned char setgw[64] = "route add default gw ";
    int g_len = strlen(setgw);

    unsigned char k_ip[4];
    unsigned char smk[6];
    int sys_id_flag = 0;

    read_identifier(sys_id);//读取identifier.ini中保存的信息

    request_buf[0] = CAM_TYPE_TOP1;
    request_buf[1] = CAM_TYPE_TOP2;
    request_buf[2] = CAM_TYPE_REPLY;
    memcpy(request_buf+3, sys_id, 6);

    unsigned char versionbuf[2];

    //获取系统本身IP

    //ret = save_system_ip(ip, strlen(ip));

    ret = read_txt_ip(s_ip, h_ip);//读取systemip.ini中的信息
    if(ret < 0)
    {
        //获取文本的IP错误
        printf("read system ip file error!!!\n");
        GetIP_v4_and_v6_linux(AF_INET,s_ip,16);        //获取系统的IP
        ret = save_system_ip(s_ip, strlen(s_ip));
    }

    /*//printf("s_ip=%s\n",s_ip);
    memcpy(setip+s_len, s_ip, strlen(s_ip)+1);
    printf("set ip:%s\n",setip);

    system(setip);//还进行了设置。

    myread_txt_ip(s_gw, h_ip);
    memcpy(setgw+g_len, s_gw, strlen(s_gw)+1);
    printf("set gateway:%s\n",setgw);
    system(setgw);*/


    s_fd = make_send_multicast_init(s_ip);    //创建主播发送字符,只使用一个套接字也完全可以的。ghf

    socklen_t  len=sizeof(addr);
    extern int errno;

    static int val=0;



    cpufd = open("/dev/cpu_led",O_RDONLY);
    if (cpufd < 0)
    {
        system("insmod cpu_led.ko");
        sleep(2);
        cpufd = open("/dev/cpu_led",O_RDONLY);
        if (cpufd < 0){
            printf("error,open device cpu_led!!!\n");
        }
    }
    else{
        printf("open device cpu_led!!!\n");
    }

    //此接口走路由不行,但直连不同字段都可以
    struct sockaddr_in peeraddr;
    bzero(&peeraddr, sizeof(peeraddr));
    peeraddr.sin_family = AF_INET;
    peeraddr.sin_port = htons(MUTIL_PORT);
    peeraddr.sin_addr.s_addr = inet_addr(MUTIL_ADDR);


    while(1)
    {
        //防止arm端ip被改
        GetIP_v4_and_v6_linux(AF_INET,s_ip,16);
        save_system_ip(s_ip, strlen(s_ip));

        val++;

        ret = recvfrom(s_fd, buf, 64, 0, (struct sockaddr*)&addr, &len);//最后一个参数的定义跟sendto不一样,注意!

        //printf("recvret=%d,buf[2]=%d\n",ret,buf[2]);
        if(ret == -1){
            printf("in configpalen_ipdetaup recvfrom error\n");
            break;
        }
        else
        {
            buf[ret]='\0';
            if(buf[2] == CAM_TYPE_REQUEST) //得到请求IP命令,mt500将ip地址和网卡地址发上去显示,收到后会发一个
                                            //CAM_TYPE_REPLY下来
            {
                printf("------1\n");
                read_txt_ip(s_ip, h_ip);
                memcpy(request_buf+9, h_ip, 4);

                versionbuf[0]=0x01;
                versionbuf[1]=0x01; //当前版本号为1.01 累计到1.10后,进到2.00。依次类推
                                    //版本更新内容用txt文档记录,交由上层显示

                memcpy(request_buf+13, versionbuf, 2);

                //以下判断条件不加也可以,因为如果没有链接的话,while一开始的地方recvfrom会阻塞,不会进到下面来发送
                ret=0;
                if(s_fd>0)
                    ret=sendto(s_fd,request_buf,15,0,(struct sockaddr *)&addr,sizeof(addr));
                //if(sfd>0)
                //    ret=sendto(sfd,request_buf,15,0,(struct sockaddr *)&peeraddr,sizeof(peeraddr));

                if(ret<0){
                    printf("errno=%d,---sendret=%d,%s\n",errno,ret,strerror(errno));
                    system("ifconfig eth0 192.172.1.85");
                    system("route add default gw 192.172.1.1");
                    ioctl(cpufd,0,0);
                }
                else{
                    printf("sendret=%d, ipaddr to serverok\n",ret);
                    if(val%2==0)
                        ioctl(cpufd,1,0);
                    else
                        ioctl(cpufd,0,0);
                }
            }
            else if(buf[2] == CAM_TYPE_MODIFY)    //得到设置IP命令,上层可以直接设置ip才行!2015-9-16
            {
                memcpy(smk, buf+3, 6);
                for(i = 0; i < 6; i+=1)
                {
                    if(smk[i] != sys_id[i])
                    {
                        sys_id_flag = 1;
                        break;
                    }
                }

                if(sys_id_flag == 0)
                {
                    memcpy(k_ip, buf+9, 4);
                    //printf("%02x %02x %02x %02x\n",k_ip[0],k_ip[1],k_ip[2],k_ip[3]);
                    if(k_ip[0] != 0x0)
                    {
                        //continue;
                        writ_txt_ip(k_ip);
                        read_txt_ip(s_ip,h_ip);

                        printf("sip:%s\n",s_ip);
                        memcpy(setip+s_len, s_ip, strlen(s_ip)+1);
                        //printf("set ip:%s\n",setip);
                        close(s_fd);
                        system(setip);

                        myread_txt_ip(s_gw, h_ip);
                        memcpy(setgw+g_len, s_gw, strlen(s_gw)+1);
                        printf("***********************\n");
                        printf("set gateway:%s\n",setgw);
                        printf("***********************\n");
                        system(setgw);

                        s_fd = make_send_multicast_init(s_ip);
                    }
                    //printf("================================================\n");
                }
            }
            else if(buf[2] == CAM_TYPE_REBOOT)        //得到请求重启控制器命令
            {
                //printf("------3\n");
                memcpy(smk, buf+3, 6);
                for(i = 0; i < 6; i+=1)
                {
                    if(smk[i] != sys_id[i])
                    {
                        sys_id_flag = 1;
                        break;
                    }
                }

                if(sys_id_flag == 0){
                    printf("reboot!!!!!!!!!!!!!!!!!!!\n");
                    system("reboot");
                }
            }
        }
        usleep(100000);
    }

    close(s_fd);
    return 0;
}
Example #7
0
int
utmpx_mark_init(pid_t pid, char *prefix)
{
	struct utmpx ut, *oldu;
	int tmplen;
	int ret;

	while (st->st_initial && !utmpx_truncated)
		(void) usleep(200 * USEC_PER_MSEC);

	/*
	 * Clean out any preexisting records for this PID, as they must be
	 * inaccurate.
	 */
	utmpx_mark_dead(pid, 0, B_TRUE);

	/*
	 * Construct a new record with the appropriate prefix.
	 */
	(void) memset(&ut, 0, sizeof (ut));
	(void) strncpy(ut.ut_user, ".startd", sizeof (ut.ut_user));
	ut.ut_pid = pid;

	ut.ut_id[0] = ut.ut_id[1] = ut.ut_id[2] = ut.ut_id[3] = (char)SC_WILDC;

	for (ret = 0; ret < strlen(prefix); ret++)
		ut.ut_id[ret] = prefix[ret];

	ut.ut_type = INIT_PROCESS;
	(void) time(&ut.ut_tv.tv_sec);

	for (;;) {
		MUTEX_LOCK(&utmpx_lock);
		setutxent();

		if ((oldu = getutxid(&ut)) != NULL) {
			/*
			 * Copy in the old "line" and "host" fields.
			 */
			bcopy(oldu->ut_line, ut.ut_line, sizeof (ut.ut_line));
			bcopy(oldu->ut_host, ut.ut_host, sizeof (ut.ut_host));
			ut.ut_syslen = (tmplen = strlen(ut.ut_host)) ?
			    min(tmplen + 1, sizeof (ut.ut_host)) : 0;
		}

		if (makeutx(&ut) != NULL)
			break;

		if (errno != EROFS)
			log_framework(LOG_WARNING,
			    "makeutx failed, retrying: %s\n", strerror(errno));

		MUTEX_UNLOCK(&utmpx_lock);

		(void) sleep(1);
	}

	updwtmpx(WTMPX_FILE, &ut);

	endutxent();
	MUTEX_UNLOCK(&utmpx_lock);

	return (ret);
}
Example #8
0
int main( int ac, char	**av)
{
    ATP			atp;
    struct atp_block	atpb;
    int			c, err = 0, fd, cuts = 0;
    char		*obj = NULL, *type = "LaserWriter", *zone = "*";
    struct timeval	stv, tv;
    char		rbuf[ ATP_MAXDATA ];
    struct iovec	iov;
    unsigned short	waiting, result;
    int			connattempts = 10;
    int			waitforidle = 0;
    struct at_addr      addr;

    extern char		*optarg;
    extern int		optind;

    memset(&addr, 0, sizeof(addr));
    while (( c = getopt( ac, av, "dWwcep:s:EA:" )) != EOF ) {
	switch ( c ) {
#ifdef FUCKED
	case 'w' :
	    waitforprinter = 1;
	    break;

	case 'W' :
	    waitforidle = 1;
	    break;
#endif /* FUCKED */

	/* enable debugging */
	case 'd' :
	    debug++;
	    break;

	case 'c' :
	    cuts++;
	    break;

	case 'e' :	/* send stdout to stderr */
	    dup2( 2, 1 );
	    break;

	case 'p' :
	    printer = optarg;
	    break;

	case 's' :
	    status = optarg;
	    break;

	case 'E' :
	    noeof = 1;
	    break;
	   
	case 'A':
	    if (!atalk_aton(optarg, &addr)) {
	      fprintf(stderr, "Bad address.\n");
	      exit(1);
	    }
	    break;

	default :
	    err++;
	}
    }
    if ( err ) {
	usage( *av );
    }
    if ( printer == NULL && (( printer = paprc()) == NULL )) {
	fprintf( stderr, "No printer specified and ./.paprc not found.\n" );
	exit( 2 );
    }

    /*
     * Open connection.
     */
    if ( nbp_name( printer, &obj, &type, &zone ) < 0 ) {
	fprintf( stderr, "%s: Bad name\n", printer );
	exit( 2 );
    }
    if ( obj == NULL ) {
	fprintf( stderr, "%s: Bad name\n", printer );
	exit( 2 );
    }

    if ( nbp_lookup( obj, type, zone, &nn, 1, &addr ) <= 0 ) {
	if ( errno != 0 ) {
	    perror( "nbp_lookup" );
	    exit( 2 );
	}
	fprintf( stderr, "%s:%s@%s: NBP Lookup failed\n", obj, type, zone );
	exit( 1 );
    }

    if ( isatty( 1 )) {
	printf( "Trying %u.%d:%d ...\n", ntohs( nn.nn_sat.sat_addr.s_net ),
		nn.nn_sat.sat_addr.s_node, nn.nn_sat.sat_port );
    }

    if (( atp = atp_open( ATADDR_ANYPORT, &addr )) == NULL ) {
	perror( "atp_open" );
	exit( 2 );
    }
    if (( satp = atp_open( ATADDR_ANYPORT, &addr )) == NULL ) {
	perror( "atp_open" );
	exit( 2 );
    }

    while ( waitforidle ) {
	char	st_buf[ 1024 ];	/* XXX too big */

	cbuf[ 0 ] = 0;
	cbuf[ 1 ] = PAP_SENDSTATUS;
	cbuf[ 2 ] = cbuf[ 3 ] = 0;
	atpb.atp_saddr = &nn.nn_sat;
	atpb.atp_sreqdata = cbuf;
	atpb.atp_sreqdlen = 4;	/* bytes in SendStatus request */
	atpb.atp_sreqto = 2;		/* retry timer */
	atpb.atp_sreqtries = 5;		/* retry count */
	if ( atp_sreq( satp, &atpb, 1, 0 ) < 0 ) {
	    perror( "atp_sreq" );
	    exit( 1 );
	}

	if(debug){ printf( "SENDSTATUS >\n" ), fflush( stdout );}

	atpb.atp_saddr = &nn.nn_sat;
	rniov[ 0 ].iov_len = PAP_MAXDATA + 4;
	atpb.atp_rresiov = rniov;
	atpb.atp_rresiovcnt = 1;
	if ( atp_rresp( satp, &atpb ) < 0 ) {
	    perror( "atp_rresp" );
	    continue;
	}

#ifndef NONZEROSTATUS
	/*
	 * The stinking LaserWriter IINTX puts crap in this
	 * field.
	 */
	if ( ((char *)rniov[ 0 ].iov_base)[ 0 ] != 0 ) {
	    fprintf( stderr, "Bad status response!\n" );
	    exit( 1 );
	}
#endif /* NONZEROSTATUS */

	if ( ((char *)rniov[ 0 ].iov_base)[ 1 ] != PAP_STATUS ||
		atpb.atp_rresiovcnt != 1 ) {
	    fprintf( stderr, "Bad status response!\n" );
	    exit( 1 );
	}

	if(debug){ printf( "< STATUS\n" ), fflush( stdout );}

	memcpy( st_buf, (char *) rniov[ 0 ].iov_base + 9, 
		((char *)rniov[ 0 ].iov_base)[ 8 ] );
	st_buf[ (int) ((char *)rniov[ 0 ].iov_base)[ 8 ]] = '\0';
	if ( strstr( st_buf, "idle" ) != NULL ) {
	    waitforidle = 0;
	} else {
	    updatestatus( (char *) rniov[ 0 ].iov_base + 9,
		    ((char *)rniov[ 0 ].iov_base)[ 8 ] );
	    sleep( 5 );
	}
    }

    cbuf[ 0 ] = connid = getpid() & 0xff;
    cbuf[ 1 ] = PAP_OPEN;
    cbuf[ 2 ] = cbuf[ 3 ] = 0;
    cbuf[ 4 ] = atp_sockaddr( atp )->sat_port;
    cbuf[ 5 ] = oquantum;	/* flow quantum */
    if ( gettimeofday( &stv, NULL ) < 0 ) {
	perror( "gettimeofday" );
	exit( 2 );
    }
    for (;;) {
	if ( cuts ) {
	    waiting = 0xffff;
	} else {
	    if ( gettimeofday( &tv, NULL ) < 0 ) {
		perror( "gettimeofday" );
		exit( 2 );
	    }
	    waiting = htons( tv.tv_sec - stv.tv_sec );
	}
	memcpy(cbuf +  6, &waiting, sizeof( waiting ));

	atpb.atp_saddr = &nn.nn_sat;
	atpb.atp_sreqdata = cbuf;
	atpb.atp_sreqdlen = 8;		/* bytes in OpenConn request */
	atpb.atp_sreqto = 2;		/* retry timer */
	atpb.atp_sreqtries = 5;		/* retry count */
	if ( atp_sreq( atp, &atpb, 1, ATP_XO ) < 0 ) {
	    perror( "atp_sreq" );
	    exit( 1 );
	}

	if(debug){ printf( "OPEN >\n" ), fflush( stdout );}

	iov.iov_base = rbuf;
	iov.iov_len = sizeof( rbuf );
	atpb.atp_rresiov = &iov;
	atpb.atp_rresiovcnt = 1;
	if ( atp_rresp( atp, &atpb ) < 0 ) {
	    perror( "atp_rresp" );
	    if ( connattempts-- <= 0 ) {
		fprintf( stderr, "Can't connect!\n" );
		exit( 1 );
	    }
	    continue;
	}

	/* sanity */
	if ( iov.iov_len < 8 || (unsigned char)rbuf[ 0 ] != connid ||
		rbuf[ 1 ] != PAP_OPENREPLY ) {
	    fprintf( stderr, "Bad response!\n" );
	    continue;	/* This is weird, since TIDs must match... */
	}

	if(debug){ printf( "< OPENREPLY\n" ), fflush( stdout );}

	if ( isatty( 1 )) {
	    printf( "%.*s\n", (int)iov.iov_len - 9, (char *) iov.iov_base + 9 );
	}
	updatestatus( (char *) iov.iov_base + 9, iov.iov_len - 9 );

	memcpy( &result, rbuf +  6,  sizeof( result ));
	if ( result != 0 ) {
	    sleep( 2 );
	} else {
	    memcpy( &sat, &nn.nn_sat, sizeof( struct sockaddr_at ));
	    sat.sat_port = rbuf[ 4 ];
	    quantum = rbuf[ 5 ];
	    break;
	}
    }

    if ( isatty( 1 )) {
	printf( "Connected to %.*s:%.*s@%.*s.\n",
		nn.nn_objlen, nn.nn_obj,
		nn.nn_typelen, nn.nn_type,
		nn.nn_zonelen, nn.nn_zone );
    }

    if ( optind == ac ) {
	send_file( 0, atp, 1 );
    } else {
	for (; optind < ac; optind++ ) {
	    if ( strcmp( av[ optind ], "-" ) == 0 ) {
		fd = 0;
	    } else if (( fd = open( av[ optind ], O_RDONLY )) < 0 ) {
		perror( av[ optind ] );
		continue;
	    }
	    send_file( fd, atp, ( optind == ac - 1 ) ? 1 : 0 );
	    if ( fd != 0 ) {
		close( fd );
	    }
	}
    }

    /*
     * Close connection.
     */
    cbuf[ 0 ] = connid;
    cbuf[ 1 ] = PAP_CLOSE;
    cbuf[ 2 ] = cbuf[ 3 ] = 0;

    atpb.atp_saddr = &sat;
    atpb.atp_sreqdata = cbuf;
    atpb.atp_sreqdlen = 4;		/* bytes in CloseConn request */
    atpb.atp_sreqto = 2;		/* retry timer */
    atpb.atp_sreqtries = 5;		/* retry count */
    if ( atp_sreq( atp, &atpb, 1, ATP_XO ) < 0 ) {
	perror( "atp_sreq" );
	exit( 1 );
    }

	if(debug){ printf( "CLOSE >\n" ), fflush( stdout );}

    iov.iov_base = rbuf;
    iov.iov_len = sizeof( rbuf );
    atpb.atp_rresiov = &iov;
    atpb.atp_rresiovcnt = 1;
    if ( atp_rresp( atp, &atpb ) < 0 ) {
	perror( "atp_rresp" );
	exit( 1 );
    }

    /* sanity */
    if ( iov.iov_len != 4 || rbuf[ 1 ] != PAP_CLOSEREPLY ) {
	fprintf( stderr, "Bad response!\n" );
	exit( 1 );
    }

#ifndef ZEROCONNID
    /*
     * The AGFA Viper Rip doesn't have the connection id in the close request.
     */
    if ((unsigned char)rbuf[ 0 ] != connid ) {
	fprintf( stderr, "Bad connid in close!\n" );
	exit( 1 );
    }
#endif /* ZEROCONNID */

	if(debug){ printf( "< CLOSEREPLY\n" ), fflush( stdout );}

    if ( isatty( 1 )) {
	printf( "Connection closed.\n" );
    }
    exit( 0 );
}
Example #9
0
main(int argc, char *argv[])
{
    int i, j, l;
    int ch;
    extern char *optarg;
    int edge;
    int size;
    int lu_arg[MAX_THREADS][3];
    
    /* ARMCI */
    void **ptr;
    double **ptr_loc;

    THREAD_LOCK_INIT(mutex);
    
    armci_msg_init(&argc,&argv);
    nproc = armci_msg_nproc();
    me = armci_msg_me();
    
    while ((ch = getopt(argc, argv, "n:b:p:t:d:h")) != -1) {
        switch(ch) {
            case 'n': n = atoi(optarg); break;
            case 'b': block_size = atoi(optarg); break;
            case 'p': nproc = atoi(optarg); break;
            case 't': th_per_p = atoi(optarg); break;
            case 'd': d = atoi(optarg); break;
            case 'h': {
                printf("Usage: LU, or \n");
        printf("       LU -nMATRIXSIZE -bBLOCKSIZE -pNPROC -tTH_PER_P\n");
                armci_msg_barrier();
                armci_msg_finalize();
                exit(0);
            } 
        }
    }

    if(th_per_p>MAX_THREADS) {
        th_per_p=MAX_THREADS;
        if(me==0)printf("Warning: cannot run more than %d threads, adjust MAX_THREADS",MAX_THREADS);
    }

    if (d) {
        fprintf(stderr, "%d: %d\n", me, getpid());
        sleep(d);
    }

    nthreads = th_per_p * nproc;
    if(me == 0) {
        printf("\n Blocked Dense LU Factorization\n");
        printf("     %d by %d Matrix\n", n, n);
        printf("     %d Processors\n", nproc);
        printf("     %d thread(s) per processor, %d threads total\n", th_per_p, nthreads);
        printf("     %d by %d Element Blocks\n", block_size, block_size);
        printf("\n");
    }
    
    num_rows = (int) sqrt((double) nthreads);
    for (;;) {
        num_cols = nthreads/num_rows;
        if (num_rows*num_cols == nthreads)
            break;
        num_rows--;
    }
    
    nblocks = n/block_size;
    if (block_size * nblocks != n) {
        nblocks++;
    }
    
    num = (nblocks * nblocks)/nthreads;
    if((num * nthreads) != (nblocks * nblocks))
        num++;

    edge = n%block_size;
    if (edge == 0) {
        edge = block_size;
    }
#ifdef DEBUG
    if(me == 0)
        for (i=0;i<nblocks;i++) {
            for (j=0;j<nblocks;j++) 
                printf("%d ", block_owner(i, j));
            printf("\n");
        }
    armci_msg_barrier();
/*    armci_msg_finalize(); */
/*    exit(0); */
#endif
    
    for (l = 0; l < th_per_p; l++) {
        me_th[l] = me * th_per_p + l;
        for (i=0;i<nblocks;i++) {
            for (j=0;j<nblocks;j++) {
                if(block_owner(i,j) == me_th[l]) {
                    if ((i == nblocks-1) && (j == nblocks-1)) {
                        size = edge*edge;
                    }
                    else if ((i == nblocks-1) || (j == nblocks-1)) {
                        size = edge*block_size;
                    }
                    else {
                        size = block_size*block_size;
                    }
                    thread_doubles[l] += size;
                }
            }
        }
        proc_bytes += thread_doubles[l] * sizeof(double);
    }

    /* initialize ARMCI */
    ARMCI_Init();
    ptr = (void **)malloc(nproc * sizeof(void *));
    ARMCI_Malloc(ptr, proc_bytes);

    a = (double **)malloc(nblocks*nblocks*sizeof(double *));
    if (a == NULL) {
        fprintf(stderr, "Could not malloc memory for a\n");
        exit(-1);
    }
    ptr_loc = (double **)malloc(nthreads*sizeof(double *));
    for (i = 0; i < nproc; i++) {
        ptr_loc[i * th_per_p] = (double *)ptr[i];
        for (j = 1; j < th_per_p; j++)
            ptr_loc[i * th_per_p + j] = ptr_loc[i * th_per_p + j - 1] + thread_doubles[j - 1];
    }
    for(i=0; i<nblocks;i ++) {
        for(j=0; j<nblocks; j++) {
            a[i+j*nblocks] = ptr_loc[block_owner(i, j)];
            if ((i == nblocks-1) && (j == nblocks-1)) {
                size = edge*edge;
            } else if ((i == nblocks-1) || (j == nblocks-1)) {
                size = edge*block_size;
            } else {
                size = block_size*block_size;
            }
            ptr_loc[block_owner(i, j)] += size;
        }
    }
#if 0
    for(i=0; i<nblocks*nblocks;i ++) printf("%d: a[%d]=%p\n", me, i, a[i]);
    fflush(stdout);
#endif
    
    /* initialize the array */
    init_array();
    
    /* barrier to ensure all initialization is done */
    armci_msg_barrier();

    /* to remove cold-start misses, all processors touch their own data */
/*    for (l = 0; l < th_per_p; l++) touch_array(block_size, me_th[l]); */
    armci_msg_barrier();

    if(doprint) {
        if(me == 0) {
            printf("Matrix before LU decomposition\n");
            print_array(me); 
        }
        armci_msg_barrier();
    }

#if 1
    for (i = 0; i < nblocks; i++)
        for (j = 0; j < nblocks; j++)
            print_block_dbg(a[i + j * nblocks], "proc %d, a[%d, %d]:\n", me, i, j);
#endif

    TH_INIT(nproc,th_per_p);

    /* Starting the timer */
    if(me == 0) start_timer();

    for (l = 0; l < th_per_p; l++) {
        lu_arg[l][0] = n;
        lu_arg[l][1] = block_size;
        lu_arg[l][2] = l;
        THREAD_CREATE(threads + l, lu, lu_arg[l]);
    }
    
    for (l = 0; l < th_per_p; l++) THREAD_JOIN(threads[l], NULL);
    armci_msg_barrier();

    /* Timer Stops here */
    if(me == 0) 
        printf("\nRunning time = %lf milliseconds.\n\n",  elapsed_time());

    if(doprint) {        
        if(me == 0) {
            printf("after LU\n");
            print_array(me);
        }
        armci_msg_barrier();
    }
    
    /* done */
    ARMCI_Free(ptr[me]);
    ARMCI_Finalize();
    armci_msg_finalize();

    THREAD_LOCK_DESTROY(mutex);
}
Example #10
0
int main (int argc, char *argv[])
{
    unsigned int    outfile_p, outfile, device, i, seek, last_blk, sprint_size, flag = 0;
    char            *buf, *buf_test, c, *buf_prev, buf2[1000];
    struct timespec start, end;
    unsigned long long local_nsec;

    if (argc < 4) {
        printf("Usage <a.out> \"device/file path\" <blocks to test> <character>\n");
        exit (1);
    }

    system("/ssdoptfs/drcontrol.py -d DAE0010T -r all -c on");
    sleep(10);

    for(i = 0; i < 1000; i++) {
        buf2[i] = '\0';
    }

    if ((device = open(argv[1], O_RDWR, O_SYNC)) == -1) {
        printf("Could not open device, exiting\n");
        exit(1);
    }
    
    unlink(OUT_FILE);
    unlink(OUT_FILE_P);

    if ((outfile = open(OUT_FILE, O_RDWR | O_CREAT, O_SYNC)) == -1) {
        printf("Could not open output file, exiting\n");
        exit(1);
    }

    if ((outfile_p = open(OUT_FILE_P, O_RDWR | O_CREAT, O_SYNC)) == -1) {
        printf("Could not open output file, exiting\n");
        exit(1);
    }

    // Allocate buffer
    if ((buf = (char *)malloc(BLOCK_SIZE)) == NULL) {
        printf("Could not allocate buffer, exiting\n");
        exit(1);
    }

    if ((buf_test = (char *)malloc(BLOCK_SIZE)) == NULL) {
        printf("Could not allocate buffer, exiting\n");
        exit(1);
    }

    /*if ((buf_prev = (char *)malloc(BLOCK_SIZE)) == NULL) {
        printf("Could not allocate buffer, exiting\n");
        exit(1);
    }*/

    c = *argv[3];
    printf("\n");

    last_blk = atoi(argv[2]);

    // Fill buffer 
    for (i = 0; i < BLOCK_SIZE; i++) {
        *(buf + i) = c;
    }

    for(seek = 0; seek <= last_blk; seek++) {

        if (lseek(device, seek * BLOCK_SIZE, SEEK_SET) == -1) {
            printf("Seek failed, blknbr %d\n", seek);
        }

        if ((read(device, buf_test, BLOCK_SIZE) == -1)) {
            printf("A read failed, blknbr %d\n", seek);
            break;
        }

//        memcpy(buf_prev, buf, BLOCK_SIZE);
       if (memcmp(buf, buf_test, BLOCK_SIZE)) {
           flag = 1;
           sprint_size = sprintf(buf2, "Inconsistent write detected at blknbr %d, sector %d\n", seek, seek * 8);
           write (outfile, buf2, sprint_size);

           for(i = 0; i < BLOCK_SIZE; i++) {
               if (*(buf_test + i) == c) {
                   printf("partial write detected\n");
                   sprint_size = sprintf(buf2, "Partial Inconsistent Write detected blknbr %d, sector %d\n", seek, seek * 8);
                   write (outfile_p, buf2, sprint_size);
                   write (outfile_p, buf_test, BLOCK_SIZE);
                   write (outfile_p, "\n", 1);
               }
           }
       } else if (flag) {
           printf("out of order write!!\n");
       }
    }
//    printf("Differing block : %s \n",buf_test);
//    printf("Previous block : %s \n",buf_prev);
    printf("normal exit\n");
    close(device);
    close(outfile);
    close(outfile_p);
    return;
}
Example #11
0
int
internal__hydra_connect(unsigned long int host, int port, int protocol, int type)
{
  int s, ret = -1;
  struct sockaddr_in target;
  char *buf, *tmpptr = NULL;
  struct sockaddr_in sin;

#ifndef CYGWIN
  char out[16];
#endif

  if ((s = socket(PF_INET, protocol, type)) >= 0) {
    if (src_port != 0)
    {
      int bind_ok=0;
      sin.sin_family = PF_INET;
      sin.sin_port = htons(src_port);
      sin.sin_addr.s_addr = INADDR_ANY;
      
      //we will try to find a free port down to 512
      while (!bind_ok && src_port >= 512)
      {
	if (bind(s, (struct sockaddr *)&sin, sizeof(sin))==-1)
	{
	      if (verbose)
	        perror("error:");
	      if (errno == EADDRINUSE)
	      {
	      	  src_port--;
		  sin.sin_port = htons(src_port);
	      }
	      else
	      {
		if (errno == EACCES && (getuid() > 0))
		{
			printf("You need to be root to test this service\n");
			return -1;
		}
	      }
	}
	else
		bind_ok=1;
      }
    }  
    if (use_proxy > 0) {
      target.sin_port = htons(proxy_string_port);
      memcpy(&target.sin_addr.s_addr, &proxy_string_ip, 4);
    } else {
      target.sin_port = htons(port);
      memcpy(&target.sin_addr.s_addr, &host, 4);
    }
    target.sin_family = AF_INET;
    signal(SIGALRM, alarming);
    do {
      if (fail > 0)
        sleep(WAIT_BETWEEN_CONNECT_RETRY);
      alarm_went_off = 0;
      alarm(waittime);
      ret = connect(s, (struct sockaddr *) &target, sizeof(target));
      alarm(0);
      if (ret < 0 && alarm_went_off == 0) {
        fail++;
        if (verbose && fail <= MAX_CONNECT_RETRY)
          fprintf(stderr, "Process %d: Can not connect [unreachable], retrying (%d of %d retries)\n", (int) getpid(), fail, MAX_CONNECT_RETRY);
      }
    } while (ret < 0 && fail <= MAX_CONNECT_RETRY);
    if (ret < 0 && fail > MAX_CONNECT_RETRY) {
      if (debug)
        printf("DEBUG_CONNECT_UNREACHABLE\n");

/* we wont quit here, thats up to the module to decide what to do 
 *              fprintf(stderr, "Process %d: Can not connect [unreachable], process exiting\n", (int)getpid());
 *              hydra_child_exit(1);
 */
      extern_socket = -1;
      ret = -1;
      return ret;
    }
    ret = s;
    extern_socket = s;
    if (debug)
      printf("DEBUG_CONNECT_OK\n");

    if (use_proxy == 2) {
      buf = malloc(4096);
      memset(&target, 0, sizeof(target));
      memcpy(&target.sin_addr.s_addr, &host, 4);
      target.sin_family = AF_INET;
#ifdef CYGWIN
      if (proxy_authentication == NULL)
        snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\n\r\n", inet_ntoa((struct in_addr) target.sin_addr), port);
      else
        snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\nProxy-Authorization: Basic %s\r\n\r\n", inet_ntoa((struct in_addr) target.sin_addr), port, proxy_authentication);
#else
      if (proxy_authentication == NULL)
        snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\n\r\n", inet_ntop(AF_INET, &target.sin_addr, out, sizeof(out)), port);
      else
        snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\nProxy-Authorization: Basic %s\r\n\r\n", inet_ntop(AF_INET, &target.sin_addr, out, sizeof(out)), port,
                 proxy_authentication);
#endif
      send(s, buf, strlen(buf), 0);
      recv(s, buf, 4096, 0);
      if (strncmp("HTTP/", buf, strlen("HTTP/")) == 0 && (tmpptr = index(buf, ' ')) != NULL && *++tmpptr == '2') {
        if (debug)
          printf("DEBUG_CONNECT_SSL_OK\n");
      } else {
        if (debug)
          printf("DEBUG_CONNECT_SSL_FAILED (Code: %c%c%c)\n", *tmpptr, *(tmpptr + 1), *(tmpptr + 2));
        if (verbose)
          fprintf(stderr, "Error: CONNECT call to proxy failed with code %c%c%c\n", *tmpptr, *(tmpptr + 1), *(tmpptr + 2));
        close(s);
        extern_socket = -1;
        ret = -1;
        free(buf);
        return ret;
      }
      free(buf);
    }
    fail = 0;
    return ret;
  }
  return ret;
}
Example #12
0
int main()
{
	char mqname[NAMESIZE], msgrv[BUFFER];
	mqd_t mqdes;
	struct timespec ts;
	time_t oldtime, newtime;
	struct mq_attr attr;
	pid_t pid;
	int unresolved = 0, failure = 0;

	sprintf(mqname, "/" FUNCTION "_" TEST "_%d", getpid());

	attr.mq_msgsize = BUFFER;
	attr.mq_maxmsg = BUFFER;
	mqdes = mq_open(mqname, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, &attr);
	if (mqdes == (mqd_t)-1) {
		perror(ERROR_PREFIX "mq_open");
		unresolved = 1;
	}

	pid = fork();
	if (pid != 0) {
		/* Parent process */
		struct sigaction act;
		act.sa_handler = exit_handler;
		act.sa_flags = 0;
		sigemptyset(&act.sa_mask);
		sigaction(SIGABRT, &act, 0);
#ifdef _POSIX_TIMERS
		printf("Using CLOCK_REALTIME\n");
		clock_gettime(CLOCK_REALTIME, &ts);
		oldtime = ts.tv_sec;
		ts.tv_sec = ts.tv_sec + TIMEOUT;
#else
		ts.tv_sec = time(NULL) + TIMEOUT;
		oldtime = time(NULL);
#endif
		ts.tv_nsec = 0;
		mq_timedreceive(mqdes, msgrv, BUFFER, NULL, &ts);
#ifdef _POSIX_TIMERS
		clock_gettime(CLOCK_REALTIME, &ts);
		newtime = ts.tv_sec;
#else
		newtime = time(NULL);
#endif
		if ((newtime - oldtime) < TIMEOUT) {
			printf("FAIL: mq_timedreceive didn't block until "
			       "timout expires\n");
			failure = 1;
		}
		/* Parent is not blocking, let child abort */
		kill(pid, SIGABRT);
		wait(NULL);
		if (mq_close(mqdes) != 0) {
			perror(ERROR_PREFIX "mq_close");
			unresolved = 1;
		}
		if (mq_unlink(mqname) != 0) {
			perror(ERROR_PREFIX "mq_unlink");
			unresolved = 1;
		}
		if (failure == 1 || blocking == 1) {
			printf("Test FAILED\n");
			return PTS_FAIL;
		}
		if (unresolved == 1) {
			printf("Test UNRESOLVED\n");
			return PTS_UNRESOLVED;
		}
		printf("Test PASSED\n");
		return PTS_PASS;
	} else {
		sleep(TIMEOUT + 3); /* Parent is probably blocking
				       send a signal to let it abort */
		kill(getppid(), SIGABRT);
		return 0;
	}
}
Example #13
0
////////////////////////////////////////////////////////////////////////////
// Function: netset
////////////////////////////////////////////////////////////////////////////
int videoset(char **postvars, int form_method)
{
	FILE *fffd,*fp, *vsfd;
	unsigned long	ulTemp;
	unsigned char	ucbuf[sizeof(video_conf)];
	int iTemp, i, size;
	char pctmp[40];
	char iptmp[20];


	// HTML header, print it here
	printf("Content-type: text/html\r\n\r\n");
	printf("\r\n\r\n");
	printf("<html><head></head>");
	fflush(stdout);
	usleep(1000);

	// If we got post, write it into flash
	if(form_method == POST)
	{
		printf("<body><center><BR><font style=\"font-size:12pt\" face=\"Arial\">");
		// Read and preserve content from flash to buffer
		GetConfValues();

		for (i=0; postvars[i]; i+= 2)
		{
#if DEBUG
			printf("DEBUG: [%s] = [%s]<br>", postvars[i], postvars[i+1]);
#endif

			// Parse for video port
			if(!strcmp(postvars[i], "VIDEOPORT"))
			{
				CONF_VIDEO->ServerPort = (unsigned short)atoi(postvars[i+1]);
			}
			
			// parse for quality method
			if(!strcmp(postvars[i], "QUALITYMETHOD"))
			{
				if(!strcmp(postvars[i+1], "1"))
					CONF_VIDEO->QualityMethod = 1;
				else if(!strcmp(postvars[i+1], "2"))
					CONF_VIDEO->QualityMethod = 2;
			}

			// parse for bitrate
			if(!strcmp(postvars[i], "BITRATE"))
			{
				if(!strcmp(postvars[i+1], "1"))
					CONF_VIDEO->BitRate = 1;
				else if(!strcmp(postvars[i+1], "2"))
					CONF_VIDEO->BitRate = 2;
				else if(!strcmp(postvars[i+1], "3"))
					CONF_VIDEO->BitRate = 3;
				else if(!strcmp(postvars[i+1], "4"))
					CONF_VIDEO->BitRate = 4;
				else if(!strcmp(postvars[i+1], "5"))
					CONF_VIDEO->BitRate = 5;
				else if(!strcmp(postvars[i+1], "6"))
					CONF_VIDEO->BitRate = 6;
				else if(!strcmp(postvars[i+1], "7"))
					CONF_VIDEO->BitRate = 7;
				else if(!strcmp(postvars[i+1], "8"))
					CONF_VIDEO->BitRate = 8;
				else if(!strcmp(postvars[i+1], "9"))
					CONF_VIDEO->BitRate = 9;
				else if(!strcmp(postvars[i+1], "10"))
					CONF_VIDEO->BitRate = 10;
				else if(!strcmp(postvars[i+1], "11"))
					CONF_VIDEO->BitRate = 11;
			}
			
			// parse for quality
			if(!strcmp(postvars[i], "QUALITY"))
			{
				if(!strcmp(postvars[i+1], "1"))
					CONF_VIDEO->Quality = 1;
				else if(!strcmp(postvars[i+1], "2"))
					CONF_VIDEO->Quality = 2;
				else if(!strcmp(postvars[i+1], "3"))
					CONF_VIDEO->Quality = 3;
				else if(!strcmp(postvars[i+1], "4"))
					CONF_VIDEO->Quality = 4;
				else if(!strcmp(postvars[i+1], "5"))
					CONF_VIDEO->Quality = 5;
			}
			
			// parse for resolution
			if(!strcmp(postvars[i], "RESOLUTION"))
			{
				if(!strcmp(postvars[i+1], "1"))
					CONF_VIDEO->Resolution = 1;
				else if(!strcmp(postvars[i+1], "2"))
					CONF_VIDEO->Resolution = 2;
				else if(!strcmp(postvars[i+1], "3"))
					CONF_VIDEO->Resolution = 3;
				else if(!strcmp(postvars[i+1], "4"))
					CONF_VIDEO->Resolution = 4;
				else if(!strcmp(postvars[i+1], "5"))
					CONF_VIDEO->Resolution = 5;
				else if(!strcmp(postvars[i+1], "6"))
					CONF_VIDEO->Resolution = 6;
				else if(!strcmp(postvars[i+1], "7"))
					CONF_VIDEO->Resolution = 7;
				else if(!strcmp(postvars[i+1], "8"))
					CONF_VIDEO->Resolution = 8;
				else if(!strcmp(postvars[i+1], "9"))
					CONF_VIDEO->Resolution = 9;
			}
			
			// parse for frame rate
			if(!strcmp(postvars[i], "FRAMERATE"))
			{
				if(!strcmp(postvars[i+1], "1"))
					CONF_VIDEO->FrameRate = 1;
				else if(!strcmp(postvars[i+1], "2"))
					CONF_VIDEO->FrameRate = 2;
				else if(!strcmp(postvars[i+1], "3"))
					CONF_VIDEO->FrameRate = 3;
				else if(!strcmp(postvars[i+1], "4"))
					CONF_VIDEO->FrameRate = 4;
				else if(!strcmp(postvars[i+1], "5"))
					CONF_VIDEO->FrameRate = 5;
				else if(!strcmp(postvars[i+1], "6"))
					CONF_VIDEO->FrameRate = 6;
			}
			
			// parse for brightness
			if(!strcmp(postvars[i], "BRIGHTNESS"))
			{
				CONF_VIDEO->Brightness = (unsigned short)atoi(postvars[i+1]);
			}
			
			// parse for saturation
			if(!strcmp(postvars[i], "SATURATION"))
			{
				CONF_VIDEO->Saturation = (unsigned short)atoi(postvars[i+1]);
			}
			
			// parse for contrast
			if(!strcmp(postvars[i], "CONTRAST"))
			{
				CONF_VIDEO->Contrast = (unsigned short)atoi(postvars[i+1]);
			}
			
			// parse for hue
			if(!strcmp(postvars[i], "HUE"))
			{
				CONF_VIDEO->Hue = (unsigned short)atoi(postvars[i+1]);
			}
			
		} // end of parse loop
		
#if DEBUG
		// Debug the value in struct
		printf("Write result:<br>\n");
		printf("%d<br>\n", CONF_VIDEO->ServerPort);
		printf("%ld<br>\n", CONF_VIDEO->Resolution);
		printf("%ld<br>\n", CONF_VIDEO->BitRate);
		printf("%d<br>\n", CONF_VIDEO->FrameRate);
		printf("%ld<br>\n", CONF_VIDEO->Quality);
		printf("%ld<br>\n", CONF_VIDEO->Saturation);
		printf("%ld<br>\n", CONF_VIDEO->Contrast);
		printf("%ld<br>\n", CONF_VIDEO->Hue);
		//printf("%s<br>\n", CONF_NET->DeviceName);  // string will cause html arrangement disordered
#endif

		// Copy strcut into buf
		memcpy(ucbuf, CONF_VIDEO, sizeof(video_conf));
		
		// Reset flash buffer
		iTemp = VIDEOOFFSET;
		for(i=iTemp; i<(sizeof(video_conf)+iTemp); i++)
		  pcContentBuf[i] = ucbuf[i-iTemp];
		
#if DEBUG
		for(i=0; i<READBUF; i++)
		{
			printf("%d ", pcContentBuf[i]);
		}
		printf("<br>");
#endif
		
		FlashWriteConfig();
		



		unlink(VIDEOSETCFG);
		
		if( (vsfd=fopen(VIDEOSETCFG, "w")) == NULL )
		{
			perror("videoset cfg file create error: ");
			return 0;
		}
		
		if(CONF_VIDEO->ServerPort == 0)
			CONF_VIDEO->ServerPort = 554;
		fprintf(vsfd, "Port %d\n", CONF_VIDEO->ServerPort);

		switch(CONF_VIDEO->FrameRate)
		{
			case 1: fprintf(vsfd, "%s\n", "VideoFrameRate 5"); break;
			case 2: fprintf(vsfd, "%s\n", "VideoFrameRate 10"); break;
			case 3: fprintf(vsfd, "%s\n", "VideoFrameRate 15"); break;
			case 4: fprintf(vsfd, "%s\n", "VideoFrameRate 20"); break;
			case 5: fprintf(vsfd, "%s\n", "VideoFrameRate 25"); break;
			case 6: fprintf(vsfd, "%s\n", "VideoFrameRate 30"); break;
			default: fprintf(vsfd, "%s\n", "VideoFrameRate 30"); break;
		}
		// video size (resolution)
		switch(CONF_VIDEO->Resolution)
		{
			case 1: fprintf(vsfd, "%s\n", "VideoSize 176x120"); break;
			case 2: fprintf(vsfd, "%s\n", "VideoSize 352x240"); break;
			case 3: fprintf(vsfd, "%s\n", "VideoSize 720x480"); break;
			case 4: fprintf(vsfd, "%s\n", "VideoSize 176x144"); break;
			case 5: fprintf(vsfd, "%s\n", "VideoSize 352x288"); break;
			case 6: fprintf(vsfd, "%s\n", "VideoSize 720x576"); break;
			case 7: fprintf(vsfd, "%s\n", "VideoSize 160x120"); break;
			case 8: fprintf(vsfd, "%s\n", "VideoSize 320x240"); break;
			case 9: fprintf(vsfd, "%s\n", "VideoSize 640x480"); break;
			default: fprintf(vsfd, "%s\n", "VideoSize 352x240"); break;
		}

		if(CONF_VIDEO->QualityMethod==1)
		{		
			// video bitrate
			switch(CONF_VIDEO->BitRate)
			{
				case 1: fprintf(vsfd, "%s\n", "VideoBitRate 64"); break;
				case 2: fprintf(vsfd, "%s\n", "VideoBitRate 128"); break;
				case 3: fprintf(vsfd, "%s\n", "VideoBitRate 256"); break;
				case 4: fprintf(vsfd, "%s\n", "VideoBitRate 512"); break;
				case 5: fprintf(vsfd, "%s\n", "VideoBitRate 768"); break;
				case 6: fprintf(vsfd, "%s\n", "VideoBitRate 1024"); break;
				case 7: fprintf(vsfd, "%s\n", "VideoBitRate 1200"); break;
				case 8: fprintf(vsfd, "%s\n", "VideoBitRate 1536"); break;
				case 9: fprintf(vsfd, "%s\n", "VideoBitRate 2048"); break;
				case 10: fprintf(vsfd, "%s\n", "VideoBitRate 2560"); break;
				case 11: fprintf(vsfd, "%s\n", "VideoBitRate 3072"); break;
				default: fprintf(vsfd, "%s\n", "VideoBitRate 1536"); break;
			}
			fprintf(vsfd, "%s\n", "VideoQMin 1"); 
			fprintf(vsfd, "%s\n", "VideoQMax 31"); 

		}
		else if(CONF_VIDEO->QualityMethod==2)
		{
			fprintf(vsfd, "%s\n", "VideoBitRate 2048");		
			// video bitrate
			switch(CONF_VIDEO->Quality)
			{
				case 1: 
					fprintf(vsfd, "%s\n", "VideoQMin 30"); 
					fprintf(vsfd, "%s\n", "VideoQMax 30"); 
					break;
				case 2: 
					fprintf(vsfd, "%s\n", "VideoQMin 24"); 
					fprintf(vsfd, "%s\n", "VideoQMax 24"); 
					break;
				case 3: 					
					fprintf(vsfd, "%s\n", "VideoQMin 18"); 
					fprintf(vsfd, "%s\n", "VideoQMax 18"); 
					break;
				case 4: 					
					fprintf(vsfd, "%s\n", "VideoQMin 12"); 
					fprintf(vsfd, "%s\n", "VideoQMax 12"); 
					break;
				case 5: 					
					fprintf(vsfd, "%s\n", "VideoQMin 6"); 
					fprintf(vsfd, "%s\n", "VideoQMax 6"); 
					break;
				default: 					
					fprintf(vsfd, "%s\n", "VideoQMin 12"); 
					fprintf(vsfd, "%s\n", "VideoQMax 12"); 
					break;
			}
		}
		
		// video GOP size
		//fprintf(vsfd, "%s\n", "VideoGopSize 15	#30");

		fclose(vsfd);













		// set ff.cfg and bring it up
		unlink(FFCONFIGFILE);
		
		if( (fffd=fopen(FFCONFIGFILE, "w")) == NULL )
		{
			perror("videoset: ");
			return 0;
		}
		
		// set port
		if(CONF_VIDEO->ServerPort == 0)
			CONF_VIDEO->ServerPort = 8090;
		fprintf(fffd, "Port %d\n", CONF_VIDEO->ServerPort);
		
		// set bind addr
		fprintf(fffd, "%s\n", "BindAddress 0.0.0.0");
		
		// set max client
		fprintf(fffd, "%s\n", "MaxClients 10");
		
		// set max bandwidth
		fprintf(fffd, "%s\n", "MaxBandwidth 20480");
		
		// custom log - NO
		fprintf(fffd, "%s\n", "CustomLog -");
		
		// not act as a daemon
		fprintf(fffd, "%s\n\n", "NoDaemon");
		
		// Feed1
		fprintf(fffd, "%s\n", "<Feed feed1.ffm>");
		fprintf(fffd, "%s\n", "File /ffmpeg/feed1.ffm");
		fprintf(fffd, "%s\n", "FileMaxSize 2M");	// file size
		fprintf(fffd, "%s\n", "ACL allow 127.0.0.1");
		fprintf(fffd, "%s\n\n", "</Feed>");
		
		// stream1
		fprintf(fffd, "%s\n", "<Stream test.asf>");
		fprintf(fffd, "%s\n", "Feed feed1.ffm");
		fprintf(fffd, "%s\n", "Format asf");
		fprintf(fffd, "%s\n", "AudioSampleRate 22050");		// audio sample rate
		fprintf(fffd, "%s\n", "AudioChannels 1 ");			// audio channel
		//fprintf(fffd, "%s\n", "NoAudio");
		fprintf(fffd, "%s\n", "AudioCodec adpcm_ms");		// audio codec
		fprintf(fffd, "%s\n", "VideoCodec mpeg4");			// video codec
		
		// video frame rate
		switch(CONF_VIDEO->FrameRate)
		{
			case 1: fprintf(fffd, "%s\n", "VideoFrameRate 5"); break;
			case 2: fprintf(fffd, "%s\n", "VideoFrameRate 10"); break;
			case 3: fprintf(fffd, "%s\n", "VideoFrameRate 15"); break;
			case 4: fprintf(fffd, "%s\n", "VideoFrameRate 20"); break;
			case 5: fprintf(fffd, "%s\n", "VideoFrameRate 25"); break;
			case 6: fprintf(fffd, "%s\n", "VideoFrameRate 30"); break;
			default: fprintf(fffd, "%s\n", "VideoFrameRate 30"); break;
		}

		// video size (resolution)
		switch(CONF_VIDEO->Resolution)
		{
			case 1: fprintf(fffd, "%s\n", "VideoSize 176x120"); break;
			case 2: fprintf(fffd, "%s\n", "VideoSize 352x240"); break;
			case 3: fprintf(fffd, "%s\n", "VideoSize 720x480"); break;
			case 4: fprintf(fffd, "%s\n", "VideoSize 176x144"); break;
			case 5: fprintf(fffd, "%s\n", "VideoSize 352x288"); break;
			case 6: fprintf(fffd, "%s\n", "VideoSize 720x576"); break;
			case 7: fprintf(fffd, "%s\n", "VideoSize 160x120"); break;
			case 8: fprintf(fffd, "%s\n", "VideoSize 320x240"); break;
			case 9: fprintf(fffd, "%s\n", "VideoSize 640x480"); break;
			default: fprintf(fffd, "%s\n", "VideoSize 352x240"); break;
		}

		if(CONF_VIDEO->QualityMethod==1)
		{		
			// video bitrate
			switch(CONF_VIDEO->BitRate)
			{
				case 1: fprintf(fffd, "%s\n", "VideoBitRate 64"); break;
				case 2: fprintf(fffd, "%s\n", "VideoBitRate 128"); break;
				case 3: fprintf(fffd, "%s\n", "VideoBitRate 256"); break;
				case 4: fprintf(fffd, "%s\n", "VideoBitRate 512"); break;
				case 5: fprintf(fffd, "%s\n", "VideoBitRate 768"); break;
				case 6: fprintf(fffd, "%s\n", "VideoBitRate 1024"); break;
				case 7: fprintf(fffd, "%s\n", "VideoBitRate 1200"); break;
				case 8: fprintf(fffd, "%s\n", "VideoBitRate 1536"); break;
				case 9: fprintf(fffd, "%s\n", "VideoBitRate 2048"); break;
				case 10: fprintf(fffd, "%s\n", "VideoBitRate 2560"); break;
				case 11: fprintf(fffd, "%s\n", "VideoBitRate 3072"); break;
				default: fprintf(fffd, "%s\n", "VideoBitRate 1536"); break;
			}
			fprintf(fffd, "%s\n", "VideoQMin 1"); 
			fprintf(fffd, "%s\n", "VideoQMax 31"); 

		}
		else if(CONF_VIDEO->QualityMethod==2)
		{
			fprintf(fffd, "%s\n", "VideoBitRate 2048");		
			// video bitrate
			switch(CONF_VIDEO->Quality)
			{
				case 1: 
					fprintf(fffd, "%s\n", "VideoQMin 30"); 
					fprintf(fffd, "%s\n", "VideoQMax 30"); 
					break;
				case 2: 
					fprintf(fffd, "%s\n", "VideoQMin 24"); 
					fprintf(fffd, "%s\n", "VideoQMax 24"); 
					break;
				case 3: 					
					fprintf(fffd, "%s\n", "VideoQMin 18"); 
					fprintf(fffd, "%s\n", "VideoQMax 18"); 
					break;
				case 4: 					
					fprintf(fffd, "%s\n", "VideoQMin 12"); 
					fprintf(fffd, "%s\n", "VideoQMax 12"); 
					break;
				case 5: 					
					fprintf(fffd, "%s\n", "VideoQMin 6"); 
					fprintf(fffd, "%s\n", "VideoQMax 6"); 
					break;
				default: 					
					fprintf(fffd, "%s\n", "VideoQMin 12"); 
					fprintf(fffd, "%s\n", "VideoQMax 12"); 
					break;
			}
		}
		
		
		// video GOP size
		fprintf(fffd, "%s\n", "VideoGopSize 15	#30");
		
		// audio bitrate
		fprintf(fffd, "%s\n", "AudioBitRate 88	#64");
		//fprintf(fffd, "%s\n", "NoAudio");
		
		// StartSendOnKey
		fprintf(fffd, "%s\n", "StartSendOnKey");

		fprintf(fffd, "%s\n\n", "</Stream>");
		
		// specific stream
		fprintf(fffd, "%s\n", "<Stream stat.html>");
		fprintf(fffd, "%s\n", "Format status");
		fprintf(fffd, "%s\n", "ACL allow localhost");
		fprintf(fffd, "%s\n", "ACL allow 192.168.0.0 192.168.255.255");
		fprintf(fffd, "%s\n\n", "</Stream>");
		
		// redirect
		fprintf(fffd, "%s\n", "<Redirect index.html>");
		fprintf(fffd, "%s\n", "URL http://ffmpeg.sourceforge.net/");
		fprintf(fffd, "%s\n", "</Redirect>");
		
		fclose(fffd);
		
		unlink(CONFIG7113);
		
		if( (fp=fopen(CONFIG7113, "w")) == NULL )
		{
			perror("set7113");
			return 0;
		}
		fprintf(fp, "%s\n", "char *7113_tokens[] = {");
//++ Foster
		CONF_VIDEO->Brightness = (CONF_VIDEO->Brightness ? CONF_VIDEO->Brightness : 0x95);
		CONF_VIDEO->Contrast = (CONF_VIDEO->Contrast ? CONF_VIDEO->Contrast : 0x48);
		CONF_VIDEO->Saturation = (CONF_VIDEO->Saturation ? CONF_VIDEO->Saturation : 0x48);
		CONF_VIDEO->Hue = (CONF_VIDEO->Hue ? CONF_VIDEO->Hue : 0x00);
		fprintf(fp, "\"0x48 0x0A 0x%x\",\n", CONF_VIDEO->Brightness);
		fprintf(fp, "\"0x48 0x0B 0x%x\",\n", CONF_VIDEO->Contrast);
		fprintf(fp, "\"0x48 0x0C 0x%x\",\n", CONF_VIDEO->Saturation);
		fprintf(fp, "\"0x48 0x0D 0x%x\",\n", CONF_VIDEO->Hue);
//-- Foster
		fprintf(fp, "%s\n", "0");
		fprintf(fp, "%s\n", "};");		

		fclose(fp);

		//if( system("alarm > /dev/null &") < 0 )
		if( system("nohup alarm > /dev/null &") < 0 )
		{
			perror("videoset:");
		}
		sleep(1);
		
		unlink(MOTIONCONFIG);
	
		if( (fp=fopen(ALARMPID, "r")) == NULL )
		{
			if( (fp=fopen(ALARMPID, "r")) == NULL )
			{	
				//system("alarm > /dev/null &");
				system("nohup alarm > /dev/null &");
				if( (fp=fopen(ALARMPID, "r")) == NULL )
				{
					printf("read pid error\n");
				}
			}
		}
	
		fgets(pctmp,20,fp);
		close(fp);
			
		if( (fffd=fopen(MOTIONCONFIG, "w")) == NULL )
		{
			perror("videoset: ");
			return 0;
		}
			
		fprintf(fffd, "pid %s\n",pctmp);
			
		// detect interval
		fprintf(fffd, "md_interval %d\n",CONF_MOTION->Interval);
			
		//window1 coordinate
			
		if(CONF_MOTION->StartX1!=0xffff && CONF_MOTION->StartY1!=0xffff && CONF_MOTION->StopX1!=0xffff && CONF_MOTION->StopY1!=0xffff)
		{
			if(CONF_MOTION->StartX1!=0 && CONF_MOTION->StartY1!=0 && CONF_MOTION->StopX1!=0 && CONF_MOTION->StopY1!=0)
			{
				fprintf(fffd, "x0_LU %d\n",(CONF_MOTION->StartX1-1)/16);
				fprintf(fffd, "y0_LU %d\n",(CONF_MOTION->StartY1-1)/16);
				if(CONF_MOTION->StopX1%16)
					fprintf(fffd, "x0_RD %d\n",((CONF_MOTION->StopX1-1)/16)+1);
				else
					fprintf(fffd, "x0_RD %d\n",(CONF_MOTION->StopX1-1)/16);
						
				if(CONF_MOTION->StopY1%16)	
					fprintf(fffd, "y0_RD %d\n",((CONF_MOTION->StopY1-1)/16)+1);
				else
					fprintf(fffd, "y0_RD %d\n",((CONF_MOTION->StopY1-1)/16));
			}
		}
			
		//window2 coordinate
		if(CONF_MOTION->StartX2!=0xffff && CONF_MOTION->StartY2!=0xffff && CONF_MOTION->StopX2!=0xffff && CONF_MOTION->StopY2!=0xffff)
		{
			if(CONF_MOTION->StartX2!=0 && CONF_MOTION->StartY2!=0 && CONF_MOTION->StopX2!=0 && CONF_MOTION->StopY2!=0)
			{
				fprintf(fffd, "x1_LU %d\n",(CONF_MOTION->StartX2-1)/16);
				fprintf(fffd, "y1_LU %d\n",(CONF_MOTION->StartY2-1)/16);
				if(CONF_MOTION->StopX2%16)
					fprintf(fffd, "x1_RD %d\n",((CONF_MOTION->StopX2-1)/16)+1);
				else
					fprintf(fffd, "x1_RD %d\n",((CONF_MOTION->StopX2-1)/16));
						
				if(CONF_MOTION->StopY2%16)
					fprintf(fffd, "y1_RD %d\n",((CONF_MOTION->StopY2-1)/16)+1);
				else
					fprintf(fffd, "y1_RD %d\n",((CONF_MOTION->StopY2-1)/16));
			}
		}
			
		//window3 coordinate
		if(CONF_MOTION->StartX3!=0xffff && CONF_MOTION->StartY3!=0xffff && CONF_MOTION->StopX3!=0xffff && CONF_MOTION->StopY3!=0xffff)
		{
			if(CONF_MOTION->StartX3!=0 && CONF_MOTION->StartY3!=0 && CONF_MOTION->StopX3!=0 && CONF_MOTION->StopY3!=0)
			{
				fprintf(fffd, "x2_LU %d\n",(CONF_MOTION->StartX3-1)/16);
				fprintf(fffd, "y2_LU %d\n",(CONF_MOTION->StartY3-1)/16);
					
				if(CONF_MOTION->StopX3%16)
					fprintf(fffd, "x2_RD %d\n",((CONF_MOTION->StopX3-1)/16)+1);
				else
					fprintf(fffd, "x2_RD %d\n",((CONF_MOTION->StopX3-1)/16));
						
				if(CONF_MOTION->StopY3%16)
					fprintf(fffd, "y2_RD %d\n",((CONF_MOTION->StopY3-1)/16)+1);
				else
					fprintf(fffd, "y2_RD %d\n",((CONF_MOTION->StopY3-1)/16));
			}
		}
			
		//window1 detect parameters
		if(CONF_MOTION->StartX1!=0xffff && CONF_MOTION->StartY1!=0xffff && CONF_MOTION->StopX1!=0xffff && CONF_MOTION->StopY1!=0xffff)
		{
			if(CONF_MOTION->StartX1!=0 && CONF_MOTION->StartY1!=0 && CONF_MOTION->StopX1!=0 && CONF_MOTION->StopY1!=0)
			{
				//motion detection method 1 sensitivity
				fprintf(fffd, "mv_th0 %d\n",CONF_MOTION->Sensitivity1);
				//motion detection method 2 sensitivity, 512-> disabled
				fprintf(fffd, "sad_th0 512\n");		
				//motion detection method 3 sensitivity, 512-> disabled
				//fprintf(fffd, "dev_th0 %d\n",CONF_MOTION->Sensitivity1);
				fprintf(fffd, "dev_th0 512\n");
				// motion detection threshold
				fprintf(fffd, "alarm_idx0 %d\n",CONF_MOTION->Threshold1);
			}
		}
			
		//window2 detect parameters
		if(CONF_MOTION->StartX2!=0xffff && CONF_MOTION->StartY2!=0xffff && CONF_MOTION->StopX2!=0xffff && CONF_MOTION->StopY2!=0xffff)
		{
			if(CONF_MOTION->StartX2!=0 && CONF_MOTION->StartY2!=0 && CONF_MOTION->StopX2!=0 && CONF_MOTION->StopY2!=0)
			{
				//motion detection method 1 sensitivity
				fprintf(fffd, "mv_th1 %d\n",CONF_MOTION->Sensitivity2);
				//motion detection method 2 sensitivity, 512-> disabled
				fprintf(fffd, "sad_th1 512\n");		
				//motion detection method 3 sensitivity, 512-> disabled
				fprintf(fffd, "dev_th1 512\n");
				// motion detection threshold
				fprintf(fffd, "alarm_idx1 %d\n",CONF_MOTION->Threshold2);
			}
		}
			
		//window3 detect parameters
		if(CONF_MOTION->StartX3!=0xffff && CONF_MOTION->StartY3!=0xffff && CONF_MOTION->StopX3!=0xffff && CONF_MOTION->StopY3!=0xffff)
		{
			if(CONF_MOTION->StartX3!=0 && CONF_MOTION->StartY3!=0 && CONF_MOTION->StopX3!=0 && CONF_MOTION->StopY3!=0)
			{
				//motion detection method 1 sensitivity
				fprintf(fffd, "mv_th2 %d\n",CONF_MOTION->Sensitivity3);
				//motion detection method 2 sensitivity, 512-> disabled
				fprintf(fffd, "sad_th2 512\n");		
				//motion detection method 3 sensitivity, 512-> disabled
				fprintf(fffd, "dev_th2 512\n");
				// motion detection threshold
				fprintf(fffd, "alarm_idx2 %d\n",CONF_MOTION->Threshold3);
			}
		}
				
		// snapshot filename
		fprintf(fffd, "filename /%s\n","temp");
			
		fprintf(fffd, "rotate %d\n",CONF_MOTION->Rotate);

		fflush(fffd);
		close(fffd);

		// start ffserver and ffmpeg
		//if( system("/ffmpeg/ffserver -f /ffmpeg/ff.cfg > /dev/null&") < 0 )
		if( system("nohup /ffmpeg/ffserver -f /ffmpeg/ff.cfg > /dev/null&") < 0 )
		{
			perror("videoset:");
		}

		sleep(2);
		if(CONF_MOTION->Detection==1)
			//sprintf(pctmp,"/ffmpeg/ffmpeg -ndisplay -motion %s http://localhost:%d/feed1.ffm > /dev/null&",MOTIONCONFIG, CONF_VIDEO->ServerPort);
			sprintf(pctmp,"nohup /ffmpeg/ffmpeg -ndisplay -motion %s http://localhost:%d/feed1.ffm > /dev/null&",MOTIONCONFIG, CONF_VIDEO->ServerPort);
		else
			//sprintf(pctmp,"/ffmpeg/ffmpeg -ndisplay http://localhost:%d/feed1.ffm > /dev/null&",CONF_VIDEO->ServerPort);
			sprintf(pctmp,"nohup /ffmpeg/ffmpeg -ndisplay http://localhost:%d/feed1.ffm > /dev/null&",CONF_VIDEO->ServerPort);

		//printf(pctmp);
		if( system(pctmp) < 0 )
		{
			perror("videoset:");
		}

		printf("Configuration parameters have been saved successfully<br><br>");
		// printf("<font color=red>To make the change active, please reboot the device.<br></font>");
		printf("</center></body></html>");
		fflush(stdout);

		free(CONF_VIDEO);
		free(CONF_NET);
		free(CONF_MOTION);

		// exit here when write
		return 0;
		
	} // end of "if we got post"
	

	////////////////////////////////////////////
	// Start CGI, Get configuration value here
	////////////////////////////////////////////	
	
	
	GetConfValues();
	get_ip(iptmp);
	
	printf("<html><head></head>\n");
	printf("<center><BR>\n");
	printf("<FORM name=videoset ACTION=/cgi-bin/videoset.cgi METHOD=POST>\n");
	printf("<table border=0 width=80%>\n");
	printf("<tr><td class=header><strong>Video Settings</strong>\n");
	printf("<tr><td><hr>\n");
	printf("<table border=0>\n");
	printf("<tr><td width=50%> \n");
	
#if 1
	if(CONF_VIDEO->Resolution==1)
	{
		printf("<object classid=\"clsid:E23FE9C6-778E-49D4-B537-38FCDE4887D8\" id=\"VLCPlugin1\" width=\"176\" height=\"120\">\n");
		printf("<param name=\"Src\" value=\"rtsp://%s:%d\">\n", iptmp, CONF_VIDEO->ServerPort);
	}
	
	if(CONF_VIDEO->Resolution==2)
	{
		printf("<object classid=\"clsid:E23FE9C6-778E-49D4-B537-38FCDE4887D8\" id=\"VLCPlugin1\" width=\"352\" height=\"240\">\n");
		printf("<param name=\"Src\" value=\"rtsp://%s:%d\">\n", iptmp, CONF_VIDEO->ServerPort);
	}
	
	if(CONF_VIDEO->Resolution==3)
	{
		printf("<object classid=\"clsid:E23FE9C6-778E-49D4-B537-38FCDE4887D8\" id=\"VLCPlugin1\" width=\"720\" height=\"480\">\n");
		printf("<param name=\"Src\" value=\"rtsp://%s:%d\">\n", iptmp, CONF_VIDEO->ServerPort);
	}

	if(CONF_VIDEO->Resolution==4)
	{
		printf("<object classid=\"clsid:E23FE9C6-778E-49D4-B537-38FCDE4887D8\" id=\"VLCPlugin1\" width=\"176\" height=\"144\">\n");
		printf("<param name=\"Src\" value=\"rtsp://%s:%d\">\n", iptmp, CONF_VIDEO->ServerPort);
	}

	if(CONF_VIDEO->Resolution==5)
	{
		printf("<object classid=\"clsid:E23FE9C6-778E-49D4-B537-38FCDE4887D8\" id=\"VLCPlugin1\" width=\"352\" height=\"288\">\n");
		printf("<param name=\"Src\" value=\"rtsp://%s:%d\">\n", iptmp, CONF_VIDEO->ServerPort);
	}

	if(CONF_VIDEO->Resolution==6)
	{
		printf("<object classid=\"clsid:E23FE9C6-778E-49D4-B537-38FCDE4887D8\" id=\"VLCPlugin1\" width=\"720\" height=\"576\">\n");
		printf("<param name=\"Src\" value=\"rtsp://%s:%d\">\n", iptmp, CONF_VIDEO->ServerPort);
	}

	if(CONF_VIDEO->Resolution==7)
	{
		printf("<object classid=\"clsid:E23FE9C6-778E-49D4-B537-38FCDE4887D8\" id=\"VLCPlugin1\" width=\"160\" height=\"120\">\n");
		printf("<param name=\"Src\" value=\"rtsp://%s:%d\">\n", iptmp, CONF_VIDEO->ServerPort);
	}

	if(CONF_VIDEO->Resolution==8)
	{
		printf("<object classid=\"clsid:E23FE9C6-778E-49D4-B537-38FCDE4887D8\" id=\"VLCPlugin1\" width=\"320\" height=\"240\">\n");
		printf("<param name=\"Src\" value=\"rtsp://%s:%d\">\n", iptmp, CONF_VIDEO->ServerPort);
	}

	if(CONF_VIDEO->Resolution==9)
	{
		printf("<object classid=\"clsid:E23FE9C6-778E-49D4-B537-38FCDE4887D8\" id=\"VLCPlugin1\" width=\"640\" height=\"480\">\n");
		printf("<param name=\"Src\" value=\"rtsp://%s:%d\">\n", iptmp, CONF_VIDEO->ServerPort);
	}
#endif
	
	printf("</object>\n");

	printf("<td width=50%>\n");
	printf("<table border=0>\n");
	if(CONF_VIDEO->ServerPort>0 && CONF_VIDEO->ServerPort!=255)
		printf("<tr><td>Video Port<td><input type=text name=VIDEOPORT value=%d>\n",CONF_VIDEO->ServerPort);
	else
		printf("<tr><td>Video Port<td><input type=text name=VIDEOPORT>\n");
		
	printf("<tr><td>Quality<td>\n");
	if(CONF_VIDEO->QualityMethod==1)
		printf("<tr><td><input type=radio name=QUALITYMETHOD value=1 checked>Fixed BitRate\n");
	else
		printf("<tr><td><input type=radio name=QUALITYMETHOD value=1>Fixed BitRate\n");
	printf("<td><select  name=BITRATE>\n");

	if(CONF_VIDEO->BitRate==1)
		printf("<option value=1 selected>64Kbps\n");
	else
		printf("<option value=1>64Kbps\n");
		
	if(CONF_VIDEO->BitRate==2)
		printf("<option value=2 selected>128Kbps\n");
	else
		printf("<option value=2>128Kbps\n");
		
	if(CONF_VIDEO->BitRate==3)
		printf("<option value=3 selected>256Kbps\n");
	else
		printf("<option value=3>256Kbps\n");
		
	if(CONF_VIDEO->BitRate==4)
		printf("<option value=4 selected>512Kbps\n");
	else
		printf("<option value=4>512Kbps\n");
		
	if(CONF_VIDEO->BitRate==5)
		printf("<option value=5 selected>768Kbps\n");
	else
		printf("<option value=5>768Kbps\n");
		
	if(CONF_VIDEO->BitRate==6)
		printf("<option value=6 selected>1Mbps\n");
	else
		printf("<option value=6>1Mbps\n");
		
	if(CONF_VIDEO->BitRate==7)
		printf("<option value=7 selected>1.2Mbps\n");
	else
		printf("<option value=7>1.2Mbps\n");
		
	if(CONF_VIDEO->BitRate==8)
		printf("<option value=8 selected>1.5Mbps\n");
	else
		printf("<option value=8>1.5Mbps\n");
		
	if(CONF_VIDEO->BitRate==9)
		printf("<option value=9 selected>2Mbps\n");
	else
		printf("<option value=9>2Mbps\n");
	
	if(CONF_VIDEO->BitRate==10)
		printf("<option value=10 selected>2.5Mbps\n");
	else
		printf("<option value=10>2.5Mbps\n");

	if(CONF_VIDEO->BitRate==11)
		printf("<option value=11 selected>3Mbps\n");
	else
		printf("<option value=11>3Mbps\n");
	
	if(CONF_VIDEO->QualityMethod==2)
		printf("<tr><td><input type=radio name=QUALITYMETHOD checked value=2>Fixed Quality\n");
	else
		printf("<tr><td><input type=radio name=QUALITYMETHOD value=2>Fixed Quality\n");

	printf("<td><select  name=QUALITY>\n");
	
	if(CONF_VIDEO->Quality==1)
		printf("<option value=1 selected>Medium\n");
	else
		printf("<option value=1>Medium\n");
	
	if(CONF_VIDEO->Quality==2)
		printf("<option value=2 selected>Standard\n");
	else
		printf("<option value=2>Standard\n");
		
	if(CONF_VIDEO->Quality==3)
		printf("<option value=3 selected>Good\n");
	else
		printf("<option value=3>Good\n");
		
	if(CONF_VIDEO->Quality==4)
		printf("<option value=4 selected>Detailed\n");
	else
		printf("<option value=4>Detailed\n");
		
	if(CONF_VIDEO->Quality==5)
		printf("<option value=5 selected>Excellent\n");
	else
		printf("<option value=5>Excellent\n");
		
	printf("<tr><td>Resolution<td><select  name=RESOLUTION>\n");
	
	if(CONF_VIDEO->Resolution==1)
		printf("<option  value=1 selected>NTSC(176x120)\n");
	else
		printf("<option  value=1>NTSC(176x120)\n");
		
	if(CONF_VIDEO->Resolution==2)
		printf("<option  value=2 selected>NTSC(352x240)\n");
	else
		printf("<option  value=2>NTSC(352x240)\n");
		
	if(CONF_VIDEO->Resolution==3)
		printf("<option  value=3 selected>NTSC(720x480)\n");
	else
		printf("<option  value=3>NTSC(720x480)\n");
//++ Foster
	if(CONF_VIDEO->Resolution==4)
		printf("<option  value=4 selected>PAL(176x144)\n");
	else
		printf("<option  value=4>PAL(176x144)\n");
	
	if(CONF_VIDEO->Resolution==5)
		printf("<option  value=5 selected>PAL(352x288)\n");
	else
		printf("<option  value=5>PAL(352x288)\n");
	
	if(CONF_VIDEO->Resolution==6)
		printf("<option  value=6 selected>PAL(720x576)\n");
	else
		printf("<option  value=6>PAL(720x576)\n");
	
	if(CONF_VIDEO->Resolution==7)
		printf("<option  value=7 selected>VGA(160x120)\n");
	else
		printf("<option  value=7>VGA(160x120)\n");
	
	if(CONF_VIDEO->Resolution==8)
		printf("<option  value=8 selected>VGA(320x240)\n");
	else
		printf("<option  value=8>VGA(320x240)\n");
	
	if(CONF_VIDEO->Resolution==9)
		printf("<option  value=9 selected>VGA(640x480)\n");
	else
		printf("<option  value=9>VGA(640x480)\n");
//-- Foster
		
	printf("<tr><td>Framerate<td><select  name=FRAMERATE>\n");
	
	if(CONF_VIDEO->FrameRate==1)
		printf("<option  value=1 selected>5fps\n");
	else
		printf("<option  value=1>5fps\n");
		
	if(CONF_VIDEO->FrameRate==2)
		printf("<option  value=2 selected>10fps\n");
	else
		printf("<option  value=2>10fps\n");
		
	if(CONF_VIDEO->FrameRate==3)
		printf("<option  value=3 selected>15fps\n");
	else
		printf("<option  value=3>15fps\n");
		
	if(CONF_VIDEO->FrameRate==4)
		printf("<option  value=4 selected>20fps\n");
	else
		printf("<option  value=4>20fps\n");
		
	if(CONF_VIDEO->FrameRate==5)
		printf("<option  value=5 selected>25fps\n");
	else
		printf("<option  value=5>25fps\n");
		
	if(CONF_VIDEO->FrameRate==6)
		printf("<option  value=6 selected>30fps\n");
	else
		printf("<option  value=6>30fps\n");
//printf("<!--\n");	
	printf("<tr><td>Brightness<td>\n");
	printf("<object classid=\"clsid:F08DF954-8592-11D1-B16A-00C0F0283628\" id=\"Slider1\" width=\"150\" height=\"25\">\n");
	printf("<param name=\"Min\" value=0>\n");
	printf("<param name=\"Max\" value=255>\n");
	printf("<param name=\"Value\" value=%d>\n",CONF_VIDEO->Brightness);
	printf("</object>\n");
	printf("<script>\n");
	printf("function videoset.Slider1::Change()\n");
	printf("{\n");
  	printf("document.all.BRIGHTNESS.value = document.all.Slider1.Value;\n");
	printf("};\n");
	printf("</script>\n");
	printf("<input type=hidden name=BRIGHTNESS value=%d>\n",CONF_VIDEO->Brightness);
	
	printf("<tr><td>Saturation<td>\n");
	printf("<object classid=\"clsid:F08DF954-8592-11D1-B16A-00C0F0283628\" id=\"Slider2\" width=\"150\" height=\"25\">\n");
	printf("<param name=\"Min\" value=0>\n");
	printf("<param name=\"Max\" value=255>\n");
	printf("<param name=\"Value\" value=%d>\n",CONF_VIDEO->Saturation);
	printf("</object>\n");
	printf("<script>\n");
	printf("function videoset.Slider2::Change()\n");
	printf("{\n");
  	printf("document.all.SATURATION.value = document.all.Slider2.Value;\n");
	printf("};\n");
	printf("</script>\n");
	printf("<input type=hidden name=SATURATION value=%d>\n",CONF_VIDEO->Saturation);
	
	printf("<tr><td>Contrast<td>\n");
	printf("<object classid=\"clsid:F08DF954-8592-11D1-B16A-00C0F0283628\" id=\"Slider3\" width=\"150\" height=\"25\">\n");
	printf("<param name=\"Min\" value=0>\n");
	printf("<param name=\"Max\" value=255>\n");
	printf("<param name=\"Value\" value=%d>\n",CONF_VIDEO->Contrast);
	printf("</object>\n");
	printf("<script>\n");
	printf("function videoset.Slider3::Change()\n");
	printf("{\n");
  	printf("document.all.CONTRAST.value = document.all.Slider3.Value;\n");
	printf("};\n");
	printf("</script>\n");
	printf("<input type=hidden name=CONTRAST value=%d>\n",CONF_VIDEO->Contrast);
	
	printf("<tr><td>Hue<td>\n");
	printf("<object classid=\"clsid:F08DF954-8592-11D1-B16A-00C0F0283628\" id=\"Slider4\" width=\"150\" height=\"25\">\n");
	printf("<param name=\"Min\" value=0>\n");
	printf("<param name=\"Max\" value=255>\n");
	printf("<param name=\"Value\" value=%d>\n",CONF_VIDEO->Hue);
	printf("</object>\n");
	printf("<script>\n");
	printf("function videoset.Slider4::Change()\n");
	printf("{\n");
  	printf("document.all.HUE.value = document.all.Slider4.Value;\n");
	printf("};\n");
	printf("</script>\n");
	printf("<input type=hidden name=HUE value=%d>\n",CONF_VIDEO->Hue);
	
//printf("-->\n");
	printf("</table></table>\n");
	printf("<tr><td><hr>\n");
	printf("<tr><td><input type=submit class=button value=Save></td></tr>\n");
	printf("</form></font></center></html>\n");
	
	
	free(CONF_VIDEO);
	free(CONF_NET);
	free(CONF_MOTION);

	return 0;
}
Example #14
0
int main(int argc, char **argv) 
{
	char dir[BUFSIZ];
	struct sock_cl s;
	pid_t child_id;
	int addrlen;
	int status;
	struct question *q; /* are we going to recycle the same data structure over and over again */	

	if(argc != 3) {
		fprintf(stderr, "USAGE: ./udp_client ip_address port_number\n");
		return -1;
	}

	if(argv[1]) 
		strcpy(hostname, argv[1]);
	else
		strcpy(hostname, HOST);
	if(argv[2]) 
		s.port = atoi(argv[2]);
	else
		s.port = port;

	while(obtain_req_type(dir) != 0){
		fprintf(stderr, "Still no request for client\n");
		sleep(2);
	}	
	populate_sock(&s);
	addrlen = s.addrlen; 

	ap_debug("====>Client side port = %d", port);

	/* All transaction are started by client, so it is client which will either ask 
	 * 1. server to send the question or 
	 * 2. process the question send by the user.
	 * in case 1. the user has already asked the question and waiting for response
	 * in case 2. user pushes a question. server sends it to another client, who wants to answer the question
	 * server waits for the response from the user, as soon as response is available, 
	 * the server pushes the question back to first client
	 */
	ap_debug("%p\n",&s.sin);
	while(1) {
		switch(query_type(dir))
		{
				/*  Begin set 1 reqQ-saveA */
			case REQ_QUESTION:
				strcpy(s.buffer, dir);
				client_req_ques(&s);
				q = (struct question *)malloc(sizeof(struct question));
				populate_ques_ds(question_file, q);
				strcpy(dir, s.buffer);
				break;
				/* set 2 reqA-saveQ End */
			case REQ_ANSWER:
				strcpy(s.buffer, dir);
				client_req_ans(&s);
				strcpy(dir, req_type[REQ_STOP]);
				break;
				/* Begin set 2 saveQ-reqA */
			case SAVE_QUESTION:
				/* CAUTION dir and s.buffer contain different values */
				memset(s.buffer, 0, sizeof(s.buffer));
				/* open the question file and populate question data structure */
				q = (struct question *)malloc(sizeof(struct question));
				populate_ques_ds(question_file, q);
				create_qbuf(q,s.buffer);
				client_save_ques(&s, dir); /* dir is populated inside here */
				free_question(q);
				break;
				/* set 1 saveA-reqQ End */
			case SAVE_ANSWER:
				if( access( answer_file, F_OK ) == -1 ) 
						continue;
				/* obtain answer in the buffer */
				/* open the answer file and fill the buffer */
				memset(s.buffer, 0, sizeof(s.buffer));
				populate_if_match(q, answer_file); /* obtain data structure for question */
				create_abuf(q, s.buffer);
				client_save_ans(&s, dir);
				strcpy(dir, req_type[REQ_STOP]);
				free_question(q);
				break;
			case REQ_STOP:
				/* do any cleanup here? */
				return 0;
			case REQ_LOOP:
				/* do any cleanup here? */
				break;
			default:
			case -1:
				fprintf(stderr, "What the fuck bro?\n");
				exit(EXIT_FAILURE);

		}

	sleep(1);
	}

	return 0;
}
Example #15
0
//read one total frame and load the data section(except for the start three bytes) into buf
//and return the length of it(including the checksum bit)
int tty_serial_read(int fds, String tbuf) {
	if(fds<0 || !tbuf) PARAMETER_ERROR("tty_serial_read");
	if(tbuf[0]) memset(tbuf,0,MAX_FRAME_SIZE);
	
	while(tbuf[0]!='~') {
		if(read(fds,tbuf,1)<0) {
			perror("reading ttyUSB0");
			sleep(2);
		}
	}
	tbuf++; //point to the new position
		
	ssize_t ret;
	int i,bytes=1,leng = 2; //bytes:bytes already read, length: bytes to read
	while (leng!=0 && (ret=read(fds,tbuf,leng))!=0) {
		if(ret==-1) {
			if(errno==EINTR)
				continue;
			perror("read the starting 3 bytes");  //no data available in non-blocking mode or other errors
			sleep(2);
			return -1;
		}
		leng -= ret;
		tbuf += ret;
	}
	bytes += 2;
	
	leng = inbuf[1]*256 + inbuf[2] +1;  //including the checksum bit, be careful to use inbuf cauze tbuf is moving!!
	printf("received data section length including the checksum: %d seq: %d\n",leng,inbuf[38]);
	
	//continue reading the followint bytes of length leng and check escape
	int nr_escapes = leng;
	do {
		leng = nr_escapes;
		while (leng!=0 && (ret=read(fds,tbuf,leng))!=0) {
			if(ret==-1) {
				if(errno==EINTR)
					continue;
				perror("read the data section error");
				sleep(1);
				return -1;
			}
			leng -= ret;
			tbuf += ret;
		}
		bytes += nr_escapes;
		
		int i, leng = nr_escapes;
		nr_escapes = 0;
		for(i=bytes-leng;i<bytes;i++) {  //check the newly read bytes
			if(inbuf[i]==0x7D) {
				printf("the byte after escape: %d %d\n",i, inbuf[i+1]);
				//int c = tbuf[1+i];
				//if(c==0x7E || c==0x11 || c==0x13 || c==0x7D) {
				nr_escapes++;
			}
		} 
	} while(nr_escapes);
	
	#ifndef DEBUG
	leng = bytes;
	String fbuf = inbuf;
	int logfds = open("./esclog.txt", O_CREAT | O_RDWR | O_APPEND);
	while (leng!=0 && (ret=write(logfds,fbuf,leng))!=0) {
		if(ret==-1) {
			if(errno==EINTR)
				continue;
			perror("wrinting to log file");
		}
		leng -= ret;
		fbuf += ret;
	}
	if(close(logfds)==-1) perror("close esclog file");
	#endif
	
	//descape and check checksum
	bytes = xbee_frame_descape(inbuf,bytes);		
	if(xbee_set_checksum(&inbuf[3],bytes-3)!=0) {
		printf("%s\n","checksum error...");
		//memset(inbuf,0,bytes);
		return 0;
	} else {
		printf("%s total bytes after descape: %d seq: %d\n","checksum perfect!",bytes,);
	}
	
	#ifndef DEBUG
	leng = bytes;
	fbuf = inbuf;
	int dlogfds = open("./esclog.txt", O_CREAT | O_RDWR | O_APPEND);
	while (leng!=0 && (ret=write(dlogfds,fbuf,leng))!=0) {
		if(ret==-1) {
			if(errno==EINTR)
				continue;
			perror("wrinting to dlog file");
		}
		leng -= ret;
		fbuf += ret;
	}
	if(close(dlogfds)==-1) perror("close desclog file");
	#endif
	
	return bytes;
}
	int main(int argc, char *argv[])
	{
		if(argc!=2)
		{
		    printf( "usage: %d <Memory in Kbs>", argc );
		}

		int nmeg,l_retval,tot_megs =0;
		char *ptr,buf[128];
		char *t;
		int reqdMegs, n;
		int noOfMallocs =1;
		int leftOver=0;
		tot_megs=0;
		
		if (ptr==NULL) 
		{
			printf("\n\n");
			exit (0);
		}
		reqdMegs=atoi(argv[1])/1024;
		if(reqdMegs>2047)
		{
		  noOfMallocs = reqdMegs/2047 + 1;
		  leftOver = reqdMegs%2047;
		  n=2047; 
		}
		else
		{
		  n=reqdMegs;
		}
		int nmegs[noOfMallocs];
		int i;
	
	
		nmeg=n*(1024*1024);
	
		void *mptr[noOfMallocs];
		for(i=0;i<noOfMallocs;i++)	
		{
		 mptr[i]=malloc(nmeg);
		}
		if(leftOver>0)
		{
			mptr[i]=malloc(leftOver*(1024*1024));
		}
		int j=0;
		while (1) {
		for(i=0;i<noOfMallocs;i++)		
		{
		if(tot_megs<reqdMegs)	 
		 {
			tot_megs=(tot_megs+n);
		 }
		if (mptr == NULL)
		{
		
			/* Error message */
			printf("malloc %d more megs failed (%d total)\n",n,tot_megs);
			exit(1);
		}
		else 
		{
			if(tot_megs<reqdMegs)		
			{
				//printf("%d megs additional RAM, Total megs = %d \n\n",n,tot_megs);
			}
			else if(tot_megs != reqdMegs)
			{
				tot_megs = tot_megs-n+leftOver;			
				//printf("%d megs additional RAM, Total megs = %d \n\n",leftOver,tot_megs);
			}
		}

		 for (j=0;j<nmeg;j+=1024)
			{
				*((char *)mptr[i]+j)='!';
			}
	
	}
	sleep(10);
		} /* while */

		printf("\n\n");
		return 0;
	} /* main */
Example #17
0
int main() {
    tty_serial_init();
    
    #ifdef RD
    #ifdef AU
    while(1) {
		int bytes = 0;
		while(bytes<=0) {
			bytes = tty_serial_read(tty_fds,inbuf);
			//printf("received data length: %d\n",bytes);
		}
		printf("received frame length: %d %d %d %d %d\n",bytes,inbuf[2],inbuf[inbuf[2]+3],inbuf[5],inbuf[6]);
		mqtt_ptr_t mydata = xbee_data_read(&inbuf[3],bytes-4); //only the data section, excluding checksum
		if(mydata) {      
			//data_print(mydata);
			//free(mydata);
		}

		int logfds = open("./rdesclog.txt", O_CREAT | O_RDWR | O_APPEND);
		int ret = 0, leng = bytes;
		String fbuf = inbuf;
		while (leng>0 && (ret=write(logfds,fbuf,leng))!=0) {
			if(ret==-1) {
				if(errno==EINTR)
					continue;
				perror("wrinting to log file");
			}
			leng -= ret;
			fbuf += ret;
		}
		if(close(logfds)==-1) perror("close log file");	
	}
		    
    #else
	
    int bytes = 0;
    while(bytes<=0) {			
		memset(inbuf,0,MAX_FRAME_SIZE);
		bytes = read(tty_fds,inbuf,MAX_FRAME_SIZE);
		printf("received data length: %d %d %d %d %d\n",bytes,inbuf[2],inbuf[inbuf[2]+4+2],inbuf[5],inbuf[6]);
		sleep(3);
	}
			
	bytes = xbee_frame_descape(inbuf,bytes);
	printf("received data length: %d %d %d %d %d\n",bytes,inbuf[2],inbuf[inbuf[2]+3],inbuf[5],inbuf[6]);
	if(xbee_set_checksum(&inbuf[3],inbuf[2]+1)) printf("%s\n","checksum error");
	
	/*
	int logfds = open("./esclog.txt", O_CREAT | O_RDWR | O_APPEND);
	int ret = 0, leng = bytes;
	String fbuf = inbuf;
	while (leng>0 && (ret=write(logfds,fbuf,leng))!=0) {
		if(ret==-1) {
			if(errno==EINTR)
				continue;
			perror("wrinting to log file");
		}
		leng -= ret;
		fbuf += ret;
	}
	if(close(logfds)==-1) perror("close log file");				
	*/
		
	mqtt_ptr_t mydata = xbee_data_read(&inbuf[3],bytes-4);
	if(mydata) {      
		//data_print(mydata);
		//free(mydata);
	}
	#endif
	
	if(close(tty_fds)==-1) perror("close ttyUSB file");
    #endif 

	#ifdef WR

	while(1) {
		char mac_addr[8] = {0x00,0x13,0xA2,0x00,0x40,0x7A,0x24,0x7A};
		char ntw_addr[2] = {0xFF,0xFE};
		//String RFData = (char*)mqtt->msg;	
		//int leng = mqtt->len;
		//char ntw_addr[2] = {0xFF,0xFE};
		//String RFData = "00 0hellohellohellohellohellohello";
		char RFData[11] = { 0x0B, 0x02, 0x00, 0x00, 0x13, 0xA2, 0x00, 0x40, 0x79, 0x5B, 0xCE };
		int leng = 11;
		int bytes = xbee_txReq_frame_assemble(mac_addr,ntw_addr,0,0,RFData,leng);
	
		/*
		int logfds = open("./wresclog.txt", O_CREAT | O_RDWR | O_APPEND);
		int ret = 0;
		leng = bytes;
		String fbuf = outbuf;
		while (leng>0 && (ret=write(logfds,fbuf,leng))!=0) {
			if(ret==-1) {
				if(errno==EINTR)
					continue;
				perror("wrinting to log file");
			}
			leng -= ret;
			fbuf += ret;
		}
		if(close(logfds)==-1) perror("close log file");	
		*/
		
		bytes = tty_serial_write(tty_fds,outbuf,bytes);
		printf("write %d bytes... %d\n",bytes,RFData[0]);
		
		sleep(10);
    }

    #endif

    
    return 0;
}
Example #18
0
File: main.c Project: mdhender/jr
/* this is a child web server process, so we can exit on errors */
void web(int fd, int hit) {
    int j, file_fd;
    long i;
    char *fstr;
    static char buffer[BUFSIZE + 1]; /* static so zero filled */
    long ret = read(fd, buffer, BUFSIZE);   /* read Web request in one go */
    
    if (ret == 0 || ret == -1) {
        /* read failure stop now */
        jr_log(SORRY, "failed to read browser request", "", fd);
    } else if (ret > 0 && ret < BUFSIZE) {
        /* return code is valid chars */
        buffer[ret] = 0;          /* terminate the buffer */
    } else {
        buffer[0] = 0;
    }
    
    for (i = 0; i < ret; i++) {
        /* remove CF and LF characters */
        if (buffer[i] == '\r' || buffer[i] == '\n') {
            buffer[i] = '*';
        }
    }
    
    jr_log(LOG, "request", buffer, hit);
    
    if (strncmp(buffer, "GET ", 4) && strncmp(buffer, "get ", 4)) {
        jr_log(SORRY, "Only simple GET operation supported", buffer, fd);
    }
    
    for (i = 4; i < BUFSIZE; i++) {
        /* null terminate after the second space to ignore extra stuff */
        if (buffer[i] == ' ') {
            /* string is "GET URL " +lots of other stuff */
            buffer[i] = 0;
            break;
        }
    }
    
    for (j = 0; j < i - 1; j++) {
        /* check for illegal parent directory use .. */
        if (buffer[j] == '.' && buffer[j + 1] == '.') {
            jr_log(SORRY, "Parent directory (..) path names not supported", buffer, fd);
        }
    }
    
    if (!strncmp(&buffer[0], "GET /\0", 6) || !strncmp(&buffer[0], "get /\0", 6) ) {
        /* convert no filename to index file */
        (void)strcpy(buffer, "GET /index.html");
    }
    
    /* work out the file type and check we support it */
    unsigned long buflen = strlen(buffer);
    fstr = (char *)0;
    
    for (i = 0; extensions[i].ext != 0; i++) {
        unsigned long len = strlen(extensions[i].ext);
        
        if (!strncmp(&buffer[buflen - len], extensions[i].ext, len)) {
            fstr = extensions[i].filetype;
            break;
        }
    }
    
    if (fstr == 0) {
        jr_log(SORRY, "file extension type not supported", buffer, fd);
    }
    
    if ((file_fd = open(&buffer[5], O_RDONLY)) == -1) {
        /* open the file for reading */
        jr_log(SORRY, "failed to open file", &buffer[5], fd);
    }
    
    jr_log(LOG, "SEND", &buffer[5], hit);
    (void)sprintf(buffer, "HTTP/1.0 200 OK\r\nContent-Type: %s\r\n\r\n", fstr);
    (void)write(fd, buffer, strlen(buffer));
    
    /* send file in 8KB block - last block may be smaller */
    while ((ret = read(file_fd, buffer, BUFSIZE)) > 0) {
        (void)write(fd, buffer, ret);
    }
#ifdef LINUX
    sleep(1);       /* to allow socket to drain */
#endif
    exit(1);
}
Example #19
0
void 
Controller::handle_transition(Transition transition, void* param)
{
	if (transition == READY_TO_START_REQUESTED || transition == RETRY_TO_START_REQUESTED)
	{
		std::pair<Database_t*, Camera_t*>* temp_pair = reinterpret_cast<std::pair<Database_t*, Camera_t*>*>(param);
		if (temp_pair->second->cam_brand)
		{
			dispatcher->set_param("tracker", "prefix", temp_pair->second->vid_dir);
			dispatcher->send_signal("ipcameracapture", START, temp_pair->second);
			b_using_ipcam = true;
		}
		else
		{
			bool recorder_switch = false;
			dispatcher->set_param("tracker", "recorder-switch", &recorder_switch); 
			dispatcher->send_signal("videoloader", START, temp_pair->second);
			b_using_ipcam = false;
		}

		dispatcher->send_signal("tracker", START, NULL);
		dispatcher->send_signal("dbmanager", START, temp_pair->first);

		delete temp_pair;
	}
	else if (transition == READY_TO_EXIT || transition == EXIT_REQUESTED_TO_EXIT)
	{
		dispatcher->send_signal("controller", 0, NULL);
		dispatcher->send_signal("ipcameracapture", 0, NULL);
		dispatcher->send_signal("tracker", 0, NULL);
		dispatcher->send_signal("videoloader", 0, NULL);
		dispatcher->send_signal("dbmanager", 0, NULL);
	}
	else if (transition == STARTED_TO_RETRY ||
			transition == STARTED_TO_STOP_REQUESTED ||
			transition == START_REQUESTED_TO_STOP_REQUESTED ||
			transition == START_REQUESTED_TO_EXIT_REQUESTED ||
			transition == STARTED_TO_EXIT_REQUESTED)
	{
		dispatcher->send_signal("ipcameracapture", STOP, NULL);
		dispatcher->send_signal("tracker", STOP, NULL);
		dispatcher->send_signal("videoloader", STOP, NULL);
	}
	else if (transition == STARTED_TO_STARTED)
		dispatcher->send_signal("tracker", NEW_IMAGE, param);
	else if (transition == RETRY_TO_RETRY)
	{
		sleep (10);
		mainWindow->on_startBtn_clicked();
	}
	else if (transition == START_REQUESTED_TO_STARTED && mainWindow->isRecordVideoChkBoxChecked())
	{
		videoWriter = new cv::VideoWriter("output.avi", CV_FOURCC('M','J','P','G'), 30, cvSize(640, 480), true);
	}
	else if ((transition == STOP_REQUESTED_TO_READY || transition == EXIT_REQUESTED_TO_EXIT) && videoWriter)
	{
		delete videoWriter;
		videoWriter = NULL;
	}

	if (transition != STARTED_TO_STARTED)
		mainWindow->stateReport(strdup(state_get_name(transition_get_post_state(transition))));
}
Example #20
0
main(int argc, char **argv){

	system("rm -r tmp log");
	system("mkdir tmp log");
	int i;
	int cont=0;
	ts cpu_time_series,queue_time_series, kernel_queue_time_series;
	initialize(&cpu_time_series);
	initialize(&queue_time_series);
	initialize(&kernel_queue_time_series);
	//time series initialization
	/*for(i=0;i<WINDOW;i++) {
		cpu_time_series[i]=0;
		queue_time_series[i]=0;
	}*/

	while(1){

		if(cont>=WINDOW){
			flag_window=1;
		} 
		if(flag_window==1){

			dequeue(&cpu_time_series);
			dequeue(&queue_time_series);
			dequeue(&kernel_queue_time_series);
		}

		//CPU UTILIZATION
		//system("mpstat 1 1 | grep age | awk {' print 100-$11 '} | tee tmp/cpu-usage >> log/cpu-usage");
		//sprintf(command,"/sys/fs/cgroup/cpuacct/%s/cpuacct.usage",argv[1]);
		system("cat /proc/stat | grep cpu | head -n 1 | awk {' print $5 '} | tee tmp/cpu-usage >> log/cpu");
		sprintf(command,"tmp/cpu-usage");

		ifp = fopen(command,mode);
        if (ifp ==NULL) printf("ERROR IN OPEN CPU USAGE FILE");
        fscanf(ifp,"%ld",&cpu_usage);
       	fclose(ifp);
       	
		if(flag == 1) {// if is the first iteration
			cpu_usage_prev=0; 
			flag = 0;
		}
		//cpu_usage=(cpu_usage-cpu_usage_prev)/TICS;
		cpu_usage_perc=100-(cpu_usage-cpu_usage_prev)/(CPUS*1.0);
		if(cpu_usage_perc<0) cpu_usage_perc=0.0;

		enqueue(&cpu_time_series,cpu_usage_perc);
		//cpu_time_series[cont]=cpu_usage_perc;

		sprintf(command,"echo %f >> log/cpu-usage",simple_average(&cpu_time_series));
		system(command);

		active_time_percent=activetime(&cpu_time_series);
	

		sprintf(command,"echo %f >> log/activetime",active_time_percent);
		system(command);

		if(DEBUG) printf("------------------\nCPU Active time: %f\n\n", active_time_percent);
		if(DEBUG) printf("CPU TIME: %ld CPU TIME PREVIOUS: %ld RESULT: %ld\n", cpu_usage,cpu_usage_prev,cpu_usage-cpu_usage_prev);
		if(DEBUG) printf("CPU: %f\n", cpu_usage_perc);
		if(DEBUG) printf("CPU Moving Average: %f\n", simple_average(&cpu_time_series));
		if(DEBUG) printf("CPU WMA: %f\n", wheighted_average(&cpu_time_series));
		if(DEBUG) printf("TIME SERIES SIZE: %d\n", size(&cpu_time_series));


		cpu_usage_prev=cpu_usage;
        	//Compute active duration times
        	//The active duration is the time interval between two idle states
        if(cpu_usage_perc <= ACTIVE_TRSH && active_duration>0){
        	// The VM is in now in idle state
        	sprintf(command,"echo %ld >> log/active-duration",active_duration);
    		system(command);
    		active_duration=0;
        }
        else{
        	active_duration+=1;
        	//sprintf(command,"echo %ld >> log/active-duration",active_duration);
    		//system(command);
        }
		//QUEUE BACKLOG
		
		sprintf(command,"tc -s -d qdisc show dev eth0 | grep backlog | awk {' print $2 '} | sed \'s/b//\' | tee tmp/queue >> log/queue");
  		system(command);
  		sprintf(command,"tail -n 1 log/kernel-queue > tmp/kernel-queue"); 
  		system(command);
    	//netstat -untpa |  awk '{Queue += $3; } END {  print Queue }'
    	//sprintf(command,"netstat -untpaw |  | tee tmp/queue >> log/queue");
    	

		sprintf(command,"tmp/queue");
    	ifp = fopen(command,mode);
        if (ifp ==NULL) printf("ERROR IN OPEN QUEUE FILE");
        fscanf(ifp,"%f",&queue);
       	fclose(ifp);
       	if(DEBUG) printf("QUEUE: %f\n", queue);
       	if(queue>0) enqueue(&queue_time_series,queue);
       	else enqueue(&queue_time_series,0);
       	//queue_time_series[cont]=queue;

       	sprintf(command,"tmp/kernel-queue");
    	ifp = fopen(command,mode);
        if (ifp ==NULL) printf("ERROR IN OPEN KERNEL QUEUE FILE");
        fscanf(ifp,"%f",&kernel_queue);
       	fclose(ifp);
       	if(DEBUG) printf("KERNEL QUEUE: %f\n", kernel_queue);
       	if(queue>0) enqueue(&queue_time_series,kernel_queue);
       	else enqueue(&queue_time_series,0);

       	queue_average=simple_average(&queue_time_series);
       	queue_average_wheighted=wheighted_average(&queue_time_series);

       	kernel_queue_average=simple_average(&kernel_queue_time_series);
       	kernel_queue_average_wheighted=wheighted_average(&kernel_queue_time_series);

       	sprintf(command,"echo %f >> log/queue-moving-average",queue_average);
    	system(command);
    	
       	sprintf(command,"echo %f >> log/queue-moving-average",queue_average_wheighted);
    	system(command);

    	sprintf(command,"echo %f >> log/kernel-queue-moving-average",kernel_queue_average);
    	system(command);
    	
       	sprintf(command,"echo %f >> log/kernel-queue-moving-average",kernel_queue_average_wheighted);
    	system(command);
    	

    	if(DEBUG) printf("QUEUE Moving Average: %f\n", queue_average);
    	if(DEBUG) printf("QUEUE WMA: %f\n", queue_average_wheighted);
	queue_usage=queue_average/1500000;
    	guiltiness=-0.9*(active_time_percent/(1+queue_average))+1.0*active_time_percent+0.1*(1/(1.01-(cpu_usage_perc/100.0)))+0.001*(1/(1-queue_usage));
    	if(guiltiness>1.0) guiltiness=1;
    	if(DEBUG) printf("GUILTINESS: %f\n", guiltiness);
    	sprintf(command,"echo %f >> log/guiltiness",guiltiness);
		system(command);


    	if(flag_window==0) {
    		cont++;
    		
    	}
		sleep(TICS);
	}

}
Example #21
0
int main(int argc, char *argv[]) {
#else
int OCG_main(char is_local_server[FILENAME_LENGTH_MAX]) { 
#endif  
	int state = STATE_START_OCG;
	char web_XML_folder[DIR_LENGTH_MAX] = "";
	char output_dir[DIR_LENGTH_MAX] = ""; // the output folder during the OCG procedure. Change step by step

	char *OPENAIR_TARGETS=getenv("OPENAIR_TARGETS");
	if (OPENAIR_TARGETS == NULL) {
		LOG_E(OCG, "please set the PATH for OPENAIR_TARGETS");
		exit(EXIT_FAILURE);
	}

	if (!strcmp(is_local_server, "0")) { // Eurecom web server
		strcpy(web_XML_folder, WEB_XML_FOLDER);
		strcat(output_dir, OUTPUT_DIR);
	} else { // local user
		
	  sprintf(web_XML_folder,"%s/SIMU/EXAMPLES/OSD/WEBXML/",getenv("OPENAIR_TARGETS"));
	  sprintf(output_dir,"%s/SIMU/EXAMPLES/OSD/RESULTS/",getenv("OPENAIR_TARGETS"));
	  /*
	  strcpy(web_XML_folder, OPENAIR_TARGETS);
		strcpy(output_dir, OPENAIR_TARGETS);
		
		char *slash;
		slash = web_XML_folder + strlen(web_XML_folder) - 1;
		if (strcmp(slash, "/")) { // check if the path OPENAIR_TARGETS is ended with a '/'
			strcat(web_XML_folder, "/");
			strcat(output_dir, "/");
		}
		strcat(web_XML_folder, "SIMU/EXAMPLES/OSD/WEBXML/");
		strcat(output_dir, "SIMU/EXAMPLES/OSD/RESULTS/");
	  */ }

	LOG_I(OCG, "Folder for detecting the XML configuration file is %s\n", web_XML_folder);
	LOG_I(OCG, "Folder for generating the results is %s\n", output_dir);
	LOG_I(OCG, "OSD XML config file is %s\n", is_local_server);


	while(state != STATE_END) {
	
		switch(state) {
			
			case STATE_START_OCG :
				LOG_I(OCG, "OCG starts ...\n\n");
				get_opt_OK = MODULE_NOT_PROCESSED; // -9999 is the initial value, representing the module not processed
				detect_file_OK = MODULE_NOT_PROCESSED;
				create_dir_OK = MODULE_NOT_PROCESSED;

				// to write the pid into a file 'OCG.pid' so that the web portal part could check if OCG is running
				/*
				pid_t pid;
				pid = getpid();
				FILE *OCG_pid;
				OCG_pid = fopen("OCG.pid", "w");
				fprintf(OCG_pid, "%d\n", pid);
				fclose(OCG_pid);
				*/
#ifdef TEST_OCG
				state = STATE_GET_OPT;

			case STATE_GET_OPT :
				get_opt_OK = get_opt(argc, argv);
				if (get_opt_OK == MODULE_OK) {
					strcpy(src_file, LOCAL_XML_FOLDER);
					copy_or_move = 1;
					state = STATE_INI_EMU;
				} else if (get_opt_OK == GET_HELP) state = STATE_END;
				else state = STATE_DETECT_FILE;
				break;
#else
				state = STATE_DETECT_FILE;
				//get_opt_OK == MODULE_OK;
#endif

			case STATE_DETECT_FILE :
				strcpy(src_file, web_XML_folder);
				detect_file_OK = detect_file(src_file, is_local_server);
				if (detect_file_OK == MODULE_OK) {
					if ((!strcmp(is_local_server, "0")) || (!strcmp(is_local_server, "-1"))) copy_or_move = 2;
					state = STATE_INI_EMU;
				} else if (detect_file_OK == MODULE_ERROR) state = STATE_GENERATE_REPORT;
				else if (detect_file_OK == NO_FILE) {
					state = STATE_DETECT_FILE;
					sleep(1);
				}
				break;
				
			case STATE_INI_EMU : // before initiating an emu, an XML file should be found above 
				parse_filename_OK = MODULE_NOT_PROCESSED;
				create_dir_OK = MODULE_NOT_PROCESSED;
				parse_XML_OK = MODULE_NOT_PROCESSED;
				save_XML_OK = MODULE_NOT_PROCESSED;
//				call_emu_OK = MODULE_NOT_PROCESSED;
				//config_mobi_OK = MODULE_NOT_PROCESSED;
				generate_report_OK = MODULE_NOT_PROCESSED;

				LOG_I(OCG, "An emulation for file %s is initiated\n", filename);
				state = STATE_PARSE_FILENAME;
				break;

			case STATE_PARSE_FILENAME :
				strcat(src_file, filename);
				if ((parse_filename_OK = parse_filename(filename)) == MODULE_OK) state = STATE_CREATE_DIR;
				else {
					if (copy_or_move == 2) {
						remove(src_file);
						state = STATE_DETECT_FILE;
					} else state = STATE_GENERATE_REPORT;
				}
				break;
				
			case STATE_CREATE_DIR :
				if ((create_dir_OK = create_dir(output_dir, user_name, file_date)) == MODULE_OK) {
					state = STATE_PARSE_XML;
					strcat(output_dir, user_name);
					strcat(output_dir, "/");
					strcat(output_dir, file_date);
					strcat(output_dir, "/");
					strcpy(dst_dir, output_dir);
					oai_emulation.info.output_path = &dst_dir; // information for other modules within OAI
				} else state = STATE_GENERATE_REPORT;
				break;
				
			case STATE_PARSE_XML :
				if ((parse_XML_OK = parse_XML(src_file)) == MODULE_OK) state = STATE_SAVE_XML;
				else {
					if (copy_or_move == 2) remove(src_file);
					state = STATE_GENERATE_REPORT;
				}
				break;
				
			case STATE_SAVE_XML :
			  if ((save_XML_OK = save_XML(copy_or_move, src_file, output_dir, filename)) == MODULE_OK) 
				state = STATE_CALL_EMU;
			  else state = STATE_GENERATE_REPORT;
			  break;
			  
		        case STATE_CALL_EMU : // change this state to set_params

				if ((detect_file_OK == MODULE_OK) && (parse_filename_OK == MODULE_OK) && (create_dir_OK == MODULE_OK) && (parse_XML_OK == MODULE_OK) && (save_XML_OK == MODULE_OK)) { 
				// if the above tasks are all successful, we could tell the oaisim_config.c that everything is ready before running the emulation
					oai_emulation.info.ocg_ok = 1;
				}
							
#ifdef TEST_OCG				
				call_emu_OK = call_emu(output_dir);
				// config_mobi_OK = config_mobi("RWMEmulator.xml", filename); // generate the XML for Mobigen
#endif
				state = STATE_GENERATE_REPORT;
				break;
				
			case STATE_GENERATE_REPORT :
				if (create_dir_OK != MODULE_OK) {
					// a temp folder is required when the output folder could not be correctly generated
					strcpy(output_dir, OPENAIR_TARGETS);
					strcat(output_dir, "SIMU/EXAMPLES/OSD/");
					strcat(output_dir, TEMP_OUTPUT_DIR);
					struct stat st;
					if(stat(output_dir, &st) != 0) { // if temp output directory does not exist, we create it here
						mkdir(output_dir, S_IRWXU | S_IRWXG | S_IRWXO);
						LOG_I(OCG, "temp output directory %s is created", output_dir);
					}
				} else {
					//strcat(output_dir, "SCENARIO/STATE/"); // if needeed the outpur directory can be further set
					LOG_I(OCG, "Output directory is %s \n", output_dir);
				}
				generate_report(output_dir, "OCG_report.xml");
				if (copy_or_move == 1) state = STATE_END;
				else state = STATE_END;
				//else state = STATE_DETECT_FILE;
				break;
		}
	} // end while
	// Cleanup function for the XML library.
	xmlCleanupParser();
	// this is to debug memory for regression tests
	xmlMemoryDump();
	LOG_I(OCG, "... OCG ends\n\n");
#ifdef TEST_OCG
	return 0;
#else
	return 1;
#endif
}
Example #22
0
File: 7-1.c Project: 1587/ltp
int main(void)
{
	sem_t *mysemp;
	char semname[28];
	int pid, status;

	sprintf(semname, "/" FUNCTION "_" TEST "_%d", getpid());

	mysemp = sem_open(semname, O_CREAT, 0, 1);
	if (mysemp == SEM_FAILED || mysemp == NULL) {
		perror(ERROR_PREFIX "sem_open");
		return PTS_UNRESOLVED;
	}

	if (sem_wait(mysemp) == -1) {
		perror(ERROR_PREFIX "sem_wait");
		return PTS_UNRESOLVED;
	}

	pid = fork();
	if (pid == 0) {		// child create the semaphore.
		struct sigaction act;

		act.sa_handler = handler;
		act.sa_flags = 0;
		if (sigemptyset(&act.sa_mask) == -1) {
			perror("Error calling sigemptyset\n");
			return CHILDFAIL;
		}
		if (sigaction(SIGABRT, &act, 0) == -1) {
			perror("Error calling sigaction\n");
			return CHILDFAIL;
		}

		sem_wait(mysemp);

		if (errno == EINTR) {
			printf("Test PASSED\n");
			return (CHILDPASS);
		}
		puts("TEST FAILED: errno != EINTR");
		return (CHILDFAIL);

	} else {		// parent to send a signal to child
		int i;
		sleep(1);
		status = kill(pid, SIGABRT);	// send signal to child
		if (wait(&i) == -1) {
			perror("Error waiting for child to exit\n");
			return PTS_UNRESOLVED;
		}

		if (!WEXITSTATUS(i)) {
			return PTS_FAIL;
		}
		puts("TEST PASSED");
		sem_unlink(semname);
		return PTS_PASS;
	}

	return PTS_UNRESOLVED;
}
Example #23
0
char *block()
{
	sleep(5);
	return strdup("slept for 5 seconds");
}
Example #24
0
int spi_send()
{
    /* Defining Variables */
    int sockfd; 
    int flag = 0;
    int nsockfd; 
    int num;
    int sin_size; 
    struct sockaddr_in addr_local; /* client addr */
    struct sockaddr_in addr_remote; /* server addr */
    char revbuf[LENGTH]; // Receiver buffer

    /* Get the Socket file descriptor */
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 )
    {
        fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor. (errno = %d)\n", errno);
        exit(1);
    }
    else 
        printf("[Server] Obtaining socket descriptor successfully.\n");

    /* Fill the client socket address struct */
    addr_local.sin_family = AF_INET; // Protocol Family
    addr_local.sin_port = htons(PORT); // Port number
    addr_local.sin_addr.s_addr = INADDR_ANY; // AutoFill local address
    bzero(&(addr_local.sin_zero), 8); // Flush the rest of struct
    /* Bind a special Port */
    if( bind(sockfd, (struct sockaddr*)&addr_local, sizeof(struct sockaddr)) == -1 )
    {
        fprintf(stderr, "ERROR: Failed to bind Port. (errno = %d)\n", errno);
        exit(1);
    }
    else 
        printf("[Server] Binded tcp port %d in addr 127.0.0.1 sucessfully.\n",PORT);

    
    
    while(1) 
    {
	    int success = 0;
	    while(success == 0)
	    {
		
		/* Listen remote connect/calling */
	    if(listen(sockfd,BACKLOG) == -1)
	    {
		fprintf(stderr, "ERROR: Failed to listen Port. (errno = %d)\n", errno);
		exit(1);
	    }
	    else
		printf ("[Server] Listening the port %d successfully.\n", PORT);
		
		
		sin_size = sizeof(struct sockaddr_in);

		/* Wait a connection, and obtain a new socket file despriptor for single connection */
		if ((nsockfd = accept(sockfd, (struct sockaddr *)&addr_remote, &sin_size)) == -1) 
		{
		    fprintf(stderr, "ERROR: Obtaining new Socket Despcritor. (errno = %d)\n", errno);
		    exit(1);
		}
		else 
		    printf("[Server] Server has got connected from %s.\n", inet_ntoa(addr_remote.sin_addr));

		

		/* Send File to Client */
		//if(!fork())
		//{
		    char fs_name[8];
		    
		   strcpy(fs_name, "log_spi.dat");
		    	
		    char sdbuf[LENGTH]; // Send buffer
		    printf("[Server] Sending %s to the Client...", fs_name);
		    FILE *fs = fopen(fs_name, "r");
		    if(fs == NULL)
		    {
		        fprintf(stderr, "ERROR: File %s not found on server. (errno = %d)\n", fs_name, errno);
		        exit(1);
		    }

		    bzero(sdbuf, LENGTH); 
		    int fs_block_sz; 
		    while((fs_block_sz = fread(sdbuf, sizeof(char), LENGTH, fs))>0)
		    {
		        if(send(nsockfd, sdbuf, fs_block_sz, 0) < 0)
		        {
		            fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n", fs_name, errno);
		            exit(1);
		        }
		        bzero(sdbuf, LENGTH);
		    }
		    printf("Ok sent to client!\n");
		    success = 1;
		    fclose(fs);
		    
		    sleep(1);
		    /*close(nsockfd);
		    printf("[Server] Connection with Client closed. Server will wait now...\n");
		    while(waitpid(-1, NULL, WNOHANG) > 0);*/
		//}
	    }
    }
    close(nsockfd);
    return 0;
}
Example #25
0
int
testAPI()
{
    struct logininfo *li1;
    struct passwd *pw;
    struct hostent *he;
    struct sockaddr_in sa_in4;
    char cmdstring[256], stripline[8];
    char username[32];
#ifdef HAVE_TIME_H
    time_t t0, t1, t2, logintime, logouttime;
    char s_t0[64],s_t1[64],s_t2[64];
    char s_logintime[64], s_logouttime[64]; /* ctime() strings */
#endif

    printf("**\n** Testing the API...\n**\n");

    pw = getpwuid(getuid());
    strlcpy(username, pw->pw_name, sizeof(username));

    /* gethostname(hostname, sizeof(hostname)); */

    printf("login_alloc_entry test (no host info):\n");

    /* FIXME fake tty more effectively - this could upset some platforms */
    li1 = login_alloc_entry((int)getpid(), username, NULL, ttyname(0));
    strlcpy(li1->progname, "OpenSSH-logintest", sizeof(li1->progname));

    if (be_verbose)
        dump_logininfo(li1, "li1");

    printf("Setting host address info for 'localhost' (may call out):\n");
    if (! (he = gethostbyname("localhost"))) {
        printf("Couldn't set hostname(lookup failed)\n");
    } else {
        /* NOTE: this is messy, but typically a program wouldn't have to set
         *  any of this, a sockaddr_in* would be already prepared */
        memcpy((void *)&(sa_in4.sin_addr), (void *)&(he->h_addr_list[0][0]),
               sizeof(struct in_addr));
        login_set_addr(li1, (struct sockaddr *) &sa_in4, sizeof(sa_in4));
        strlcpy(li1->hostname, "localhost", sizeof(li1->hostname));
    }
    if (be_verbose)
        dump_logininfo(li1, "li1");

    if ((int)geteuid() != 0) {
        printf("NOT RUNNING LOGIN TESTS - you are not root!\n");
        return 1;
    }

    if (nologtest)
        return 1;

    line_stripname(stripline, li1->line, sizeof(stripline));

    printf("Performing an invalid login attempt (no type field)\n--\n");
    login_write(li1);
    printf("--\n(Should have written errors to stderr)\n");

#ifdef HAVE_TIME_H
    (void)time(&t0);
    strlcpy(s_t0, ctime(&t0), sizeof(s_t0));
    t1 = login_get_lastlog_time(getuid());
    strlcpy(s_t1, ctime(&t1), sizeof(s_t1));
    printf("Before logging in:\n\tcurrent time is %d - %s\t"
           "lastlog time is %d - %s\n",
           (int)t0, s_t0, (int)t1, s_t1);
#endif

    printf("Performing a login on line %s ", stripline);
#ifdef HAVE_TIME_H
    (void)time(&logintime);
    strlcpy(s_logintime, ctime(&logintime), sizeof(s_logintime));
    printf("at %d - %s", (int)logintime, s_logintime);
#endif
    printf("--\n");
    login_login(li1);

    snprintf(cmdstring, sizeof(cmdstring), "who | grep '%s '",
             stripline);
    system(cmdstring);

    printf("--\nPausing for %d second(s)...\n", PAUSE_BEFORE_LOGOUT);
    sleep(PAUSE_BEFORE_LOGOUT);

    printf("Performing a logout ");
#ifdef HAVE_TIME_H
    (void)time(&logouttime);
    strlcpy(s_logouttime, ctime(&logouttime), sizeof(s_logouttime));
    printf("at %d - %s", (int)logouttime, s_logouttime);
#endif
    printf("\nThe root login shown above should be gone.\n"
           "If the root login hasn't gone, but another user on the same\n"
           "pty has, this is OK - we're hacking it here, and there\n"
           "shouldn't be two users on one pty in reality...\n"
           "-- ('who' output follows)\n");
    login_logout(li1);

    system(cmdstring);
    printf("-- ('who' output ends)\n");

#ifdef HAVE_TIME_H
    t2 = login_get_lastlog_time(getuid());
    strlcpy(s_t2, ctime(&t2), sizeof(s_t2));
    printf("After logging in, lastlog time is %d - %s\n", (int)t2, s_t2);
    if (t1 == t2)
        printf("The lastlog times before and after logging in are the "
               "same.\nThis indicates that lastlog is ** NOT WORKING "
               "CORRECTLY **\n");
    else if (t0 != t2)
        /* We can be off by a second or so, even when recording works fine.
         * I'm not 100% sure why, but it's true. */
        printf("** The login time and the lastlog time differ.\n"
               "** This indicates that lastlog is either recording the "
               "wrong time,\n** or retrieving the wrong entry.\n"
               "If it's off by less than %d second(s) "
               "run the test again.\n", PAUSE_BEFORE_LOGOUT);
    else
        printf("lastlog agrees with the login time. This is a good thing.\n");

#endif

    printf("--\nThe output of 'last' shown next should have "
           "an entry for root \n  on %s for the time shown above:\n--\n",
           stripline);
    snprintf(cmdstring, sizeof(cmdstring), "last | grep '%s ' | head -3",
             stripline);
    system(cmdstring);

    printf("--\nEnd of login test.\n");

    login_free_entry(li1);

    return 1;
} /* testAPI() */
Example #26
0
void* Slave::_run_thread(void *arg){
	Slave *slave = (Slave *)arg;
	const std::vector<Bytes> *req;
	Fdevents select;
	const Fdevents::events_t *events;
	int idle = 0;
	bool reconnect = false;
	
#define RECV_TIMEOUT	200
#define MAX_RECV_IDLE	300 * 1000/RECV_TIMEOUT

	while(!slave->thread_quit){
		if(reconnect){
			reconnect = false;
			select.del(slave->link->fd());
			delete slave->link;
			slave->link = NULL;
		}
		if(!slave->connected()){
			if(slave->connect() != 1){
				usleep(100 * 1000);
			}else{
				select.set(slave->link->fd(), FDEVENT_IN, 0, NULL);
			}
			continue;
		}
		
		events = select.wait(RECV_TIMEOUT);
		if(events == NULL){
			log_fatal("events.wait error: %s", strerror(errno));
			break;
		}else if(events->empty()){
			if(idle++ >= MAX_RECV_IDLE){
				log_error("the master hasn't responsed for awhile, reconnect...");
				idle = 0;
				reconnect = true;
			}
			continue;
		}
		idle = 0;

		if(slave->link->read() <= 0){
			log_error("link.read error: %s, reconnecting to master", strerror(errno));
			reconnect = true;
			sleep(1);
			continue;
		}

		while(1){
			req = slave->link->recv();
			if(req == NULL){
				log_error("link.recv error: %s, reconnecting to master", strerror(errno));
				reconnect = true;
				sleep(1);
				break;
			}else if(req->empty()){
				break;
			}else{
				if(slave->proc(*req) == -1){
					goto err;
				}
			}
		}
	} // end while
	log_info("Slave thread quit");
	return (void *)NULL;

err:
	log_fatal("Slave thread exit unexpectedly");
	exit(0);
	return (void *)NULL;;
}
Example #27
0
VSTRING *rewrite_clnt(const char *rule, const char *addr, VSTRING *result)
{
    VSTREAM *stream;
    int     server_flags;
    int     count = 0;

    /*
     * One-entry cache.
     */
    if (last_addr == 0) {
	last_rule = vstring_alloc(10);
	last_addr = vstring_alloc(100);
	last_result = vstring_alloc(100);
    }

    /*
     * Sanity check. An address must be in externalized form. The result must
     * not clobber the input, because we may have to retransmit the query.
     */
#define STR vstring_str

    if (*addr == 0)
	addr = "";
    if (addr == STR(result))
	msg_panic("rewrite_clnt: result clobbers input");

    /*
     * Peek at the cache.
     */
    if (time((time_t *) 0) < last_expire
	&& strcmp(addr, STR(last_addr)) == 0
	&& strcmp(rule, STR(last_rule)) == 0) {
	vstring_strcpy(result, STR(last_result));
	if (msg_verbose)
	    msg_info("rewrite_clnt: cached: %s: %s -> %s",
		     rule, addr, vstring_str(result));
	return (result);
    }

    /*
     * Keep trying until we get a complete response. The rewrite service is
     * CPU bound and making the client asynchronous would just complicate the
     * code.
     */
    if (rewrite_clnt_stream == 0)
	rewrite_clnt_stream = clnt_stream_create(MAIL_CLASS_PRIVATE,
						 var_rewrite_service,
						 var_ipc_idle_limit,
						 var_ipc_ttl_limit);

    for (;;) {
	stream = clnt_stream_access(rewrite_clnt_stream);
	errno = 0;
	count += 1;
	if (attr_print(stream, ATTR_FLAG_NONE,
		       ATTR_TYPE_STR, MAIL_ATTR_REQ, REWRITE_ADDR,
		       ATTR_TYPE_STR, MAIL_ATTR_RULE, rule,
		       ATTR_TYPE_STR, MAIL_ATTR_ADDR, addr,
		       ATTR_TYPE_END) != 0
	    || vstream_fflush(stream)
	    || attr_scan(stream, ATTR_FLAG_STRICT,
			 ATTR_TYPE_INT, MAIL_ATTR_FLAGS, &server_flags,
			 ATTR_TYPE_STR, MAIL_ATTR_ADDR, result,
			 ATTR_TYPE_END) != 2) {
	    if (msg_verbose || count > 1 || (errno && errno != EPIPE && errno != ENOENT))
		msg_warn("problem talking to service %s: %m",
			 var_rewrite_service);
	} else {
	    if (msg_verbose)
		msg_info("rewrite_clnt: %s: %s -> %s",
			 rule, addr, vstring_str(result));
	    /* Server-requested disconnect. */
	    if (server_flags != 0)
		clnt_stream_recover(rewrite_clnt_stream);
	    break;
	}
	sleep(1);				/* XXX make configurable */
	clnt_stream_recover(rewrite_clnt_stream);
    }

    /*
     * Update the cache.
     */
    vstring_strcpy(last_rule, rule);
    vstring_strcpy(last_addr, addr);
    vstring_strcpy(last_result, STR(result));
    last_expire = time((time_t *) 0) + 30;	/* XXX make configurable */

    return (result);
}
/*
** Die with a fatal error
*/
void xdie(char *msg) {
	fprintf(stderr, "FATAL: %s - exiting in %d seconds\n", msg, SEC_SLEEP);
	sleep(SEC_SLEEP); /* we get respawn by init - sleep */
	exit(1);
}
Example #29
0
bool MSqlDatabase::OpenDatabase(bool skipdb)
{
    if (!m_db.isValid())
    {
        VERBOSE(VB_IMPORTANT,
              "MSqlDatabase::OpenDatabase(), db object is not valid!");
        return false;
    }

    bool connected = true;

    if (!m_db.isOpen())
    {
        if (!skipdb)
            m_dbparms = GetMythDB()->GetDatabaseParams();
        m_db.setDatabaseName(m_dbparms.dbName);
        m_db.setUserName(m_dbparms.dbUserName);
        m_db.setPassword(m_dbparms.dbPassword);
        m_db.setHostName(m_dbparms.dbHostName);

        if (m_dbparms.dbHostName.isEmpty())  // Bootstrapping without a database?
        {
            connected = true;              // Pretend to be connected
            return true;                   // to reduce errors
        }

        if (m_dbparms.dbPort)
            m_db.setPort(m_dbparms.dbPort);

        // Prefer using the faster localhost connection if using standard
        // ports, even if the user specified a DBHostName of 127.0.0.1.  This
        // will cause MySQL to use a Unix socket (on *nix) or shared memory (on
        // Windows) connection.
        if ((m_dbparms.dbPort == 0 || m_dbparms.dbPort == 3306) &&
            m_dbparms.dbHostName == "127.0.0.1")
            m_db.setHostName("localhost");

        connected = m_db.open();

        if (!connected && m_dbparms.wolEnabled)
        {
            int trycount = 0;

            while (!connected && trycount++ < m_dbparms.wolRetry)
            {
                VERBOSE(VB_GENERAL, QString(
                         "Using WOL to wakeup database server (Try %1 of %2)")
                         .arg(trycount).arg(m_dbparms.wolRetry));

                if (myth_system(m_dbparms.wolCommand) != GENERIC_EXIT_OK)
                {
                    VERBOSE(VB_IMPORTANT,
                            QString("Failed to run WOL command '%1'")
                            .arg(m_dbparms.wolCommand));
                }

                sleep(m_dbparms.wolReconnect);
                connected = m_db.open();
            }

            if (!connected)
            {
                VERBOSE(VB_IMPORTANT, "WOL failed, unable to connect to database!");
            }
        }
        if (connected)
        {
            VERBOSE(VB_GENERAL,
                    QString("Connected to database '%1' at host: %2")
                            .arg(m_db.databaseName()).arg(m_db.hostName()));

            // WriteDelayed depends on SetHaveDBConnection() and SetHaveSchema()
            // both being called with true, so order is important here.
            GetMythDB()->SetHaveDBConnection(true);
            if (!GetMythDB()->HaveSchema())
            {
                // We can't just check the count of QSqlDatabase::tables()
                // because it returns all tables visible to the user in *all*
                // databases (not just the current DB).
                bool have_schema = false;
                QString sql = "SELECT COUNT( "
                              "         INFORMATION_SCHEMA.TABLES.TABLE_NAME "
                              "       ) "
                              "  FROM INFORMATION_SCHEMA.TABLES "
                              " WHERE INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA "
                              "       = DATABASE() "
                              "   AND INFORMATION_SCHEMA.TABLES.TABLE_TYPE = "
                              "       'BASE TABLE';";
                // We can't use MSqlQuery to determine if we have a schema,
                // since it will open a new connection, which will try to check
                // if we have a schema
                QSqlQuery query = m_db.exec(sql); // don't convert to MSqlQuery
                if (query.next())
                    have_schema = query.value(0).toInt() > 1;
                GetMythDB()->SetHaveSchema(have_schema);
            }
            GetMythDB()->WriteDelayedSettings();
        }
    }

    if (!connected)
    {
        GetMythDB()->SetHaveDBConnection(false);
        VERBOSE(VB_IMPORTANT, "Unable to connect to database!");
        VERBOSE(VB_IMPORTANT, MythDB::DBErrorMessage(m_db.lastError()));
    }

    return connected;
}
Example #30
0
static void
test_read_and_write_primitives (void)
{
  int status;
  pid_t pid;
  ThriftSocket *tsocket = NULL;
  ThriftTransport *transport = NULL;
  ThriftCompactProtocol *tc = NULL;
  ThriftProtocol *protocol = NULL;
  gpointer binary = (gpointer *) TEST_STRING;
  guint32 len = strlen (TEST_STRING);
  int port = TEST_PORT;

  /* fork a server from the client */
  pid = fork ();
  assert (pid >= 0);

  if (pid == 0)
  {
    /* child listens */
    thrift_server_primitives (port);
    exit (0);
  } else {
    /* parent.  wait a bit for the socket to be created. */
    sleep (1);

    /* create a ThriftSocket */
    tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost",
                            "port", port, NULL);
    transport = THRIFT_TRANSPORT (tsocket);
    thrift_transport_open (transport, NULL);
    assert (thrift_transport_is_open (transport));

    /* create a ThriftCompactTransport */
    tc = g_object_new (THRIFT_TYPE_COMPACT_PROTOCOL, "transport",
                       tsocket, NULL);
    protocol = THRIFT_PROTOCOL (tc);
    assert (protocol != NULL);

    /* write a bunch of primitives */
    assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0);
    assert (thrift_compact_protocol_write_byte (protocol, TEST_BYTE, NULL) > 0);
    assert (thrift_compact_protocol_write_i16 (protocol, TEST_I16, NULL) > 0);
    assert (thrift_compact_protocol_write_i32 (protocol, TEST_I32, NULL) > 0);
    assert (thrift_compact_protocol_write_i64 (protocol, TEST_I64, NULL) > 0);
    assert (thrift_compact_protocol_write_i16 (protocol, TEST_NI16, NULL) > 0);
    assert (thrift_compact_protocol_write_i32 (protocol, TEST_NI32, NULL) > 0);
    assert (thrift_compact_protocol_write_i64 (protocol, TEST_NI64, NULL) > 0);
    assert (thrift_compact_protocol_write_i16 (protocol, 2, NULL) > 0);
    assert (thrift_compact_protocol_write_i32 (protocol, 2, NULL) > 0);
    assert (thrift_compact_protocol_write_i64 (protocol, 2, NULL) > 0);
    assert (thrift_compact_protocol_write_i16 (protocol, -2, NULL) > 0);
    assert (thrift_compact_protocol_write_i32 (protocol, -2, NULL) > 0);
    assert (thrift_compact_protocol_write_i64 (protocol, -2, NULL) > 0);
    assert (thrift_compact_protocol_write_double (protocol,
                                                 TEST_DOUBLE, NULL) > 0);
    assert (thrift_compact_protocol_write_string (protocol,
                                                 TEST_STRING, NULL) > 0);
    assert (thrift_compact_protocol_write_binary (protocol, binary,
                                                 len, NULL) > 0);
    assert (thrift_compact_protocol_write_binary (protocol, NULL, 0, NULL) > 0);
    assert (thrift_compact_protocol_write_binary (protocol, binary,
                                                 len, NULL) > 0);

    /* test write errors */
    transport_write_error = 1;
    assert (thrift_compact_protocol_write_byte (protocol, TEST_BYTE,
                                               NULL) == -1);
    assert (thrift_compact_protocol_write_i16 (protocol, TEST_I16, NULL) == -1);
    assert (thrift_compact_protocol_write_i32 (protocol, TEST_I32, NULL) == -1);
    assert (thrift_compact_protocol_write_i64 (protocol, TEST_I64, NULL) == -1);
    assert (thrift_compact_protocol_write_i16 (protocol, TEST_NI16,
                                               NULL) == -1);
    assert (thrift_compact_protocol_write_i32 (protocol, TEST_NI32,
                                               NULL) == -1);
    assert (thrift_compact_protocol_write_i64 (protocol, TEST_NI64,
                                               NULL) == -1);
    assert (thrift_compact_protocol_write_double (protocol, TEST_DOUBLE,
                                                 NULL) == -1);
    assert (thrift_compact_protocol_write_binary (protocol, binary, len,
                                                 NULL) == -1);
    transport_write_error = 0;

    /* test binary partial failure */
    transport_write_count = 0;
    transport_write_error_at = 1;
    assert (thrift_compact_protocol_write_binary (protocol, binary,
                                                 len, NULL) == -1);
    transport_write_error_at = -1;

    /* clean up */
    thrift_transport_close (transport, NULL);
    g_object_unref (tsocket);
    g_object_unref (protocol);
    assert (wait (&status) == pid);
    assert (status == 0);
  }
}