Ejemplo n.º 1
0
void fault_handler(void)
{
    INT32 device_id;
    INT32 status;
    INT32 Index = 0;
    static INT32 how_many_interrupt_entries = 0;

    // Get cause of interrupt
    read_from_memory(Z502InterruptDevice, &device_id);
    // Set this device as target of our query
    write_to_memory(Z502InterruptDevice, &device_id);
    // Now read the status of this device
    read_from_memory(Z502InterruptStatus, &status);

    if (ConfigArgument->show_other_output == Full)
    {
        printf("Fault_handler: Found vector type %d with value %d\n", device_id, status);
    }
    else if (ConfigArgument->show_other_output == Limited)
    {
        how_many_interrupt_entries++;
        if (how_many_interrupt_entries < 10)
        {
            printf("Fault_handler: Found vector type %d with value %d\n", device_id, status);
        }
    }

    if (status >= 1024)
    {
        printf("Invalid address: virtual page number out of range!\n");
        shut_down();
    }

    frame_scheduler(status);

    // Conditional output.
    if (ConfigArgument->show_memory_output == Full)
    {
        int idx;
        for (idx = 0; idx < NUM_OF_FRAMES; idx++)
        {
            if (shadow_pg_tbl[idx] != NULL)
            {
                MP_setup((INT32) ((*shadow_pg_tbl[idx]) & PTBL_FRAME_BITS), (INT32) process_holder[idx],
                         (INT32) (shadow_pg_tbl[idx] - address_holder[process_holder[idx]]),
                         (INT32) ((*shadow_pg_tbl[idx]) & PTBL_STATE_BITS) >> 13);
            }
        }
Ejemplo n.º 2
0
    virtual int svc()
    {
      ACE_OS::sleep (3);
      const ACE_TCHAR *msg =
        ACE_TEXT ("Message from Connection worker");
      
      ACE_TCHAR buf [BUFSIZ];
      buf[0] = ACE_OS::strlen (msg) + 1;
      ACE_OS::strcpy (&buf[1], msg);

      for (size_t i = 0; i < cli_runs; i++)
        send_work_to_server(buf);

      shut_down();

      return 0;
    }
Ejemplo n.º 3
0
  void keyboard(unsigned char key, int x, int y)
  {	  
    switch (key) 
    {
       case(27):
         shut_down(1);    
         break;
	   case(113):		  
		   keyValue = 'q';
		   break;
	   case(119):
		   keyValue = 'w';
		   break;
	   case(101):
		   keyValue = 'e';
		   break;
    }
  }
Ejemplo n.º 4
0
/*
+-----------------+------------------------------------------------------------+
| FUNCION         | main                                                       |
+-----------------+------------------------------------------------------------+
| DESCRIPCION     | Principal de la aplicacion                                 |
|                 |                                                            | 
+-----------------+------------------------------------------------------------+
*/
int main(int argc, char *argv[])
{
	/* Inicia las estructuras */
    if (init()==NOOK)
	{
		exit(1);
	}

    /* Repite el ciclo */
	while(1)
    {
		search_timeout();
    }

	/* Finaliza la aplicacion */
    shut_down();
	return OK;
}
Ejemplo n.º 5
0
EXPORTED void fatal(const char* s, int code)
{
    static int recurse_code = 0;

    if (recurse_code) {
        /* We were called recursively. Just give up */
        proc_cleanup();
        exit(recurse_code);
    }
    recurse_code = code;

    open_backups_list_close(&backupd_open_backups, 0);

    if (backupd_out) {
        prot_printf(backupd_out, "* Fatal error: %s\r\n", s);
        prot_flush(backupd_out);
    }
    syslog(LOG_ERR, "Fatal error: %s", s);
    shut_down(code);
}
Ejemplo n.º 6
0
	void keyboard(unsigned char key, int x, int y)
	{
		switch (key) 
		{
			case(27):
				shut_down(1);    
				break;
			case('4'):
				displayMode = (int)DISPLAY_TOON;
				break;
			case('1'):
				displayMode = (int)DISPLAY_DEPTH;
				break;
			case('2'):
				displayMode = (int)DISPLAY_NORMAL;
				break;
			case('3'):
				displayMode = (int)DISPLAY_DIFFUSE_SPEC;
				break;
		}
	}
Ejemplo n.º 7
0
  int svc (void)
  {
    ACE_TRACE ("Manager::svc");

    ACE_DEBUG ((LM_INFO, ACE_TEXT ("(%t) Manager started\n")));

    // Create pool.
    create_worker_pool ();

    while (!done ())
      {
        ACE_Message_Block *mb = 0;
        ACE_Time_Value tv ((long)MAX_TIMEOUT);
        tv += ACE_OS::time (0);

        // Get a message request.
        if (this->getq (mb, &tv) < 0)
          {
            shut_down ();
            break;
          }

        // Choose a worker.
        Worker *worker = 0;
        {
          ACE_GUARD_RETURN (ACE_Thread_Mutex,
                            worker_mon, this->workers_lock_, -1);

          while (this->workers_.is_empty ())
            workers_cond_.wait ();

          this->workers_.dequeue_head (worker);
        }

        // Ask the worker to do the job.
        worker->putq (mb);
      }

    return 0;
  }
Ejemplo n.º 8
0
  void keyboard(unsigned char key, int x, int y)
  {
    switch (key) 
    {
       case(27):
         shut_down(1);    
         break;
	   case('s'):
		   Toggle(SCISSOR_TEST);
		   break;
		   case('S'):
		   Toggle(SCISSOR_TEST);
		   break;
	   case ('+'):
		   break;
	   case ('b'):
		   SetBlendType(ADD);
		   break;
		   case ('B'):
		   SetBlendType(ADD);
		   break;

    }
  }
Ejemplo n.º 9
0
void init(void)
{
  srand(time(0));

  const int window_width = 800,
    window_height = 600;

  int x = NUM_POINTS_X;
  int y = NUM_POINTS_Y;
 
  if (glfwInit() != GL_TRUE)
    shut_down(1);

  // 800 x 600, 16 bit color, no depth, alpha or stencil buffers, windowed
  if (glfwOpenWindow(window_width, window_height, 5, 6, 5,
                     0, 0, 0, GLFW_WINDOW) != GL_TRUE)
    shut_down(1);
  glfwSetWindowTitle("Cloth");
 
  // set the projection matrix to a normal frustum with a max depth of 50
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  float aspect_ratio = ((float)window_height) / window_width;
  glFrustum(.5, -.5, -.5 * aspect_ratio, .5 * aspect_ratio, 1, 50);
  glMatrixMode(GL_MODELVIEW);

  //create the Point grid
  for(int i = 0; i < y; i++) {
    for(int j = 0; j < x; j++) {
      Point *p = malloc(sizeof(Point));
      p->x = j*LINK_DIST;
      p->y = i*LINK_DIST + 5;//put them off the ground a bit
      p->z = 0.0;
      p->vel_x = 0.0;
      p->vel_y = 0.0;
      p->vel_z = 0.0;
      p->prev_x = p->x;
      p->prev_y = p->y;
      p->prev_z = p->z;
      p->anchor = 0;
      int invert = y-i-1; //inverts y axis
      if(invert == 0) {
	p->anchor = 1;
      }
      point_array[(invert*x)+j] = p;
    }
  }

  //link the points together in a mesh
  int q = 0;
  for(int i = 0; i < y; i++) {
    for(int j = 0; j < x; j++) {
      int invert = y-i-1;
      
      //link upward
      if(i != 0) { //not top row
	Link *l1 = malloc(sizeof(Link));
	l1->resting_distance = LINK_DIST;//10.0/x;
	l1->tear_distance = 15*LINK_DIST;
	l1->stiffness = 1;

	l1->a = point_array[invert*x+j];
	l1->b = point_array[(invert+1)*x+j];
	l1->broken = 0;
	link_array[q] = l1;
	q++;
      }

      //link leftward (is that a word?)
      if(j != 0) { //not left edge
	Link *l2 = malloc(sizeof(Link));
	l2->resting_distance = LINK_DIST;//10.0/x;
	l2->tear_distance = 15*LINK_DIST;
	l2->stiffness = 1;
      
	l2->a = point_array[invert*x+j];
	l2->b = point_array[invert*x+j-1];
	l2->broken = 0;
	link_array[q] = l2;
	q++;
      }
    }
  }

  //make an invisible barrier for the mouse to click on
  Point *p0 = malloc(sizeof(Point));
  p0->x = -100;
  p0->y = -100;
  p0->z = 0;

  Point *p1 = malloc(sizeof(Point));
  p1->x = -100;
  p1->y = 100;
  p1->z = 0;

  Point *p2 = malloc(sizeof(Point));
  p2->x = 100;
  p2->y = 100;
  p2->z = 0;

  Point *p3 = malloc(sizeof(Point));
  p3->x = 100;
  p3->y = -100;
  p3->z = 0;

  barrier_array[0] = p0;
  barrier_array[1] = p1;
  barrier_array[2] = p2;
  barrier_array[3] = p3;
}
Ejemplo n.º 10
0
train_processing(char * trainMessage)
{
    char string[]="dest:doomtrain:stopstation:add(1111@1hostname,2222@2hostname):res1+1,res2+1,res3-1";
// char string[]="dest";
//    char *inputString = string;
    char *inputString = trainMessage;
    /* Delimeter set for State machine */
    char *delimeterColon = ":";
    char *delimeterAt = "@";
    char *delimeterAdd = "(";
    char *delimeterParenthesisClose = ")";
    char *delimeterPlus = "+";
    char *delimeterMinus = "-";
    char *delimeterComa = ",";
    char *delimeterStationNameColon = ":";
    char * token = NULL;
    char * tokenAllResourcePair = NULL;
    char * resourceName = NULL;
    char * resourceQuantity = NULL;
    char * tokenResourcePair = NULL;
    char * tokenAllConnectingStations = NULL;
    char * tokenConnectingStation = NULL;
    char * portNumber = NULL;
    char * intPortNumber;
    char * delim = NULL;
    int nextStationPortNum=0;
    int len=0;

    delim = delimeterColon;
    int state = -1;

    /* For sending messages to other station*/
    int sock_send, n_send;
    unsigned int length_send;
    struct sockaddr_in server_send, from_send;
    struct hostent *hp_send;
    char buffer_send[256];
    sock_send= socket(AF_INET, SOCK_DGRAM, 0);
    if (sock_send < 0) error("socket");
    server_send.sin_family = AF_INET;
    /*-------------------------------------------*/

    fprintf(stderr, "\n Input String = ---%s---END\n", inputString);

    while ( token = strsep(&inputString, delimeterColon)  )
    {
//      fprintf(stderr, "\ntoken---%s---Remaining stringis:---%s----", token, inputString);
        if ( -1 == state)
        {
            state++;
            if (strcmp("dest", token) ==0)
            {
                fprintf(stderr, "\n Station Name matches %s Remaining string  is : %s END\n", token, inputString);
                continue;
            }
            else
            {
                discardedTrainCountWrongStation++;
                break;
            }
        }

        if ( '\0' == token)
        {
            fprintf(stderr, "\nNothing left to END\n");
            break;
        }
        if (NULL ==inputString )
            token[strlen(token) -1] = '\0';
        fprintf(stderr, "\nTOKEN ::::;%s;:::::END\n", token);

        /* case : doomtrainstop and stop train */
        if (strcmp("doomtrain",token) ==0)
        {
            printf("\n Doomtrain encountered: Send doomtrain message to all connected stationEND\n");
            /*TODO : Doomtrain encountered: Send doomtrain message to all connected station*/
            display_all_stations(stationList);
            send_doomtrain_to_all_connected_stations(stationList);
            shut_down(0);
        }
        else if (strcmp("stopstation",token) ==0)
        {
            fprintf(stderr, "\n stoptrain encounteredEND\n");
            /* This is tricky: will do this in last, lets make everything else before this*/
            /*TODO : 1. Process this train
                     2. Send remaining message to next station
                     3. Shut down -- Done*/
            shut_down(0);
        }
        else if (strncmp("add(",token,4) ==0)
        {
//       fprintf(stderr, "\n add( encountered");    /* All Connecting Station are here*/
            tokenAllConnectingStations = strsep(&token, delimeterAdd); // must return NULL
            tokenAllConnectingStations = strsep(&token, delimeterParenthesisClose);
//        fprintf(stderr, "\n tokenAllConnectingStations %s  token %s",tokenAllConnectingStations, token);

            for (; tokenConnectingStation = strsep(&tokenAllConnectingStations, delimeterComa);)
            {
                if( NULL != strrchr(tokenConnectingStation,'@'))
                {
                    portNumber = strsep(&tokenConnectingStation, delimeterAt);

                    if( atoi(portNumber) < 0 | atoi(portNumber) > 65535)
                    {
                        discardedTrainCountFormatErrors++;
                        return;
                    }
                    stationList = insert_station(stationList, atoi(portNumber), tokenConnectingStation);
                    //      fprintf(stderr, "\n insert_station portNumber: %s hostname : %s",portNumber, tokenConnectingStation);
                }
                else
                {
                    /* Bad Port Hostname pair*/
                    //  fprintf(stderr, "In Port Hostname pair @ not foundEND\n");
                    //  exit;
                    discardedTrainCountFormatErrors++;
                    return;
                }
            }         /* End : Connecting Station are here*/
        }
        else if ( ( NULL != strrchr(token,'+')) && ( NULL != strrchr(token,'-')))
        {
            //       fprintf(stderr, "\n In Resource List %s %s",token , inputString);
            tokenAllResourcePair=token;
            /* Resources are here*/
            for (; tokenResourcePair = strsep(&tokenAllResourcePair, delimeterComa );)
            {
                //fprintf(stderr, "\n In Resource tokenAllResourcePair  %s  tokenResourcePair %s",tokenAllResourcePair , tokenResourcePair);
                if ( NULL ==  tokenResourcePair)
                {
                    fprintf(stderr, "\n No more tokenResourcePairEND\n");
                    break;
                }
                else
                    if( NULL != strrchr(tokenResourcePair,'+'))
                    {
                        resourceName = strsep(&tokenResourcePair, delimeterPlus);
                        resourceList = insert_resources(resourceList, atoi(tokenResourcePair), resourceName);
//                        fprintf(stderr, "\n                insert_resources  resourceName : %s resourceQuantity %s",resourceName, tokenResourcePair);
                    }
                    else if( NULL != strrchr(tokenResourcePair,'-'))
                    {
                        resourceName = strsep(&tokenResourcePair, delimeterMinus);
                        resourceList = insert_resources(resourceList, atoi(tokenResourcePair), resourceName);
                        //                      fprintf(stderr, "\n                insert_resources  resourceName : %s resourceQuantity %s",resourceName, tokenResourcePair);
                    }
                    else
                    {
                        /* Bad resource & quantity*/
                        discardedTrainCountFormatErrors++;
                        return;
                        fprintf(stderr, "\nIn resource pair, + or - not found= ---%s---END\n",tokenAllResourcePair);
                    }
            }         /* End : Resources are here*/
        }
        else
        {
            /* here token is next station , search this station and its port*/
            /* token + input string */
            //      fprintf(stderr, "\n $$$New Station is Token --with data in inputString$$$");
            //     fprintf(stderr, "\n Please send me to next station: token  = ---%s---",token );
            /*
                        len = strlen(token);
                        while ( len > 0 && token[len - 1] == '\n' )
                        {
                            token[len - 1] = '\0';
                            --len;
                        }
            */
            //     fprintf(stderr, "\n Pls send me2 : inputString  = ---%s---",inputString );
            //          display_all_stations(stationList);

            nextStationPortNum = search_station(stationList,token);
            //         fprintf(stderr, "\n For station name = ---%s--- , portNum = ---%d---",token, nextStationPortNum );
            if ( 0 == nextStationPortNum )
            {
                fprintf(stderr, "\n ERROR : For station name = ---%s--- , portNum = ---%d---END\n",token, nextStationPortNum );
            }
            else
            {
                /* Send message code*/
                /*TODO :  Authentication to be handled i.e. Check page 4*/
                //      fprintf(stderr, "\n\nstart of Send message code\n\n");
                hp_send = gethostbyname("localhost");
                if (0 ==hp_send) error("Unknown host");

                bcopy((char *)hp_send->h_addr,  (char *)&server_send.sin_addr, hp_send->h_length);
                server_send.sin_port = htons(nextStationPortNum);
                length_send=sizeof(struct sockaddr_in);
                bzero(buffer_send,256);
                //         char *strcat(char *dest, const char *src);
                strcat (buffer_send,token);
                if ( 0< strlen(inputString))
                    strcat (buffer_send,inputString);
                n_send=sendto(sock_send,buffer_send,
                strlen(buffer_send),0,(const struct sockaddr *)&server_send,length_send);
                if (n_send < 0)
                {
                    processedTrainCountInvalidNextStation++;
                    error("Sendto");
                }
                close(sock_send);
                //        fprintf(stderr, "\n\nEnd of Send message code\n\n");
            }

        }
    } /* first for loop ends here */
    processedTrainCountWithoutErrors++;
    state = -1;
}
Ejemplo n.º 11
0
int main (int argc, char *argv[]) {

  char input[STR_BUFF], *p, output[STR_BUFF];
  move_s move, comp_move;
  int depth = 4, comp_color;
  bool force_mode, show_board;
  double nps, elapsed;
  clock_t cpu_start = 0, cpu_end = 0;

  parse_cmdline (argc, argv);
  start_up ();
  init_hash_values ();
  init_hash_tables ();
  init_game ();
  init_book ();
  xb_mode = FALSE;
  force_mode = FALSE;
  comp_color = 0;
  show_board = TRUE;
  
  setbuf (stdout, NULL);
  setbuf (stdin, NULL);

  /* keep looping for input, and responding to it: */
  while (TRUE) {

    /* case where it's the computer's turn to move: */
    if (comp_color == white_to_move && !force_mode) {
      nodes = 0;
      qnodes = 0;
      ply = 0;

      start_time = rtime ();
      cpu_start = clock ();
      comp_move = think ();
      cpu_end = clock ();

      /* check for a game end: */
      if (((comp_color == 1 && result != white_is_mated) ||
	  (comp_color == 0 && result != black_is_mated)) &&
	  result != stalemate && result != draw_by_fifty &&
	  result != draw_by_rep) {
	
	comp_to_coord (comp_move, output);

	make (&comp_move, 0);

	/* check to see if we draw by rep/fifty after our move: */
	if (is_draw ()) {
	  result = draw_by_rep;
	}
	else if (fifty > 100) {
	  result = draw_by_fifty;
	}

	reset_piece_square ();
	/* check to see if we mate our opponent with our current move: */
	if (!result) {
	  if (xb_mode) {
	    printf ("move %s\n", output);
	  }
	  else {
	    printf ("\n%s\n", output);
	  }
	}
	else {
	  if (xb_mode) {
	    printf ("move %s\n", output);
	  }
	  else {
	    printf ("\n%s\n", output);
	  }
	  if (result == white_is_mated) {
	    printf ("0-1 {Black Mates}\n");
	  }
	  else if (result == black_is_mated) {
	    printf ("1-0 {White Mates}\n");
	  }
	  else if (result == draw_by_fifty) {
	    printf ("1/2-1/2 {Fifty move rule}\n");
	  }
	  else if (result == draw_by_rep) {
	    printf ("1/2-1/2 {3 fold repetition}\n");
	  }
	  else {
	    printf ("1/2-1/2 {Draw}\n");
	  }
	}
      }
      /* we have been mated or there is a draw: */
      else {
	if (result == white_is_mated) {
	  printf ("0-1 {Black Mates}\n");
	}
	else if (result == black_is_mated) {
	  printf ("1-0 {White Mates}\n");
	}
	else if (result == stalemate) {
	  printf ("1/2-1/2 {Stalemate}\n");
	}
	else if (result == draw_by_fifty) {
	  printf ("1/2-1/2 {Fifty move rule}\n");
	}
	else if (result == draw_by_rep) {
	  printf ("1/2-1/2 {3 fold repetition}\n");
	}
	else {
	  printf ("1/2-1/2 {Draw}\n");
	}
      }

    }

    /* get our input: */
    if (!xb_mode) {
      if (show_board && strcmp (input, "help")) {
	printf ("\n");
	display_board (stdout, 1-comp_color);
      }
      printf ("Faile> ");
      rinput (input, STR_BUFF, stdin);
    }
    else {
      rinput (input, STR_BUFF, stdin);
    }

    /* check to see if we have a move.  If it's legal, play it. */
    if (is_valid_comp (pgn_to_comp (input))) {
      /* good SAN input style move */
      move = pgn_to_comp (input);
      make (&move, 0);
      reset_piece_square ();
      if (show_board) {
	printf ("\n");
	display_board (stdout, 1-comp_color);
      }
    }
    else if (is_move (&input[0])) {
      /* good coordinate style input move */
      if (verify_coord (input, &move)) {
	make (&move, 0);
	reset_piece_square ();
	if (show_board) {
	  printf ("\n");
	  display_board (stdout, 1-comp_color);
	}
      }
      else {
	printf ("Illegal move: %s\n", input);
      }
    }
    else {

      /* make everything lower case for convenience: */
      for (p = input; *p; p++) *p = tolower (*p);

      /* command parsing: */
      if (!strcmp (input, "quit") || !strcmp (input, "exit")) {
	shut_down (EXIT_SUCCESS);
      }
      else if (!strcmp (input, "diagram") || !strcmp (input, "d")) {
	toggle_bool (&show_board);
      }
      else if (!strncmp (input, "perft", 5)) {
	sscanf (input+6, "%d", &depth);
	raw_nodes = 0;
	perft (depth);
	printf ("Raw nodes for depth %d: %ld\n", depth, raw_nodes);
      }
      else if (!strcmp (input, "new")) {
	init_game ();
	/* refresh our hash tables: */
	refresh_hash ();
	force_mode = FALSE;
	comp_color = 0;
      }
      else if (!strcmp (input, "xboard")) {
	xb_mode = TRUE;
	toggle_bool (&show_board);
	signal (SIGINT, SIG_IGN);
	printf ("\n");
      }
      else if (!strcmp (input, "nodes")) {
	printf ("Number of nodes: %li (%0.2f%% qnodes)\n", nodes,
		(float) ((float) qnodes / (float) nodes * 100.0));
      }
      else if (!strcmp (input, "nps")) {
	elapsed = (cpu_end-cpu_start)/(double) CLOCKS_PER_SEC;
	nps = (float) nodes/(float) elapsed;
	if (!elapsed)
	  printf ("NPS: N/A\n");
	else
	  printf ("NPS: %ld\n", (long int) nps);
      }
      else if (!strcmp (input, "post")) {
	toggle_bool (&post);
	if (xb_mode)
	  post = TRUE;
      }
      else if (!strcmp (input, "nopost")) {
	post = FALSE;
      }
      else if (!strcmp (input, "random")) {
	continue;
      }
      else if (!strcmp (input, "hard")) {
	continue;
      }
      else if (!strcmp (input, "easy")) {
	continue;
      }
      else if (!strcmp (input, "?")) {
	continue;
      }
      else if (!strcmp (input, "white")) {
	white_to_move = 1;
	comp_color = 0;
      }
      else if (!strcmp (input, "black")) {
	white_to_move = 0;
	comp_color = 1;
      }
      else if (!strcmp (input, "force")) {
	force_mode = TRUE;
      }
      else if (!strcmp (input, "go")) {
	comp_color = white_to_move;
	force_mode = FALSE;
      }
      else if (!strncmp (input, "time", 4)) {
	sscanf (input+5, "%ld", &time_left);
      }
      else if (!strncmp (input, "otim", 4)) {
	sscanf (input+5, "%ld", &opp_time);
      }
      else if (!strncmp (input, "level", 5)) {
	/* extract the time controls: */
	sscanf (input+6, "%ld %ld %ld", &moves_to_tc, &min_per_game, &inc);
	time_left = min_per_game*6000;
	opp_time = time_left;
	inc *= 100;
      }
      else if (!strncmp (input, "result", 6)) {
	ics_game_end ();
	init_game ();
	force_mode = FALSE;
	comp_color = 0;
      }
      else if (!strcmp (input, "help")) {
	printf ("\n%s\n\n", divider);
	printf ("diagram/d: toggle diagram display\n");
	printf ("exit/quit: terminate Faile\n");
	printf ("go:        make Faile play the side to move\n");
	printf ("new:       start a new game\n");
	printf ("level <x>: the xboard style command to set time\n");
	printf ("  <x> should be in the form: <a> <b> <c> where:\n");
	printf ("  a -> moves to TC (0 if using an ICS style TC)\n");
	printf ("  b -> minutes per game\n");
	printf ("  c -> increment in seconds\n");
	printf ("nodes:     outputs the number of nodes searched\n");
	printf ("nps:       outputs Faile's NPS in search\n");
	printf ("perft <x>: compute raw nodes to depth x\n");
	printf ("post:      toggles thinking output\n");
	printf ("xboard:    put Faile into xboard mode\n");
	printf ("\n%s\n\n", divider);
      }
      else if (!xb_mode) {
	printf ("Illegal move: %s\n", input);
      }

    }

  }

  return 0;

}
Ejemplo n.º 12
0
int check_argument_number(int argc)
{
    if(argc < 4 || argc > 6)
        shut_down(1) ;
}
Ejemplo n.º 13
0
int thttpd_main(int argc, char **argv)
#endif
{
  int num_ready;
  int cnum;
  FAR struct connect_s *conn;
  FAR httpd_conn *hc;
  httpd_sockaddr sa;
  struct timeval tv;
#ifdef CONFIG_THTTPD_DIR
  int ret;
#endif

  nvdbg("THTTPD started\n");

  /* Setup host address */

#ifdef  CONFIG_NET_IPv6
#  error "IPv6 support not yet implemented"
#else
  sa.sin_family      = AF_INET;
  sa.sin_port        = HTONS(CONFIG_THTTPD_PORT);
  sa.sin_addr.s_addr = HTONL(CONFIG_THTTPD_IPADDR);
#endif

  /* Initialize the fdwatch package to handle all of the configured
   * socket descriptors
   */

  fw = fdwatch_initialize(CONFIG_NSOCKET_DESCRIPTORS);
  if (!fw)
    {
      ndbg("fdwatch initialization failure\n");
      exit(1);
    }

  /* Switch directories again if requested */

#ifdef CONFIG_THTTPD_DATADIR
  if (chdir(CONFIG_THTTPD_DATADIR) < 0)
    {
      ndbg("chdir to %s: %d\n", CONFIG_THTTPD_DATADIR, errno);
      exit(1);
    }
#endif

  /* Initialize the timer package */

  tmr_init();

  /* Initialize the HTTP layer */

  nvdbg("Calling httpd_initialize()\n");
  hs = httpd_initialize(&sa);
  if (!hs)
    {
      ndbg("httpd_initialize() failed\n");
      exit(1);
    }

  /* Set up the occasional timer */

  if (tmr_create(NULL, occasional, JunkClientData, CONFIG_THTTPD_OCCASIONAL_MSEC * 1000L, 1) == NULL)
    {
      ndbg("tmr_create(occasional) failed\n");
      exit(1);
    }

  /* Set up the idle timer */

  if (tmr_create(NULL, idle, JunkClientData, 5 * 1000L, 1) == NULL)
    {
      ndbg("tmr_create(idle) failed\n");
      exit(1);

    }

  /* Initialize our connections table */

  connects = NEW(struct connect_s, AVAILABLE_FDS);
  if (connects == NULL)
    {
      ndbg("Out of memory allocating a struct connect_s\n");
      exit(1);
    }

  for (cnum = 0; cnum < AVAILABLE_FDS; ++cnum)
    {
      connects[cnum].conn_state  = CNST_FREE;
      connects[cnum].next        = &connects[cnum + 1];
      connects[cnum].hc          = NULL;
    }

  connects[AVAILABLE_FDS-1].next = NULL;      /* End of link list */
  free_connections               = connects;  /* Beginning of the link list */

  if (hs != NULL)
    {
      if (hs->listen_fd != -1)
        {
          fdwatch_add_fd(fw, hs->listen_fd, NULL);
        }
    }

  /* Main loop */

  nvdbg("Entering the main loop\n");
  (void)gettimeofday(&tv, NULL);
  for (;;)
    {
      /* Do the fd watch */

      num_ready = fdwatch(fw, tmr_mstimeout(&tv));
      if (num_ready < 0)
        {
          if (errno == EINTR || errno == EAGAIN)
            {
              /* Not errors... try again */

              continue;
            }

          ndbg("fdwatch failed: %d\n", errno);
          exit(1);
        }

      (void)gettimeofday(&tv, NULL);

      if (num_ready == 0)
        {
          /* No fd's are ready - run the timers */

          tmr_run(&tv);
          continue;
        }

      /* Is it a new connection? */

      if (fdwatch_check_fd(fw, hs->listen_fd))
        {
          if (!handle_newconnect(&tv, hs->listen_fd))
            {
              /* Go around the loop and do another fdwatch, rather than
               * dropping through and processing existing connections.  New
               * connections always get priority.
               */

              continue;
            }
        }

      /* Find the connections that need servicing */

      while ((conn = (struct connect_s*)fdwatch_get_next_client_data(fw)) != (struct connect_s*)-1)
        {
          if (conn)
            {
              hc = conn->hc;
              if (fdwatch_check_fd(fw, hc->conn_fd))
                {
                  nvdbg("Handle conn_state %d\n", conn->conn_state);
                  switch (conn->conn_state)
                    {
                      case CNST_READING:
                        {
                          handle_read(conn, &tv);

                          /* If a GET request was received and a file is ready to
                           * be sent, then fall through to send the file.
                           */

                          if (conn->conn_state != CNST_SENDING)
                            {
                              break;
                            }
                        }

                      case CNST_SENDING:
                        {
                          /* Send a file -- this really should be performed on a
                           * separate thread to keep the serve from locking up during
                           * the write.
                           */

                          handle_send(conn, &tv);
                        }
                        break;

                      case CNST_LINGERING:
                        {
                          /* Linger close the connection */

                          handle_linger(conn, &tv);
                        }
                        break;
                    }
                }
            }
        }
      tmr_run(&tv);
    }

  /* The main loop terminated */

  shut_down();
  ndbg("Exiting\n");
  exit(0);
}
Ejemplo n.º 14
0
int main(int argc, char* argv[])
{
    int ret;
    char buffer[256];
    signal(SIGHUP,sighup); /* set function calls */

   /*TODO: Wrap all cmdline argument checking in a function.*/
    check_argument_number(argc);
    char *name = argv[1];
    //name must be at least 1 char long
    if (strlen(name) < 1)
        shut_down(2) ;
    //second argument is the authfile
    FILE *fauth = fopen(argv[2],"r");
    //could not open authfile
    if (!fauth)
        shut_down(2) ;

    char authstr[128];
    //could not read authstring
    // fgets will read 128 chars or will stop if it getes into newline or EOF
    if (!fgets(authstr, 128, fauth))
        shut_down(2) ;

    //authstring must be more than 0 in length
    if (strlen(authstr) == 0)
        shut_down(2) ;

    //third arg is the logfile
    // a stands for appendnig
//    FILE *flog = fopen(argv[3],"a");
    flog = fopen(argv[3],"a");

    //could not open logfile
    if (!flog)
        shut_down(3) ;

    //default port is 0 (any)
    int port = 0;

    //parse optional 4th argument
    if (argc > 4)
    {
        char *end;
        port = strtol(argv[4], &end, 10);
        //the port argument is not a number
        if (*end != '\0')
            shut_down(4) ;

    }

    char *iface = NULL;
    //parse optional 5th argument
    if (argc > 5)
    {
        iface = argv[5];
    }

    /* TODO:  remove or comment these*/
    fprintf(stderr, "name:  %s\n", name);
    fprintf(stderr, "host: %s\n", iface);
    fprintf(stderr, "port:  %d\n", port);
    fprintf(stderr, "auth:  %s\n", argv[2]);
    fprintf(stderr, "log:   %s\n", argv[3]);

    int sock, length, n;
    socklen_t fromlen;
    struct sockaddr_in server;
    struct sockaddr_in from;
    char buf[1024];

    if (argc < 2)
    {
        fprintf(stderr, "ERROR, no port provided END\n");
        exit(0);
    }

    sock=socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) error("Opening socket");
    length = sizeof(server);
    bzero(&server,length);
    server.sin_family=AF_INET;
    server.sin_addr.s_addr=INADDR_ANY;
    server.sin_port=htons(port);
    if (bind(sock,(struct sockaddr *)&server,length)<0)
        error("binding");
    fromlen = sizeof(struct sockaddr_in);
    while (1)
    {
        /*TODO :  Authentication to be handled i.e. Check page 4*/
        n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,&fromlen);
        if (n < 0) error("recvfrom");
        buf[n] = '\0';
        printf("\n Recieved string = --%d---%s---END\n", n,buf);
        train_processing(buf);
        bzero(buf,256);
    }
    close(sock);
    return 0;
}
Ejemplo n.º 15
0
Archivo: AIO.c Proyecto: Nadasua/HBNews
		~AioProcessor()
		{
			shut_down();
		}
Ejemplo n.º 16
0
int main(int argc, char *argv[])
{		
	// Variables	
	// Default CSS
	char CSSFILE[12]="style.css";

	// Pointers to filenames
	char *infofilename = INFO;
	char *logfilename = LOG;
	
	// Handle arguments
	int opt;
	while ((opt=getopt_long(argc, argv, "dvhm", main_options, NULL)) != EOF)
	{
		switch (opt)
		{
		case 'h':
			help();
			exit(0);
		case 'd':
			debug();
			exit(0);
		case 'v':
			printf("%s (v%s) by MS3FGX\n", APPNAME, VERSION);
			exit(0);
			break;
		case 'm':
			strcpy(CSSFILE, "mobile.css");
			mobile = 1;
			break;
		default:
			printf("Unknown option.\n");
			exit(0);
		}
	}
	
	// Bail out if we are root, except on WRT
	#ifndef OPENWRT
	if(getuid() == 0)
	{
		syslog(LOG_ERR,"CGI module refusing to run as root!");
		printf("Server attempting to run CGI module as root, bailing out!\n");
		printf("Check your web server configuration and try again.\n");
		exit(1);
	}
	#endif

	// Read in environment variable
	// Comment this to fix compiler warning until ready to implement
	//char* env_string;
	//env_string=getenv("QUERY_STRING");

	// Print HTML head
	print_header(CSSFILE);
	//print_html(CSSFILE);
	
	// Start container div
	if (!mobile)
		puts("<div id=\"container\">\n");

	// Open files
	if ((infofile = fopen(infofilename, "r")) == NULL)
	{
		syslog(LOG_ERR,"Error while opening %s!",infofilename);
		puts("<div id=\"content\">");
		printf("Error while opening %s!\n",infofilename);
		puts("</body></html>");
		exit(1);
	}
	
	if ((logfile = fopen(logfilename, "r")) == NULL)
	{
		syslog(LOG_ERR,"Error while opening %s!",logfilename);
		puts("<div id=\"content\">");
		printf("Error while opening %s!\n",logfilename);
		puts("</body></html>");
		exit(1);
	}
	
	// Draw sidebar\topbar
	read_log();
	if (!mobile)
		SideBar();
	else
		TopBar();
	
	// Content window
	puts("<div id=\"content\">");
	
	if (device_index > 0)
	{
		// Print results
		setup_table();
		print_devices();
		puts("</table>\n");
	}
	
	// Close content, body, and HTML
	puts("</div></body></html>");
	
	// Close files and exit
	shut_down();
	return 0;
}
Ejemplo n.º 17
0
int main(int argc, char **argv)
{
    int opt;
    pid_t pid;
    char *alt_config = NULL;
    time_t runattime = 0;
    int upgrade = 0;

    if ((geteuid()) == 0 && (become_cyrus(/*is_master*/0) != 0)) {
        fatal("must run as the Cyrus user", EC_USAGE);
    }

    while ((opt = getopt(argc, argv, "C:dt:U")) != EOF) {
        switch (opt) {
        case 'C': /* alt config file */
            alt_config = optarg;
            break;
        case 'd': /* don't fork. debugging mode */
            debugmode = 1;
            break;
        case 't': /* run a single scan at this time */
            runattime = atoi(optarg);
            break;
        case 'U':
            upgrade = 1;
            break;
        default:
            fprintf(stderr, "invalid argument\n");
            exit(EC_USAGE);
            break;
        }
    }

    cyrus_init(alt_config, "calalarmd", 0, 0);

    mboxlist_init(0);
    mboxlist_open(NULL);

    quotadb_init(0);
    quotadb_open(NULL);

    annotatemore_open();

    caldav_init();

    mboxevent_init();

    if (upgrade) {
        caldav_alarm_upgrade();
        shut_down(0);
    }

    if (runattime) {
        caldav_alarm_process(runattime);
        shut_down(0);
    }

    signals_set_shutdown(shut_down);
    signals_add_handlers(0);

    /* fork unless we were given the -d option or we're running as a daemon */
    if (debugmode == 0 && !getenv("CYRUS_ISDAEMON")) {

        pid = fork();

        if (pid == -1) {
            perror("fork");
            exit(1);
        }

        if (pid != 0) { /* parent */
            exit(0);
        }
    }
    /* child */

    for (;;) {
        struct timeval start, end;
        double totaltime;
        int tosleep;

        signals_poll();

        gettimeofday(&start, 0);
        caldav_alarm_process(0);
        gettimeofday(&end, 0);

        signals_poll();

        totaltime = timesub(&start, &end);
        tosleep = 10 - (int) (totaltime + 0.5); /* round to nearest int */
        if (tosleep > 0)
            sleep(tosleep);
    }

    /* NOTREACHED */
    shut_down(1);
}
Ejemplo n.º 18
0
int
main( int argc, char** argv )
    {
    char* cp;
    struct passwd* pwd;
    uid_t uid;
    gid_t gid;
    char cwd[MAXPATHLEN];
    FILE* logfp;
    int num_ready;
    int cnum, ridx;
    connecttab* c;
    httpd_conn* hc;
    httpd_sockaddr sa4;
    httpd_sockaddr sa6;
    int gotv4, gotv6;
    struct timeval tv;

    argv0 = argv[0];

    cp = strrchr( argv0, '/' );
    if ( cp != (char*) 0 )
	++cp;
    else
	cp = argv0;
    openlog( cp, LOG_NDELAY|LOG_PID, LOG_FACILITY );

    /* Handle command-line arguments. */
    parse_args( argc, argv );

    /* Check port number. */
    if ( port <= 0 )
	{
	syslog( LOG_CRIT, "illegal port number" );
	(void) fprintf( stderr, "%s: illegal port number\n", argv0 );
	exit( 1 );
	}

    /* Read zone info now, in case we chroot(). */
    tzset();

    /* Look up hostname now, in case we chroot(). */
    lookup_hostname( &sa4, sizeof(sa4), &gotv4, &sa6, sizeof(sa6), &gotv6 );
    if ( ! ( gotv4 || gotv6 ) )
	{
	syslog( LOG_ERR, "can't find any valid address" );
	(void) fprintf( stderr, "%s: can't find any valid address\n", argv0 );
	exit( 1 );
	}

    /* Throttle file. */
    numthrottles = 0;
    maxthrottles = 0;
    throttles = (throttletab*) 0;
    if ( throttlefile != (char*) 0 )
	read_throttlefile( throttlefile );

    /* Log file. */
    if ( logfile != (char*) 0 )
	{
	if ( strcmp( logfile, "/dev/null" ) == 0 )
	    {
	    no_log = 1;
	    logfp = (FILE*) 0;
	    }
	else
	    {
	    logfp = fopen( logfile, "a" );
	    if ( logfp == (FILE*) 0 )
		{
		syslog( LOG_CRIT, "%.80s - %m", logfile );
		perror( logfile );
		exit( 1 );
		}
	    (void) fcntl( fileno( logfp ), F_SETFD, 1 );
	    }
	}
    else
	logfp = (FILE*) 0;

    /* Figure out uid/gid from user. */
    pwd = getpwnam( user );
    if ( pwd == (struct passwd*) 0 )
	{
	syslog( LOG_CRIT, "unknown user - '%.80s'", user );
	(void) fprintf( stderr, "%s: unknown user - '%s'\n", argv0, user );
	exit( 1 );
	}
    uid = pwd->pw_uid;
    gid = pwd->pw_gid;

    /* Switch directories if requested. */
    if ( dir != (char*) 0 )
	{
	if ( chdir( dir ) < 0 )
	    {
	    syslog( LOG_CRIT, "chdir - %m" );
	    perror( "chdir" );
	    exit( 1 );
	    }
	}
#ifdef USE_USER_DIR
    else if ( getuid() == 0 )
	{
	/* No explicit directory was specified, we're root, and the
	** USE_USER_DIR option is set - switch to the specified user's
	** home dir.
	*/
	if ( chdir( pwd->pw_dir ) < 0 )
	    {
	    syslog( LOG_CRIT, "chdir - %m" );
	    perror( "chdir" );
	    exit( 1 );
	    }
	}
#endif /* USE_USER_DIR */

    /* Get current directory. */
    (void) getcwd( cwd, sizeof(cwd) - 1 );
    if ( cwd[strlen( cwd ) - 1] != '/' )
	(void) strcat( cwd, "/" );

    if ( ! debug )
	{
	/* We're not going to use stdin stdout or stderr from here on, so close
	** them to save file descriptors.
	*/
	(void) fclose( stdin );
	(void) fclose( stdout );
	(void) fclose( stderr );

	/* Daemonize - make ourselves a subprocess. */
#ifdef HAVE_DAEMON
	if ( daemon( 1, 1 ) < 0 )
	    {
	    syslog( LOG_CRIT, "daemon - %m" );
	    exit( 1 );
	    }
#else /* HAVE_DAEMON */
	switch ( fork() )
	    {
	    case 0:
	    break;
	    case -1:
	    syslog( LOG_CRIT, "fork - %m" );
	    exit( 1 );
	    default:
	    exit( 0 );
	    }
#ifdef HAVE_SETSID
        (void) setsid();
#endif /* HAVE_SETSID */
#endif /* HAVE_DAEMON */
	}
    else
	{
	/* Even if we don't daemonize, we still want to disown our parent
	** process.
	*/
#ifdef HAVE_SETSID
        (void) setsid();
#endif /* HAVE_SETSID */
	}

    if ( pidfile != (char*) 0 )
	{
	/* Write the PID file. */
	FILE* pidfp = fopen( pidfile, "w" );
	if ( pidfp == (FILE*) 0 )
	    {
	    syslog( LOG_CRIT, "%.80s - %m", pidfile );
	    exit( 1 );
	    }
	(void) fprintf( pidfp, "%d\n", (int) getpid() );
	(void) fclose( pidfp );
	}

    /* Chroot if requested. */
    if ( do_chroot )
	{
	if ( chroot( cwd ) < 0 )
	    {
	    syslog( LOG_CRIT, "chroot - %m" );
	    perror( "chroot" );
	    exit( 1 );
	    }
	(void) strcpy( cwd, "/" );
	/* Always chdir to / after a chroot. */
	if ( chdir( cwd ) < 0 )
	    {
	    syslog( LOG_CRIT, "chroot chdir - %m" );
	    perror( "chroot chdir" );
	    exit( 1 );
	    }
	}

    /* Set up to catch signals. */
    (void) signal( SIGTERM, handle_term );
    (void) signal( SIGINT, handle_term );
    (void) signal( SIGPIPE, SIG_IGN );          /* get EPIPE instead */
    (void) signal( SIGHUP, handle_hup );
    got_usr1 = 0;
    (void) signal( SIGUSR1, handle_usr1 );
    (void) signal( SIGUSR2, handle_usr2 );

    /* Initialize the timer package. */
    tmr_init();

    /* Initialize the HTTP layer.  Got to do this before giving up root,
    ** so that we can bind to a privileged port.
    */
    hs = httpd_initialize(
	hostname,
	gotv4 ? &sa4 : (httpd_sockaddr*) 0, gotv6 ? &sa6 : (httpd_sockaddr*) 0,
	port, cgi_pattern, charset, cwd, no_log, logfp, no_symlink, do_vhost,
	do_global_passwd, url_pattern, local_pattern, no_empty_referers );
    if ( hs == (httpd_server*) 0 )
	exit( 1 );

    /* Set up the occasional timer. */
    if ( tmr_create( (struct timeval*) 0, occasional, JunkClientData, OCCASIONAL_TIME * 1000L, 1 ) == (Timer*) 0 )
	{
	syslog( LOG_CRIT, "tmr_create(occasional) failed" );
	exit( 1 );
	}
    if ( numthrottles > 0 )
	{
	/* Set up the throttles timer. */
	if ( tmr_create( (struct timeval*) 0, update_throttles, JunkClientData, THROTTLE_TIME * 1000L, 1 ) == (Timer*) 0 )
	    {
	    syslog( LOG_CRIT, "tmr_create(update_throttles) failed" );
	    exit( 1 );
	    }
	}
#ifdef STATS_TIME
    /* Set up the stats timer. */
    if ( tmr_create( (struct timeval*) 0, show_stats, JunkClientData, STATS_TIME * 1000L, 1 ) == (Timer*) 0 )
	{
	syslog( LOG_CRIT, "tmr_create(show_stats) failed" );
	exit( 1 );
	}
#endif /* STATS_TIME */
    start_time = stats_time = time( (time_t*) 0 );
    stats_connections = stats_bytes = 0L;
    stats_simultaneous = 0;

    /* If we're root, try to become someone else. */
    if ( getuid() == 0 )
	{
	/* Set aux groups to null. */
	if ( setgroups( 0, (const gid_t*) 0 ) < 0 )
	    {
	    syslog( LOG_CRIT, "setgroups - %m" );
	    exit( 1 );
	    }
	/* Set primary group. */
	if ( setgid( gid ) < 0 )
	    {
	    syslog( LOG_CRIT, "setgid - %m" );
	    exit( 1 );
	    }
	/* Try setting aux groups correctly - not critical if this fails. */
	if ( initgroups( user, gid ) < 0 )
	    syslog( LOG_WARNING, "initgroups - %m" );
#ifdef HAVE_SETLOGIN
	/* Set login name. */
        (void) setlogin( user );
#endif /* HAVE_SETLOGIN */
	/* Set uid. */
	if ( setuid( uid ) < 0 )
	    {
	    syslog( LOG_CRIT, "setuid - %m" );
	    exit( 1 );
	    }
	/* Check for unnecessary security exposure. */
	if ( ! do_chroot )
	    syslog(
		LOG_CRIT,
		"started as root without requesting chroot(), warning only" );
	}

    /* Initialize our connections table. */
    maxconnects = fdwatch_get_nfiles();
    if ( maxconnects < 0 )
	{
	syslog( LOG_CRIT, "fdwatch initialization failure" );
	exit( 1 );
	}
    maxconnects -= SPARE_FDS;
    connects = NEW( connecttab, maxconnects );
    if ( connects == (connecttab*) 0 )
	{
	syslog( LOG_CRIT, "out of memory allocating a connecttab" );
	exit( 1 );
	}
    for ( cnum = 0; cnum < maxconnects; ++cnum )
	{
	connects[cnum].conn_state = CNST_FREE;
	connects[cnum].hc = (httpd_conn*) 0;
	}
    numconnects = 0;
    httpd_conn_count = 0;

    if ( hs != (httpd_server*) 0 )
	{
	if ( hs->listen4_fd != -1 )
	    fdwatch_add_fd( hs->listen4_fd, (void*) 0, FDW_READ );
	if ( hs->listen6_fd != -1 )
	    fdwatch_add_fd( hs->listen6_fd, (void*) 0, FDW_READ );
	}

    /* Main loop. */
    (void) gettimeofday( &tv, (struct timezone*) 0 );
    while ( ( ! terminate ) || numconnects > 0 )
	{
	/* Do the fd watch. */
	num_ready = fdwatch( tmr_mstimeout( &tv ) );
	if ( num_ready < 0 )
	    {
	    if ( errno == EINTR )
		continue;       /* try again */
	    syslog( LOG_ERR, "fdwatch - %m" );
	    exit( 1 );
	    }
	(void) gettimeofday( &tv, (struct timezone*) 0 );
	if ( num_ready == 0 )
	    {
	    /* No fd's are ready - run the timers. */
	    tmr_run( &tv );
	    continue;
	    }

	/* Is it a new connection? */
	if ( hs != (httpd_server*) 0 && hs->listen6_fd != -1 && 
	     fdwatch_check_fd( hs->listen6_fd ) )
	    {
	    if ( handle_newconnect( &tv, hs->listen6_fd ) )
		/* Go around the loop and do another fdwatch, rather than
		** dropping through and processing existing connections.
		** New connections always get priority.
		*/
		continue;
	    }
	if ( hs != (httpd_server*) 0 && hs->listen4_fd != -1 && 
	     fdwatch_check_fd( hs->listen4_fd ) )
	    {
	    if ( handle_newconnect( &tv, hs->listen4_fd ) )
		/* Go around the loop and do another fdwatch, rather than
		** dropping through and processing existing connections.
		** New connections always get priority.
		*/
		continue;
	    }

	/* Find the connections that need servicing. */
	for ( ridx = 0; ridx < num_ready; ++ridx )
	    {
	    c = (connecttab*) fdwatch_get_client_data( ridx );
	    if ( c == (connecttab*) 0 )
		continue;
	    hc = c->hc;
	    if ( c->conn_state == CNST_READING &&
		 fdwatch_check_fd( hc->conn_fd ) )
		handle_read( c, &tv );
	    else if ( c->conn_state == CNST_SENDING &&
		 fdwatch_check_fd( hc->conn_fd ) )
		handle_send( c, &tv );
	    else if ( c->conn_state == CNST_LINGERING &&
		 fdwatch_check_fd( hc->conn_fd ) )
		handle_linger( c, &tv );
	    }
	tmr_run( &tv );

	if ( got_usr1 && ! terminate )
	    {
	    terminate = 1;
	    if ( hs != (httpd_server*) 0 )
		{
		httpd_terminate( hs );
		hs = (httpd_server*) 0;
		}
	    }
	}

    /* The main loop terminated. */
    shut_down();
    syslog( LOG_NOTICE, "exiting" );
    closelog();
    exit( 0 );
    }
Ejemplo n.º 19
0
int main(void)
{
  init();
  main_loop();
  shut_down(0);
}
Ejemplo n.º 20
0
/**
 * Write data into the specific position indicated by the disk id and sector id.
 * @param disk_id: Indicates which disk to write to. 
 * @param sector: Indicates which sector to write to. 
 * @param buffer: The data needs to be written.
 */
void os_disk_write(INT32 disk_id, INT32 sector, char *buffer)
{
    INT32 status;
    int result;

    /* Do the hardware call to put data on disk */
    write_to_memory(Z502DiskSetID, &disk_id);
    read_from_memory(Z502DiskStatus, &status);

    // If the disk is free, indicates success in writing.
    if (status == DEVICE_FREE)
    {
        write_to_memory(Z502DiskSetSector, &sector);
        write_to_memory(Z502DiskSetBuffer, (INT32 *) buffer);
        status = 1; // Specify a write
        write_to_memory(Z502DiskSetAction, &status);
        status = 0; // Must be set to 0
        write_to_memory(Z502DiskStart, &status);

        CurrentPCB->disk_id = disk_id;
        CurrentPCB->operation = -1;

        get_data_lock(SUSPEND_QUEUE_LOCK);
        result = add_to_suspend_queue(CurrentPCB);
        release_data_lock(SUSPEND_QUEUE_LOCK);
        if (result)
        {
            CurrentPCB->suspend = TRUE;
            print_scheduling_info(ACTION_NAME_SUSPEND, CurrentPCB, NORMAL_INFO);
        }
        else
        {
            error_message("add_to_suspend_queue");
            shut_down();
        }
        os_dispatcher();
        return;
    }
    // If the disk is busy, indicates failure in writing.
    else if (status == DEVICE_IN_USE)
    {
        DISK_DATA *disk_data;
        disk_data = (DISK_DATA *) calloc(1, sizeof ( DISK_DATA));

        CurrentPCB->disk_id = disk_id;
        CurrentPCB->operation = WRITE_ONE;
        CurrentPCB->disk = disk_id;
        CurrentPCB->sector = sector;
        memcpy(disk_data, buffer, sizeof (DISK_DATA));
        CurrentPCB->disk_data = disk_data;
        result = add_to_suspend_queue(CurrentPCB);
        if (result)
        {
            CurrentPCB->suspend = TRUE;
            print_scheduling_info(ACTION_NAME_WRITE, CurrentPCB, NORMAL_INFO);
        }
        else
        {
            error_message("add_to_suspend_queue");
            shut_down();
        }
        os_dispatcher();
        return;
    }
    else
    {
        printf("some error not processed in os_disk_write!\n");
    }
}
Ejemplo n.º 21
0
int main(int argc, char *argv[])
{
	// Handle signals
	signal(SIGINT,shut_down);
	signal(SIGHUP,shut_down);
	signal(SIGTERM,shut_down);
	signal(SIGQUIT,shut_down);

	// HCI device number, MAC struct
	int device = 0;
	bdaddr_t bdaddr;
	bacpy(&bdaddr, BDADDR_ANY);

	// Time to scan. Scan time is roughly 1.28 seconds * scan_window
	// Originally this was always 8, now we adjust based on device:
	#ifdef OPENWRT
	int scan_window = 8;
	#elif PWNPLUG
	int scan_window = 5;
	#else
	int scan_window = 3;
	#endif

	// Maximum number of devices per scan
	int max_results = 255;
	int num_results;

	// Device cache and index
	int cache_index = 0;

	// HCI cache setting
	int flags = IREQ_CACHE_FLUSH;

	// Strings to hold MAC and name
	char addr[19] = {0};
	char addr_buff[19] = {0};

	// String for time
	char cur_time[20];

	// Process ID read from PID file
	int ext_pid;

	// Pointers to filenames
	char *infofilename = LIVE_INF;

	// Change default filename based on date
	char OUT_FILE[1000] = OUT_PATH;
	strncat(OUT_FILE, file_timestamp(),sizeof(OUT_FILE)-strlen(OUT_FILE)-1);
	char *outfilename = OUT_FILE;

	// Mode to open output file in
	char *filemode = "a+";

	// Output buffer
	char outbuffer[500];

	// Buffer for data from the second loop
	char exitbuffer[500];

	// Misc Variables
	int i, ri, opt;

	// Record numbner of BlueZ errors
	int error_count = 0;

	// Current epoch time
	long long int epoch;

	// Kernel version info
	struct utsname sysinfo;
	uname(&sysinfo);

	while ((opt=getopt_long(argc,argv,"+o:i:r:a:w:vxctghldbfenksmq", main_options, NULL)) != EOF)
	{
		switch (opt)
		{
		case 'i':
			if (!strncasecmp(optarg, "hci", 3))
				hci_devba(atoi(optarg + 3), &bdaddr);
			else
				str2ba(optarg, &bdaddr);
			break;
		case 'o':
			outfilename = strdup(optarg);
			break;
		case 'r':
			config.retry_count = atoi(optarg);
			break;
		case 'a':
			config.amnesia = atoi(optarg);
			break;
		case 'w':
			config.scan_window = round((atoi(optarg) / 1.28));
			break;
		case 'c':
			config.showclass = 1;
			break;
		case 'e':
			config.encode = 1;
			break;
		case 'f':
			config.friendlyclass = 1;
			break;
		case 'v':
			config.verbose = 1;
			break;
		case 'g':
			config.status = 1;
			break;
		case 't':
			config.showtime = 1;
			break;
		case 's':
			config.syslogonly = 1;
			break;
		case 'x':
			config.obfuscate = 1;
			break;
		case 'q':
			config.quiet = 1;
			break;
		case 'l':
			if(!LIVEMODE)
			{
				printf("Live mode has been disabled in this build. See documentation.\n");
				exit(0);
			}
			else
				config.bluelive = 1;
			break;
		case 'b':
			config.bluepropro = 1;
			break;
		case 'd':
			config.daemon = 1;
			break;
		case 'n':
			config.getname = 1;
			break;
		case 'm':
			if(!OUILOOKUP)
			{
				printf("Manufacturer lookups have been disabled in this build. See documentation.\n");
				exit(0);
			}
			else
				config.getmanufacturer = 1;
			break;
		case 'h':
			help();
			exit(0);
		case 'k':
			// Read PID from file into variable
			ext_pid = read_pid();
			if (ext_pid != 0)
			{
				printf("Killing Bluelog process with PID %i...",ext_pid);
				if(kill(ext_pid,15) != 0)
				{
					printf("ERROR!\n");
					printf("Unable to kill Bluelog process. Check permissions.\n");
					exit(1);
				}
				else
					printf("OK.\n");

				// Delete PID file
				unlink(PID_FILE);
			}
			else
				printf("No running Bluelog process found.\n");

			exit(0);
		default:
			printf("Unknown option. Use -h for help, or see README.\n");
			exit(1);
		}
	}

	// See if there is already a process running
	if (read_pid() != 0)
	{
		printf("Another instance of Bluelog is already running!\n");
		printf("Use the -k option to kill a running Bluelog process.\n");
		exit(1);
	}

	// Load config from file if no options given on command line
	if(cfg_exists() && argc == 1)
	{
		if (cfg_read() != 0)
		{
			printf("Error opening config file!\n");
			exit(1);
		}
		// Put interface into BT struct
		hci_devba(config.hci_device, &bdaddr);
	}

	// Perform sanity checks on varibles
	cfg_check();

	// Setup libmackerel
	mac_init();

	// Boilerplate
	if (!config.quiet)
	{
		printf("%s (v%s%s) by MS3FGX\n", APPNAME, VERSION, VER_MOD);
		#if defined OPENWRT || PWNPLUG
			printf("----");
		#endif
		printf("---------------------------\n");
	}

	// Show notification we loaded config from file
	if(cfg_exists() && argc == 1 && !config.quiet)
		printf("Config loaded from: %s\n", CFG_FILE);

	// Init Hardware
	ba2str(&bdaddr, config.addr);
	if (!strcmp(config.addr, "00:00:00:00:00:00"))
	{
		if (!config.quiet)
			printf("Autodetecting device...");
		device = hci_get_route(NULL);
		// Put autodetected device MAC into addr
		hci_devba(device, &bdaddr);
		ba2str(&bdaddr, config.addr);
	}
	else
	{
		if (!config.quiet)
			printf("Initializing device...");
		device = hci_devid(config.addr);
	}

	// Open device and catch errors
	config.bt_socket = hci_open_dev(device);
	if (device < 0 || config.bt_socket < 0)
	{
		// Failed to open device, that can't be good
		printf("\n");
		printf("Error initializing Bluetooth device!\n");
		exit(1);
	}

	// If we get here the device should be online.
	if (!config.quiet)
		printf("OK\n");

	// Status message for BPP
	if (!config.quiet)
		if (config.bluepropro)
			printf("Output formatted for BlueProPro.\n"
				   "More Info: www.hackfromacave.com\n");

	// Open socket
	if (config.udponly)
		open_udp_socket();

	// Open output file, unless in networking mode
	if (!config.syslogonly && !config.udponly)
	{
		if (config.bluelive)
		{
			// Change location of output file
			outfilename = LIVE_OUT;
			filemode = "w";
			if (!config.quiet)
				printf("Starting Bluelog Live...\n");
		}
		if (!config.quiet)
			printf("Opening output file: %s...", outfilename);
		if ((outfile = fopen(outfilename, filemode)) == NULL)
		{
			printf("\n");
			printf("Error opening output file!\n");
			exit(1);
		}
		if (!config.quiet)
			printf("OK\n");
	}
	else
		if (!config.quiet)
			printf("Network mode enabled, not creating log file.\n");

	// Open status file
	if (config.bluelive)
	{
		if (!config.quiet)
			printf("Opening info file: %s...", infofilename);
		if ((infofile = fopen(infofilename,"w")) == NULL)
		{
			printf("\n");
			printf("Error opening info file!\n");
			exit(1);
		}
		if (!config.quiet)
			printf("OK\n");
	}

	// Write PID file
	if (!config.daemon)
		write_pid(getpid());

	// Get and print time to console and file
	strcpy(cur_time, get_localtime());

	if (!config.daemon)
		printf("Scan started at [%s] on %s\n", cur_time, config.addr);

	if (config.showtime && (outfile != NULL))
	{
		fprintf(outfile,"[%s] Scan started on %s\n", cur_time, config.addr);
		// Make sure this gets written out
		fflush(outfile);
	}

	// Write info file for Bluelog Live
	if (config.bluelive)
	{
		fprintf(infofile,"<div class=\"sideitem\">%s Version: %s%s</div>\n", APPNAME, VERSION, VER_MOD);
		fprintf(infofile,"<div class=\"sideitem\">Device: %s</div>\n", config.addr);
		fprintf(infofile,"<div class=\"sideitem\">Started: %s</div>\n", cur_time);

		// Think we are done with you now
		fclose(infofile);
	}

	// Log success to this point
	syslog(LOG_INFO,"Init OK!");

	// Daemon switch
	if (config.daemon)
		daemonize();
	else
		if (!config.quiet)
			#if defined PWNPAD
			printf("Close this window to end scan.\n");
			#else
			printf("Hit Ctrl+C to end scan.\n");
			#endif

	// Init result struct
	results = (inquiry_info*)malloc(max_results * sizeof(inquiry_info));

	// Start scan, be careful with this infinite loop...
	for(;;)
	{
		// Flush results buffer
		memset(results, '\0', max_results * sizeof(inquiry_info));

		// Scan and return number of results
		num_results = hci_inquiry(device, scan_window, max_results, NULL, &results, flags);

		// A negative number here means an error during scan
		if(num_results < 0)
		{
			// Increment error count
			error_count++;

			// Ignore occasional errors on Pwn Plug and OpenWRT
			#if !defined PWNPLUG || OPENWRT
			// All other platforms, print error and bail out
			syslog(LOG_ERR,"Received error from BlueZ!");
			printf("Scan failed!\n");
			// Check for kernel 3.0.x
			if (!strncmp("3.0.",sysinfo.release,4))
			{
				printf("\n");
				printf("-----------------------------------------------------\n");
				printf("Device scanning failed, and you are running a 3.0.x\n");
				printf("Linux kernel. This failure is probably due to the\n");
				printf("following kernel bug:\n");
				printf("\n");
				printf("http://marc.info/?l=linux-kernel&m=131629118406044\n");
				printf("\n");
				printf("You will need to upgrade your kernel to at least the\n");
				printf("the 3.1 series to continue.\n");
				printf("-----------------------------------------------------\n");

			}
			shut_down(1);
			#else
			// Exit on back to back errors
			if (error_count > 5)
			{
				printf("Scan failed!\n");
				syslog(LOG_ERR,"BlueZ not responding, unrecoverable!");
				shut_down(1);
			}

			// Otherwise, throttle back a bit, might help
			sleep(1);
			#endif
		}
		else
		{
			// Clear error counter
			error_count = 0;
		}

		// Check if we need to reset device cache
		if ((cache_index + num_results) >= MAX_DEV)
		{
			syslog(LOG_INFO,"Resetting device cache...");
			memset(dev_cache, 0, sizeof(dev_cache));
			cache_index = 0;
		}



		// Loop through results
		for (i = 0; i < num_results; i++)
		{
			// Return current MAC from struct
			ba2str(&(results+i)->bdaddr, addr);

			// Compare to device cache
			for (ri = 0; ri <= cache_index; ri++)
			{
				// Determine if device is already logged
				if (strcmp (addr, dev_cache[ri].priv_addr) == 0)
				{
					// This device has been seen before

					// Increment seen count, update printed time
					dev_cache[ri].seen++;
					strcpy(dev_cache[ri].time, get_localtime());
					dev_cache[ri].missing_count = 0;

					// If we don't have a name, query again
					if ((dev_cache[ri].print == 3) && (dev_cache[ri].seen > config.retry_count))
					{
						syslog(LOG_INFO,"Unable to find name for %s!", addr);
						dev_cache[ri].print = 1;
					}
					else if ((dev_cache[ri].print == 3) && (dev_cache[ri].seen < config.retry_count))
					{
						// Query name
						strcpy(dev_cache[ri].name, namequery(&(results+i)->bdaddr));

						// Did we get one?
						if (strcmp (dev_cache[ri].name, "VOID") != 0)
						{
							syslog(LOG_INFO,"Name retry for %s successful!", addr);
							// Force print
							dev_cache[ri].print = 1;
						}
						else
							syslog(LOG_INFO,"Name retry %i for %s failed!",dev_cache[ri].seen, addr);
					}

					// Amnesia mode
					if (config.amnesia >= 0)
					{
						// Find current epoch time
						epoch = time(NULL);
						if ((epoch - dev_cache[ri].epoch) >= (config.amnesia * 60))
						{
							// Update epoch time
							dev_cache[ri].epoch = epoch;
							// Set device to print
							dev_cache[ri].print = 1;
						}
					}

					// This device is seen before, but has been away
					if (strcmp (dev_cache[ri].status, "gone") == 0)
					{
						dev_cache[ri].print = 1;
						strcpy(dev_cache[ri].status, "returned");
					}

					// Unless we need to get printed, move to next result
					if (dev_cache[ri].print != 1)
						break;
				}
				else if (strcmp (dev_cache[ri].addr, "") == 0)
				{
					// Write new device MAC (visible and internal use)
					strcpy(dev_cache[ri].addr, addr);
					strcpy(dev_cache[ri].priv_addr, addr);

					// Query for name
					if (config.getname)
						strcpy(dev_cache[ri].name, namequery(&(results+i)->bdaddr));
					else
						strcpy(dev_cache[ri].name, "IGNORED");

					// Get time found
					strcpy(dev_cache[ri].time, get_localtime());
					dev_cache[ri].epoch = time(NULL);

					// Class info
					dev_cache[ri].flags = (results+i)->dev_class[2];
					dev_cache[ri].major_class = (results+i)->dev_class[1];
					dev_cache[ri].minor_class = (results+i)->dev_class[0];

					// Init misc variables
					dev_cache[ri].seen = 1;
					dev_cache[ri].missing_count = 0;
					strcpy(dev_cache[ri].status, "new");

					// Increment index
					cache_index++;

					// If we have a device name, get printed
					if (strcmp (dev_cache[ri].name, "VOID") != 0)
						dev_cache[ri].print = 1;
					else
					{
						// Found with no name.
						// Print message to syslog, prevent printing, and move on
						syslog(LOG_INFO,"Device %s discovered with no name, will retry", dev_cache[ri].addr);
						dev_cache[ri].print = 3;
						break;
					}
				}

				// Ready to print?
				if (dev_cache[ri].print == 1)
				{
					// Encode MAC
					if (config.encode || config.obfuscate)
					{
						// Clear buffer
						memset(addr_buff, '\0', sizeof(addr_buff));

						if (config.obfuscate)
							strcpy(addr_buff, mac_obfuscate(dev_cache[ri].priv_addr));

						if (config.encode)
							strcpy(addr_buff, mac_encode(dev_cache[ri].priv_addr));

						// Copy to cache
						strcpy(dev_cache[ri].addr, addr_buff);
					}

					// Print everything to console if verbose is on, optionally friendly class info
					if (config.verbose)
					{
						if (config.friendlyclass)
						{
							printf("[%s] %s,%s,%s,(%s) - %s\n",\
								dev_cache[ri].time, dev_cache[ri].addr,\
								dev_cache[ri].name, device_class(dev_cache[ri].major_class,\
								dev_cache[ri].minor_class), device_capability(dev_cache[ri].flags), dev_cache[ri].status);
						}
						else
						{
							printf("[%s] %s,%s,0x%02x%02x%02x - %s\n",\
								dev_cache[ri].time, dev_cache[ri].addr,\
								dev_cache[ri].name, dev_cache[ri].flags,\
								dev_cache[ri].major_class, dev_cache[ri].minor_class, dev_cache[ri].status);
						}
					}

					if (config.bluelive)
					{
						// Write result with live function
						live_entry(ri);
					}
					else if (config.bluepropro)
					{
						// Set output format for BlueProPro
						fprintf(outfile,"%s", dev_cache[ri].addr);
						fprintf(outfile,",0x%02x%02x%02x", dev_cache[ri].flags,\
						dev_cache[ri].major_class, dev_cache[ri].minor_class);
						fprintf(outfile,",%s\n", dev_cache[ri].name);
					}
					else
					{
						// Flush buffer
						memset(outbuffer, 0, sizeof(outbuffer));

						// Print time first if enabled
						if (config.showtime)
							sprintf(outbuffer,"[%s],", dev_cache[ri].time);

						// Always output MAC
						sprintf(outbuffer+strlen(outbuffer),"%s", dev_cache[ri].addr);

						// Optionally output class
						if (config.showclass)
							sprintf(outbuffer+strlen(outbuffer),",0x%02x%02x%02x", dev_cache[ri].flags,\
							dev_cache[ri].major_class, dev_cache[ri].minor_class);

						// "Friendly" version of class info
						if (config.friendlyclass)
							sprintf(outbuffer+strlen(outbuffer),",%s,(%s)",\
							device_class(dev_cache[ri].major_class, dev_cache[ri].minor_class),\
							device_capability(dev_cache[ri].flags));

						// Get manufacturer
						if (config.getmanufacturer)
							sprintf(outbuffer+strlen(outbuffer),",%s", mac_get_vendor(dev_cache[ri].priv_addr));

						// Append the name
						if (config.getname)
							sprintf(outbuffer+strlen(outbuffer),",%s", dev_cache[ri].name);

						// Append the status
						if (config.status)
							sprintf(outbuffer+strlen(outbuffer)," - %s", dev_cache[ri].status);

						// Send buffer, else file. File needs newline
						if (config.syslogonly)
							syslog(LOG_INFO,"%s", outbuffer);
						else if (config.udponly)
						{
							// Append newline to socket, kind of hacky
							sprintf(outbuffer+strlen(outbuffer),"\n");
							send_udp_msg(outbuffer);
						}
						else
							fprintf(outfile,"%s\n",outbuffer);
					}
					dev_cache[ri].print = 0;
					break;
				}
				// If we make it this far, it means we will check next stored device
			}

			// If there's a file open, write changes
			if (outfile != NULL)
				fflush(outfile);
		}

		// Now check if any devices are missing

		// Loop through the cache
		for (ri = 0; ri < cache_index; ri++)
		{

			for (i = 0; i <= num_results; i++)
			{
				// Return current MAC from struct
				ba2str(&(results+i)->bdaddr, addr);

				// Determine if device still present
				if (strcmp (addr, dev_cache[ri].priv_addr) == 0)
				{

					break;
				}

				// Device not found.
				if (i == num_results)
				{
					// The device is missing but not marked as gone -> it has just disappeared
					if (strcmp(dev_cache[ri].status, "gone") != 0)
					{
						// Devices aren't present every time. Wait a while before marking it gone
						if (dev_cache[ri].missing_count < 10)
						{
							dev_cache[ri].missing_count++;
						}
						else
						// It's really gone :(
						{
							strcpy(dev_cache[ri].status,"gone");

							// Print to console
							if (config.verbose) {
								printf("[%s] %s,%s - %s\n",\
										dev_cache[ri].time, dev_cache[ri].addr,\
										dev_cache[ri].name, dev_cache[ri].status);

							}

							// Flush buffer
							memset(exitbuffer, 0, sizeof(exitbuffer));

							// Print time first if enabled
							if (config.showtime)
								sprintf(exitbuffer,"[%s],", dev_cache[ri].time);

							// Always output MAC
							sprintf(exitbuffer+strlen(exitbuffer),"%s", dev_cache[ri].addr);

							// Append the name
							if (config.getname)
								sprintf(exitbuffer+strlen(exitbuffer),",%s", dev_cache[ri].name);

							// Append the status
							if (config.status)
								sprintf(exitbuffer+strlen(exitbuffer)," - %s", dev_cache[ri].status);

							// Send buffer, else file. File needs newline
							if (config.syslogonly)
								syslog(LOG_INFO,"%s", exitbuffer);
							else if (config.udponly)
							{
								// Append newline to socket, kind of hacky
								sprintf(exitbuffer+strlen(exitbuffer),"\n");
								send_udp_msg(exitbuffer);
							}
							else
								fprintf(outfile,"%s\n",exitbuffer);

							// If there's a file open, write changes
							if (outfile != NULL)
								fflush(outfile);

						}
					}

				}

			}

		}



	}
	// If we get here, shut down
	shut_down(0);
	// STFU
	return (1);
}
Ejemplo n.º 22
0
static future_t *start_up(void) {
  LOG_INFO(LOG_TAG, "%s", __func__);

  // The host is only allowed to send at most one command initially,
  // as per the Bluetooth spec, Volume 2, Part E, 4.4 (Command Flow Control)
  // This value can change when you get a command complete or command status event.
  command_credits = 1;
  firmware_is_configured = false;

  pthread_mutex_init(&commands_pending_response_lock, NULL);

  // TODO(armansito): cutils/properties.h is only being used to pull-in runtime
  // settings on Android. Remove this conditional include once we have a generic
  // way to obtain system properties. For now, always use the default timeout on
  // non-Android builds.
  period_ms_t startup_timeout_ms = DEFAULT_STARTUP_TIMEOUT_MS;

#if !defined(OS_GENERIC)
  // Grab the override startup timeout ms, if present.
  char timeout_prop[PROPERTY_VALUE_MAX];
  if (!property_get("bluetooth.enable_timeout_ms", timeout_prop, STRING_VALUE_OF(DEFAULT_STARTUP_TIMEOUT_MS))
      || (startup_timeout_ms = atoi(timeout_prop)) < 100)
    startup_timeout_ms = DEFAULT_STARTUP_TIMEOUT_MS;
#endif  // !defined(OS_GENERIC)

  startup_timer = non_repeating_timer_new(startup_timeout_ms, startup_timer_expired, NULL);
  if (!startup_timer) {
    LOG_ERROR(LOG_TAG, "%s unable to create startup timer.", __func__);
    goto error;
  }

  // Make sure we run in a bounded amount of time
  non_repeating_timer_restart(startup_timer);

  epilog_timer = non_repeating_timer_new(EPILOG_TIMEOUT_MS, epilog_timer_expired, NULL);
  if (!epilog_timer) {
    LOG_ERROR(LOG_TAG, "%s unable to create epilog timer.", __func__);
    goto error;
  }

  command_response_timer = non_repeating_timer_new(COMMAND_PENDING_TIMEOUT, command_timed_out, NULL);
  if (!command_response_timer) {
    LOG_ERROR(LOG_TAG, "%s unable to create command response timer.", __func__);
    goto error;
  }

  command_queue = fixed_queue_new(SIZE_MAX);
  if (!command_queue) {
    LOG_ERROR(LOG_TAG, "%s unable to create pending command queue.", __func__);
    goto error;
  }

  packet_queue = fixed_queue_new(SIZE_MAX);
  if (!packet_queue) {
    LOG_ERROR(LOG_TAG, "%s unable to create pending packet queue.", __func__);
    goto error;
  }

  thread = thread_new("hci_thread");
  if (!thread) {
    LOG_ERROR(LOG_TAG, "%s unable to create thread.", __func__);
    goto error;
  }

  commands_pending_response = list_new(NULL);
  if (!commands_pending_response) {
    LOG_ERROR(LOG_TAG, "%s unable to create list for commands pending response.", __func__);
    goto error;
  }

  memset(incoming_packets, 0, sizeof(incoming_packets));

  packet_fragmenter->init(&packet_fragmenter_callbacks);

  fixed_queue_register_dequeue(command_queue, thread_get_reactor(thread), event_command_ready, NULL);
  fixed_queue_register_dequeue(packet_queue, thread_get_reactor(thread), event_packet_ready, NULL);

  vendor->open(btif_local_bd_addr.address, &interface);
  hal->init(&hal_callbacks, thread);
  low_power_manager->init(thread);

  vendor->set_callback(VENDOR_CONFIGURE_FIRMWARE, firmware_config_callback);
  vendor->set_callback(VENDOR_CONFIGURE_SCO, sco_config_callback);
  vendor->set_callback(VENDOR_DO_EPILOG, epilog_finished_callback);

  if (!hci_inject->open(&interface)) {
    // TODO(sharvil): gracefully propagate failures from this layer.
  }

  int power_state = BT_VND_PWR_OFF;
#if (defined (BT_CLEAN_TURN_ON_DISABLED) && BT_CLEAN_TURN_ON_DISABLED == TRUE)
  LOG_WARN(LOG_TAG, "%s not turning off the chip before turning on.", __func__);
  // So apparently this hack was needed in the past because a Wingray kernel driver
  // didn't handle power off commands in a powered off state correctly.

  // The comment in the old code said the workaround should be removed when the
  // problem was fixed. Sadly, I have no idea if said bug was fixed or if said
  // kernel is still in use, so we must leave this here for posterity. #sadpanda
#else
  // cycle power on the chip to ensure it has been reset
  vendor->send_command(VENDOR_CHIP_POWER_CONTROL, &power_state);
#endif
  power_state = BT_VND_PWR_ON;
  vendor->send_command(VENDOR_CHIP_POWER_CONTROL, &power_state);

  startup_future = future_new();
  LOG_DEBUG(LOG_TAG, "%s starting async portion", __func__);
  thread_post(thread, event_finish_startup, NULL);
  return startup_future;
error:;
  shut_down(); // returns NULL so no need to wait for it
  return future_new_immediate(FUTURE_FAIL);
}
Ejemplo n.º 23
0
int
main(int argc, char **argv)
{
    parse_config_file(DEFAULT_CONF_FILE_PATH);

    load_modules();

    statis.cur_time = time(NULL);

    conf.print_day = -1;

    main_init(argc, argv);

    /*
     * enter running
     */
    switch (conf.running_mode) {
        case RUN_LIST:
            running_list();
            break;

        case RUN_CRON:
            conf.print_mode = DATA_DETAIL;
            running_cron();
            break;
#ifdef OLDTSAR
            /*for check option*/
        case RUN_CHECK:
            reload_check_modules();
            /* disable module when n_col is zero */
            running_check(RUN_CHECK);
            break;
            /*end*/
#endif
        case RUN_CHECK_NEW:
            if (reload_modules(conf.output_print_mod)) {
                conf.print_mode = DATA_DETAIL;
            };
            /* disable module when n_col is zero */
            disable_col_zero();
            running_check(RUN_CHECK_NEW);
            break;
        case RUN_PRINT:
            /* reload module by output_stdio_mod and output_print_mod*/
            reload_modules(conf.output_stdio_mod);
            reload_modules(conf.output_print_mod);

            /* disable module when n_col is zero */
            disable_col_zero();

            /* set conf.print_nline_interval */
            conf.print_nline_interval = conf.print_interval;

            running_print();
            break;

        case RUN_PRINT_LIVE:
            /* reload module by output_stdio_mod and output_print_mod*/
            reload_modules(conf.output_stdio_mod);
            reload_modules(conf.output_print_mod);

            /* disable module when n_col is zero */
            disable_col_zero();

            running_print_live();
            break;

        default:
            break;
    }

    shut_down();
    return 0;
}
Ejemplo n.º 24
0
int
thttpd_run(void)
    {
    char* cp;
    struct passwd* pwd;
    uid_t uid = 32767;
    gid_t gid = 32767;
    int num_ready;
    int cnum;
    connecttab* c;
    httpd_conn* hc;
    httpd_sockaddr sa4;
    httpd_sockaddr sa6;
    int gotv4, gotv6;
    struct timeval tv;
    
    cp = getenv( "GHTTPPORT" );
    if ( cp )
	port = atoi( cp );
    if( port == 0 )
	port = 9999;

    /* Read zone info now, in case we chroot(). */
    tzset();

    /* Look up hostname now, in case we chroot(). */
    lookup_hostname( &sa4, sizeof(sa4), &gotv4, &sa6, sizeof(sa6), &gotv6 );
    if ( ! ( gotv4 || gotv6 ) )
	{
	memset(&sa4, 0, sizeof sa4);
	gotv4 = 1;
	}

    /* Initialize the fdwatch package.  Have to do this before chroot,
    ** if /dev/poll is used.
    */
    max_connects = fdwatch_get_nfiles();
    if ( max_connects < 0 )
	{
	return;
	}
    max_connects -= SPARE_FDS;

    /* Set up to catch signals. */
#ifdef HAVE_SIGSET
    (void) sigset( SIGPIPE, SIG_IGN );          /* get EPIPE instead */
#else /* HAVE_SIGSET */
    (void) signal( SIGPIPE, SIG_IGN );          /* get EPIPE instead */
#endif /* HAVE_SIGSET */

    /* Initialize the timer package. */
    tmr_init();

    /* Initialize the HTTP layer.  Got to do this before giving up root,
    ** so that we can bind to a privileged port.
    */
    hs = httpd_initialize(
	hostname,
	gotv4 ? &sa4 : (httpd_sockaddr*) 0, gotv6 ? &sa6 : (httpd_sockaddr*) 0,
	port, cgi_pattern, cgi_limit, charset, p3p, max_age, "/", no_log, 
	no_symlink_check, do_vhost, do_global_passwd, url_pattern,
	local_pattern, no_empty_referers );
    if ( hs == (httpd_server*) 0 )
	exit( 1 );

    /* Set up the occasional timer. */
    if ( tmr_create( (struct timeval*) 0, occasional, JunkClientData, OCCASIONAL_TIME * 1000L, 1 ) == (Timer*) 0 )
	{
	return;
	}
    /* Set up the idle timer. */
    if ( tmr_create( (struct timeval*) 0, idle, JunkClientData, 5 * 1000L, 1 ) == (Timer*) 0 )
	{
	return;
	}
    start_time = stats_time = time( (time_t*) 0 );
    stats_connections = 0;
    stats_bytes = 0;
    stats_simultaneous = 0;

    /* Initialize our connections table. */
    connects = NEW( connecttab, max_connects );
    if ( connects == (connecttab*) 0 )
	{
	return;
	}
    for ( cnum = 0; cnum < max_connects; ++cnum )
	{
	connects[cnum].conn_state = CNST_FREE;
	connects[cnum].next_free_connect = cnum + 1;
	connects[cnum].hc = (httpd_conn*) 0;
	}
    connects[max_connects - 1].next_free_connect = -1;	/* end of link list */
    first_free_connect = 0;
    num_connects = 0;
    httpd_conn_count = 0;

    if ( hs != (httpd_server*) 0 )
	{
	if ( hs->listen4_fd != -1 )
	    fdwatch_add_fd( hs->listen4_fd, (void*) 0, FDW_READ );
	if ( hs->listen6_fd != -1 )
	    fdwatch_add_fd( hs->listen6_fd, (void*) 0, FDW_READ );
	}

    /* Main loop. */
    (void) gettimeofday( &tv, (struct timezone*) 0 );
    while ( ( ! terminate ) || num_connects > 0 )
	{

	/* Do the fd watch. */
	num_ready = fdwatch( tmr_mstimeout( &tv ) );
	if ( num_ready < 0 )
	    {
	    if ( errno == EINTR || errno == EAGAIN )
		continue;       /* try again */
	    return;
	    }
	(void) gettimeofday( &tv, (struct timezone*) 0 );

	if ( num_ready == 0 )
	    {
	    /* No fd's are ready - run the timers. */
	    tmr_run( &tv );
	    continue;
	    }

	/* Is it a new connection? */
	if ( hs != (httpd_server*) 0 && hs->listen6_fd != -1 &&
	     fdwatch_check_fd( hs->listen6_fd ) )
	    {
	    if ( handle_newconnect( &tv, hs->listen6_fd ) )
		/* Go around the loop and do another fdwatch, rather than
		** dropping through and processing existing connections.
		** New connections always get priority.
		*/
		continue;
	    }
	if ( hs != (httpd_server*) 0 && hs->listen4_fd != -1 &&
	     fdwatch_check_fd( hs->listen4_fd ) )
	    {
	    if ( handle_newconnect( &tv, hs->listen4_fd ) )
		/* Go around the loop and do another fdwatch, rather than
		** dropping through and processing existing connections.
		** New connections always get priority.
		*/
		continue;
	    }

	/* Find the connections that need servicing. */
	while ( ( c = (connecttab*) fdwatch_get_next_client_data() ) != (connecttab*) -1 )
	    {
	    if ( c == (connecttab*) 0 )
		continue;
	    hc = c->hc;
	    if ( ! fdwatch_check_fd( hc->conn_fd ) )
		/* Something went wrong. */
		clear_connection( c, &tv );
	    else
		switch ( c->conn_state )
		    {
		    case CNST_READING: handle_read( c, &tv ); break;
		    case CNST_SENDING: handle_send( c, &tv ); break;
		    case CNST_LINGERING: handle_linger( c, &tv ); break;
		    }
	    }
	tmr_run( &tv );
	}

    /* The main loop terminated. */
    shut_down();
    return 0;
    }
Ejemplo n.º 25
0
static void
cachemgrShutdown(StoreEntry * entryunused)
{
    debug(16, 0) ("Shutdown by command.\n");
    shut_down(0);
}
Ejemplo n.º 26
0
void DLL CloseEncoderJob(EncoderJob &jobSpec) {
	if (!jobSpec.IsValid) return; // already closed!
	shut_down(jobSpec);
	jobSpec.IsValid = false;
	// DONE!
}
Ejemplo n.º 27
0
int main(int argc, char **argv)
{
    int opt;
    char *alt_config = NULL;
    int r = IMAP_NOTFOUND;
    strarray_t mboxnames = STRARRAY_INITIALIZER;
    const char *query = NULL;
    int background = 1;
    const char *channel = "squatter";
    const char *synclogfile = NULL;
    int init_flags = CYRUSINIT_PERROR;
    int multi_folder = 0;
    int user_mode = 0;
    int compact_flags = 0;
    const char *fromfile = NULL;
    strarray_t *srctiers = NULL;
    const char *desttier = NULL;
    enum { UNKNOWN, INDEXER, INDEXFROM, SEARCH, ROLLING, SYNCLOG,
           START_DAEMON, STOP_DAEMON, RUN_DAEMON, COMPACT } mode = UNKNOWN;

    if ((geteuid()) == 0 && (become_cyrus(/*is_master*/0) != 0)) {
        fatal("must run as the Cyrus user", EC_USAGE);
    }

    setbuf(stdout, NULL);

    while ((opt = getopt(argc, argv, "C:I:N:RAXT:S:Fc:de:f:mn:rsiavz:t:ou")) != EOF) {
        switch (opt) {
        case 'C':               /* alt config file */
            alt_config = optarg;
            break;

        case 'A':
            compact_flags |= SEARCH_COMPACT_AUDIT;
            break;

        case 'F':
            compact_flags |= SEARCH_COMPACT_FILTER;
            break;

        case 'X':
            compact_flags |= SEARCH_COMPACT_REINDEX;
            break;

        case 'N':
            name_starts_from = optarg;
            break;

        case 'I':               /* indexer, using specified mbox/uids in file */
            if (mode != UNKNOWN && mode != INDEXFROM) usage(argv[0]);
            fromfile = optarg;
            mode = INDEXFROM;
            break;

        case 'R':               /* rolling indexer */
            if (mode != UNKNOWN) usage(argv[0]);
            mode = ROLLING;
            incremental_mode = 1; /* always incremental if rolling */
            break;

        case 'S':               /* sleep time in seconds */
            sleepmicroseconds = (atof(optarg) * 1000000);
            break;

        case 'T':               /* temporary root directory for search */
            temp_root_dir = optarg;
            break;

        /* This option is deliberately undocumented, for testing only */
        case 'c':               /* daemon control mode */
            if (mode != UNKNOWN) usage(argv[0]);
            if (!strcmp(optarg, "start"))
                mode = START_DAEMON;
            else if (!strcmp(optarg, "stop"))
                mode = STOP_DAEMON;
            else if (!strcmp(optarg, "run"))
                mode = RUN_DAEMON;
            else
                usage(argv[0]);
            break;

        case 'd':               /* foreground (with -R) */
            background = 0;
            break;

        /* This option is deliberately undocumented, for testing only */
        case 'e':               /* add a search term */
            if (mode != UNKNOWN && mode != SEARCH) usage(argv[0]);
            query = optarg;
            mode = SEARCH;
            break;

        case 'f': /* alternate synclogfile used in SYNCLOG mode */
            synclogfile = optarg;
            mode = SYNCLOG;
            break;

        /* This option is deliberately undocumented, for testing only */
        case 'm':               /* multi-folder in SEARCH mode */
            if (mode != UNKNOWN && mode != SEARCH) usage(argv[0]);
            multi_folder = 1;
            mode = SEARCH;
            break;

        case 'n':               /* sync channel name (with -R) */
            channel = optarg;
            break;

        case 'o':               /* copy one DB rather than compressing */
            compact_flags |= SEARCH_COMPACT_COPYONE;
            break;

        case 'v':               /* verbose */
            verbose++;
            break;

        case 'r':               /* recurse */
            if (mode != UNKNOWN && mode != INDEXER) usage(argv[0]);
            recursive_flag = 1;
            mode = INDEXER;
            break;

        case 'i':               /* incremental mode */
            incremental_mode = 1;
            break;

        case 'a':               /* use /squat annotation */
            if (mode != UNKNOWN && mode != INDEXER) usage(argv[0]);
            annotation_flag = 1;
            mode = INDEXER;
            break;

        case 'z':
            if (mode != UNKNOWN && mode != COMPACT) usage(argv[0]);
            desttier = optarg;
            mode = COMPACT;
            break;

        case 't':
            if (mode != UNKNOWN && mode != COMPACT) usage(argv[0]);
            srctiers = strarray_split(optarg, ",", 0);
            mode = COMPACT;
            break;

        case 'u':
            user_mode = 1;
            break;

        default:
            usage("squatter");
        }
    }

    compact_flags |= SEARCH_VERBOSE(verbose);

    if (mode == UNKNOWN)
        mode = INDEXER;

    /* fork and close fds if required */
    if (mode == ROLLING && background) {
        become_daemon();
        init_flags &= ~CYRUSINIT_PERROR;
    }

    if (mode == COMPACT && (!desttier || !srctiers)) {
        /* need both src and dest for compact */
        usage("squatter");
    }

    cyrus_init(alt_config, "squatter", init_flags, CONFIG_NEED_PARTITION_DATA);

    /* Set namespace -- force standard (internal) */
    if ((r = mboxname_init_namespace(&squat_namespace, 1)) != 0) {
        fatal(error_message(r), EC_CONFIG);
    }

    annotate_init(NULL, NULL);
    annotatemore_open();

    mboxlist_init(0);
    mboxlist_open(NULL);

    if (mode == ROLLING || mode == SYNCLOG) {
        signals_set_shutdown(&shut_down);
        signals_add_handlers(0);
    }

    switch (mode) {
    case UNKNOWN:
        break;
    case INDEXER:
        /* -r requires at least one mailbox */
        if (recursive_flag && optind == argc) usage(argv[0]);
        expand_mboxnames(&mboxnames, argc-optind, (const char **)argv+optind, user_mode);
        syslog(LOG_NOTICE, "indexing mailboxes");
        r = do_indexer(&mboxnames);
        syslog(LOG_NOTICE, "done indexing mailboxes");
        break;
    case INDEXFROM:
        syslog(LOG_NOTICE, "indexing messages");
        r = do_indexfrom(fromfile);
        syslog(LOG_NOTICE, "done indexing messages");
        break;
    case SEARCH:
        if (recursive_flag && optind == argc) usage(argv[0]);
        expand_mboxnames(&mboxnames, argc-optind, (const char **)argv+optind, user_mode);
        r = do_search(query, !multi_folder, &mboxnames);
        break;
    case ROLLING:
        do_rolling(channel);
        /* never returns */
        break;
    case SYNCLOG:
        r = do_synclogfile(synclogfile);
        break;
    case START_DAEMON:
        if (optind != argc) usage("squatter");
        search_start_daemon(verbose);
        break;
    case STOP_DAEMON:
        if (optind != argc) usage("squatter");
        search_stop_daemon(verbose);
        break;
    case RUN_DAEMON:
        if (optind != argc) usage("squatter");
        do_run_daemon();
        break;
    case COMPACT:
        if (recursive_flag && optind == argc) usage(argv[0]);
        expand_mboxnames(&mboxnames, argc-optind, (const char **)argv+optind, user_mode);
        r = do_compact(&mboxnames, srctiers, desttier, compact_flags);
        break;
    }

    strarray_fini(&mboxnames);
    shut_down(r ? EC_TEMPFAIL : 0);
}
Ejemplo n.º 28
0
/* Called by service API to shut down the service */
void service_abort(int error)
{
    shut_down(error);
}