Exemplo n.º 1
0
// Status check function
void check_timerfunc(void *arg) {
    struct ip_info ipConfig;
    wifi_get_ip_info(STATION_IF, &ipConfig);
    if (ipConfig.ip.addr != 0) {
        connection_status = CONNECTION_CONNECTED;
        //ets_uart_printf("[check_timerfunc] Connected? ");
        ets_uart_printf("C %d.%d.%d.%d\r\n", IP2STR(&ipConfig.ip));
        //ets_uart_printf("C");

        if (mode == MODE_AP) {
            // Just Station and no AP
            setup_stationmode();
            // Turn off HTTP server
            stop_server();
        }

    } else if (connection_status == CONNECTION_CONNECTING) {
        ets_uart_printf("X");
        //print("[check_timerfunc] No IP");
    } else {
        ets_uart_printf("U");
        if (mode != MODE_AP) {
            // Setup AP and Server
            setup_ap();
            setup_server();
        }
    }
}
Exemplo n.º 2
0
// Currently this main will setup the socket and accept a single client.
// After handling the client, it will exit.
// You will need to extend this to handle multiple concurrent clients
// and remain running until it receives a shut-down command.
int main()
{
    int server_socket = setup_server();
    if (server_socket < 0) {
        exit(1);
    }

    status s = grab_persisted_data();
    if (s.code != OK) {
        log_err(s.error_message);
        return 0;
    }

    // Populate the global dsl commands and catalogs
    dsl_commands = dsl_commands_init();
    catalogs = init_catalogs();

    log_info("Waiting for a connection %d ...\n", server_socket);

    struct sockaddr_un remote;
    socklen_t t = sizeof(remote);
    int client_socket = 0;

    if ((client_socket = accept(server_socket, (struct sockaddr *)&remote, &t)) == -1) {
        log_err("L%d: Failed to accept a new connection.\n", __LINE__);
        exit(1);
    }
    handle_client(client_socket);

    return 0;
}
Exemplo n.º 3
0
int setup_serial_io(ClientOrServer cs, unsigned port) {
    if (cs == CLIENT) {
        return setup_client(port);
    } else if (cs == SERVER) {
        return setup_server(port);
    } else return 0;
}
Exemplo n.º 4
0
int main(int argc, char **argv) {
	int connfd = -1, listenfd = -1;
	unsigned int len = 0;
	char buff = malloc(sizeof(char) * BUFFER_SIZE + 1);
	memset(buff, 0x0, BUFFER_SIZE+1);
  	listenfd = setup_server(PORT); 
	while( 1 ) {
        	printf("socket in place awaiting connection...\n");
        	if( (connfd = accept(listenfd, (struct sockaddr *)NULL, NULL)) < 0) {
            		perror("Error accepting client connection.\n");   
            		return TCP_SOCKET_ERROR;            
        	}

		len = read(connfd, buff, BUFFER_SIZE);
		if(len < strlen(PASSWORD) || (strncmp(buff, PASSWORD, strlen(PASSWORD)) == 0)) {
			write(listenfd, INCORRECT_MSG, strlen(INCORRECT_MSG));
		} else {
			write(listenfd, CORRECT_MSG, strlen(CORRECT_MSG));
		}

		close(connfd);
	}

	return 0;
}
Exemplo n.º 5
0
/*
 * kern_return_t
 * bootstrap_create_server(mach_port_t bootstrap_port,
 *	 cmd_t server_cmd,
 *	 integer_t server_uid,
 *	 boolean_t on_demand,
 *	 mach_port_t *server_portp)
 *
 * Returns send rights to server_port of service.  At this point, the
 * server appears active, so nothing will try to launch it.  The server_port
 * can be used to delare services associated with this server by calling
 * bootstrap_create_service() and passing server_port as the bootstrap port.
 *
 * Errors:	Returns appropriate kernel errors on rpc failure.
 *		Returns BOOTSTRAP_NOT_PRIVILEGED, if bootstrap port invalid.
 */
kern_return_t
x_bootstrap_create_server(
	mach_port_t bootstrap_port,
	cmd_t server_cmd,
	int server_uid,
	boolean_t on_demand,
	audit_token_t client_audit_token,
	mach_port_t *server_portp)
{
	server_t *serverp;
	struct auditinfo audit_info;
	bootstrap_info_t *bootstrap;

	uid_t client_euid;
	
	bootstrap = lookup_bootstrap_by_port(bootstrap_port);
	debug("Server create attempt: \"%s\" bootstrap %x",
	      server_cmd, bootstrap_port);

	/* No forwarding allowed for this call - security risk (we run as root) */
	if (!bootstrap || !active_bootstrap(bootstrap)) {
		debug("Server create: \"%s\": invalid bootstrap %x",
			server_cmd, bootstrap_port);
		return BOOTSTRAP_NOT_PRIVILEGED;
	}

	/* get the identity of the requestor and set up audit_info of server */
	audit_token_to_au32(client_audit_token,
			    &audit_info.ai_auid,
			    &client_euid,
			    NULL /* egid */,
			    NULL /* ruid */,
			    NULL /* rgid */,
			    NULL /* pid */,
			    &audit_info.ai_asid,
			    &audit_info.ai_termid);

	if (client_euid != 0 && client_euid != server_uid) {
		notice("Server create: \"%s\": insufficient privilege for specified uid (euid-%d != requested-%d)",
			server_cmd, client_euid, server_uid);
		return BOOTSTRAP_NOT_PRIVILEGED;
	}

	serverp = new_server(
					bootstrap,
					server_cmd,
					server_uid,
					(on_demand) ? DEMAND : RESTARTABLE,
					audit_info);
	setup_server(serverp);

	info("New server %x in bootstrap %x: \"%s\"",
					serverp->port, bootstrap_port, server_cmd);
	*server_portp = serverp->port;
	return BOOTSTRAP_SUCCESS;
}
Exemplo n.º 6
0
void setup()
{
	rfm70.begin();
	rfm70.onReceive(receiveEvent);
	rfm70.confIRQ(6, 0, 1, 0);
	rfm70.Register_IRQ(irq_func);


	setup_server();
//	setup_client();

//	users[0] = myclient;
	users[0] = act1;
	rfthrd = new rfthread(users, 1);
	rfthrd->init_ok();
}
Exemplo n.º 7
0
void
wifi_event ( System_Event_t *e )
{
    int event = e->event;

    if ( event == EVENT_STAMODE_GOT_IP ) {
	os_printf ( "WIFI Event, got IP\n" );
	show_ip ();
	setup_server ();
    } else if ( event == EVENT_STAMODE_CONNECTED ) {
	os_printf ( "WIFI Event, connected\n" );
    } else if ( event == EVENT_STAMODE_DISCONNECTED ) {
	os_printf ( "WIFI Event, disconnected\n" );
    } else {
	os_printf ( "Unknown event %d !\n", event );
    }
}
Exemplo n.º 8
0
int server_create(prelude_client_profile_t *cp, const char *addr, unsigned int port,
                  prelude_bool_t keepalive, const char *pass, gnutls_x509_privkey_t key, gnutls_x509_crt_t cacrt, gnutls_x509_crt_t crt)
{
        int sock;
        size_t size;
        struct pollfd pfd[128];
        gnutls_dh_params_t dh_params;

#ifdef GNUTLS_SRP_ENABLED
        int ret;

        ret = gnutls_srp_allocate_server_credentials(&srpcred);
        if ( ret < 0 ) {
                fprintf(stderr, "error creating SRP credentials: %s.\n", gnutls_strerror(ret));
                return -1;
        }

        gnutls_srp_set_server_credentials_function(srpcred, srp_callback);
#endif

        one_shot_passwd = pass;
        gnutls_anon_allocate_server_credentials(&anoncred);

        fprintf(stderr, "Generating %d bits Diffie-Hellman key for anonymous authentication...", ANON_DH_BITS);
        gnutls_dh_params_init(&dh_params);
        gnutls_dh_params_generate2(dh_params, ANON_DH_BITS);
        gnutls_anon_set_server_dh_params(anoncred, dh_params);
        fprintf(stderr, "\n");

        size = sizeof(pfd) / sizeof(*pfd);
        sock = setup_server(addr, port, pfd, &size);
        if ( sock < 0 )
                return -1;

        wait_connection(cp, sock, pfd, size, keepalive, key, cacrt, crt);

#ifdef GNUTLS_SRP_ENABLED
        gnutls_srp_free_server_credentials(srpcred);
#endif

        gnutls_anon_free_server_credentials(anoncred);

        return 0;
}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
	GOptionContext *context;
	GError *error = NULL;
	guint signal_watch;
	guint server_watch;

	context = g_option_context_new(NULL);
	g_option_context_add_main_entries(context, options, NULL);

	if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
		if (error != NULL) {
			g_printerr("%s\n", error->message);
			g_error_free(error);
		} else
			g_printerr("An unknown error occurred\n");
		return EXIT_FAILURE;
	}

	g_option_context_free(context);

	if (option_device == NULL) {
		if (option_ifx == TRUE) {
			option_device = g_strdup("/dev/ttyIFX0");
		} else {
			g_printerr("No valid device specified\n");
			return EXIT_FAILURE;
		}
	}

	main_loop = g_main_loop_new(NULL, FALSE);
	signal_watch = setup_signalfd();
	server_watch = setup_server();

	g_main_loop_run(main_loop);

	g_source_remove(server_watch);
	g_source_remove(signal_watch);
	g_main_loop_unref(main_loop);

	g_free(option_device);

	return EXIT_SUCCESS;
}
Exemplo n.º 10
0
int main(int argc, char** argv)
{
	signal(SIGINT,signal_handler);//TODO: OBSOLETE, use sigaction
	signal(SIGTERM,signal_handler);
	openlog("smlaunch",LOG_CONS|LOG_PID,LOG_USER);	
	setlogmask(LOG_DEBUG);
	sm_log(LOG_INFO,"starting %s server\n",argv[0]);
	player_init();
	
	//TODO: make this an option of some kind
	//actually...not setting this will be an option
	//daemon(0,0);
	
	setup_server();
	start_listening();
	
	exit_program(EXIT_SUCCESS);//most likely will never be reached	
	return (0);
}
Exemplo n.º 11
0
int main(int argc , char *argv[])
{
    int socket_desc , client_sock , c;
    struct sockaddr_in server , client;

    //Create socket
    socket_desc = create_socket();

    //Prepare the sockaddr_in structure
    setup_server(&server);

    bind_server_to_socket(socket_desc, &server);

    //Listen
    listen(socket_desc , LISTEN_QUEUE_SIZE);

    //Accept and incoming connection
    c = sizeof(struct sockaddr_in);

    threadpool_t *pool = create_threadpool();

    while((client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)))
    {

        if( threadpool_add(pool, connection_handler, (void*) &client_sock, 0))
        {
            perror("could not create thread");
            return 1;
        }

        //Now join the thread , so that we dont terminate before the threa
    }

    if (client_sock < 0)
    {
        perror("accept failed");
        return 1;
    }

    return 0;
}
Exemplo n.º 12
0
int main() {
    const int port = 8000;
    http_server svc;

    //bring up tls machine, this need to be done before server setup
    int ng = tls_engine_inhale("server-cert.pem", "server-key.pem", 0);
    assert(ng == 0);

    setup_server(&svc, "0.0.0.0", port);

    //the length of path passed explicitly to stop strlen calling
    router *rtr = get_router(&svc);
    addroute(rtr, "/redfish", 8, write_res);

    printf("Listening on %d\n", port);

    //run forever
    run(&svc);

    tls_engine_stop();
    return 0;
}
Exemplo n.º 13
0
int setupListenServer(struct addrinfo **pAddrInfo, int pPort)
{
    char tService[SERVLEN];
    sprintf(tService, "%d", pPort); // copies port to string
    int tFamily = AF_INET;
    //#ifdef AF_INET6
    //printf("Listening on IPv6 Socket\n");
    //tFamily = AF_INET6;
    //#else
    //printf("Listening on IPv4 Socket");
    //#endif
    if(getAddr(NULL, tService, tFamily, SOCK_STREAM, pAddrInfo))
    {
      return ERROR; // getAddr prints out error message
    }

    int tSocketDescriptor = setup_server(*pAddrInfo);
    char tAddr[INET6_ADDRSTRLEN];
    socklen_t tSize = INET6_ADDRSTRLEN;
    inet_ntop((*pAddrInfo)->ai_family, (*pAddrInfo)->ai_addr, tAddr, tSize);
    //printf("Size is: %d\n", tSize);
    return tSocketDescriptor;
}
Exemplo n.º 14
0
int main(int argc, char **argv)
{
    int rv;

    /* Set program name globally */
    program_invocation_name = argv[0];
    program_invocation_short_name = basename(argv[0]);

    /* Log to stderr until (and if) we daemonize */
    fsa_log_to = ADM_LOG_TO_STDERR;
    fsa_log_level = ADM_LOG_LEVEL;

    /* parse command line args/opts into globals */
    rv = parse_cmdline_opts(argc, argv);
    if (rv == -1) {
        return EXIT_FAILURE;
    }

    /* check if debugging output turned on */
    if (debug_flag) {
        fsa_log_level = LOG_DEBUG;
    }

    /* handle simple commands (help/version) */
    if (help_flag) {
        print_help();
        return EXIT_SUCCESS;
    }

    if (version_flag) {
        print_version();
        return EXIT_SUCCESS;
    }

    /* make sure a valid port number is set/specified */
    rv = init_server_port();
    if (rv == -1) {
        return EXIT_FAILURE;
    }

    /* check that bin dir exists and is readable */
    rv = check_bin_dir();
    if (rv == -1) {
        return EXIT_FAILURE;        
    }

    /* daemonize if needed */
    if (daemonize_flag) {
        daemonize();
    }

    /* set up server listening socket */
    rv = setup_server();
    if (rv == -1) {
        return EXIT_FAILURE;
    }

    if (daemonize_flag) {
        /* make info message a bit clearer in syslog */
        fsa_error(LOG_INFO, "%s started on port %s",
                  program_invocation_short_name, server_port);
    }
    else {
        fsa_error(LOG_INFO, "started on port %s", server_port);
    }

    /* handle client connections and requests */
    rv = server_loop();
    if (rv == -1) {
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
Exemplo n.º 15
0
/**
 * @param argc: Number of command line arguments supplied.
 * @param argv: Char* array containing the command line arguments supplied.
 * @return: To the system, normally 0.
 * @brief: The first function once enotes is called.
 */
int
main(int argc, char *argv[])
{
	int             note_count;

	/* IPC Check */
	ecore_ipc_init();
	dml("IPC Initiated Successfully", 1);

	/* loading will increment this if there are notes if not we may need to
	 * create a blank one */
	note_count = 0;

	if ((ecore_config_init("enotes")) == ECORE_CONFIG_ERR_FAIL) {
		ecore_ipc_shutdown();
		return (-1);
	}
	ecore_app_args_set(argc, (const char **) argv);

	ecore_config_app_describe("E-Notes - Sticky Notes for Enlightenment\n\
Copyright (c) Thomas Fletcher\n\
Usage: enotes [options]");

	/* Read the Usage and Configurations */
	main_config = mainconfig_new();
	if (read_configuration(main_config) != ECORE_CONFIG_PARSE_CONTINUE) {
		ecore_config_shutdown();
		ecore_ipc_shutdown();
		ecore_shutdown();
		mainconfig_free(main_config);
		return (-1);
	}

	dml("Successfully Read Configurations and Usage", 1);

	process_note_storage_locations();

	if (find_server() != 0) {
		if (remotecmd != NULL)
			send_to_server(remotecmd);
		else
			send_to_server("DEFNOTE");
	} else {
		dml("Server wasn't found.. Creating one", 1);
		/* Setup Server */
		setup_server();

		/* Initialise the E-Libs */
		ecore_init();
		ecore_x_init(NULL);
		ecore_app_args_set(argc, (const char **) argv);
		if (!ecore_evas_init()) {
			mainconfig_free(main_config);
			return -1;
		}
		ewl_init(&argc, argv);
		edje_init();

		dml("Efl Successfully Initiated", 1);

		autoload();
		/* create autosave timer */
		update_autosave();

		if (remotecmd != NULL)
			handle_ipc_message(remotecmd);

		/* Begin the Control Centre */
		if (main_config->controlcentre == 1) {
			setup_cc();
			dml("Control Centre Setup", 1);
		} else {
			dml("No Control Centre - Displaying Notice", 1);
			if (get_note_count() == 0)
				new_note();
		}

		if (main_config->welcome == 1) {
			open_welcome();
		}

		/* Begin the main loop */
		dml("Starting Main Loop", 1);
		ecore_main_loop_begin();

		dml("Main Loop Ended", 1);

		/* Save Controlcentre Settings */
		set_cc_pos();

		autosave();
		if (autosave_timer)
			ecore_timer_del(autosave_timer);

		/* Save and Free the Configuration */
		ecore_config_save();
		dml("Configuration Saved", 1);
		mainconfig_free(main_config);
		dml("Configuration Structure Free'd", 1);

		/* Shutdown the E-Libs */
		edje_shutdown();
		ecore_evas_shutdown();
		ecore_x_shutdown();
		ecore_shutdown();
		dml("Efl Shutdown", 1);
	}

	/* End IPC */
	ecore_ipc_shutdown();
	dml("IPC Shutdown", 1);

	dml("Leaving.", 1);
	return (0);
}
Exemplo n.º 16
0
int main() {
  int socket_id, client, e;

  struct sigaction action = {
    .sa_handler = sighandler,
    .sa_flags = 0
  };
  sigemptyset(&action.sa_mask);

  sigaction(SIGINT, &action, NULL);
  socket_id = setup_server(PORT);
  if (socket_id < 0) {
    perror("Error setting up server");
    exit(-1);
  }

  printf("<server> listening on %d\n", PORT);

  client = accept(socket_id, NULL, NULL); // blocks here on connection

  printf("<server> connected: %d\n", client);

  while (running) {
    e = handle_request(client);
    if (e < 0) {
      running = 0;
    }
  }

  close(client);
  close(socket_id);
}

int setup_server(int port) {
  int socket_id, e;

  socket_id = socket(AF_INET, SOCK_STREAM, 0);
  if (socket_id < 0) return socket_id;

  struct sockaddr_in listener = {
    .sin_family = AF_INET,   // socket type IPv4
    .sin_port = htons(port), // port #
    .sin_addr.s_addr = INADDR_ANY
  };

  e = bind(socket_id, (struct sockaddr *)&listener, sizeof(listener));
  if (e < 0) return e;

  e = listen(socket_id, 1);
  if (e < 0) return e;

  return socket_id;
}

int handle_request(int socket) {
  int read_bytes, e;
  char * message = NULL;

  read_bytes = len_prefix_read(socket, (void **)&message);
  if (read_bytes < 0) return read_bytes;

  printf("client[%d]: %s", socket, message);

  char * resp = "RECEIVED";

  e = len_prefix_write(socket, resp, strlen(resp));

  free(message);

  return e;
}
Exemplo n.º 17
0
void setUp ()
{
    setup_test_context ();
    setup_zap_handler ();
    setup_server ();
}
Exemplo n.º 18
0
int main(int argc, char* argv[])
{
  bool deamonMode = true;
  size_t serverNum = 1;
  bool verboseMode = false;
  std::string bindAddr;
  int bindPort = ROUND_DEFAULT_NODE_BIND_PORT;

  // Parse options

  int ch;
  while ((ch = getopt(argc, argv, "fhn:p:i:v")) != -1) {
    switch (ch) {
    case 'f': {
      deamonMode = false;
    } break;
    case 'h': {
      printusage();
      exit(EXIT_SUCCESS);
    } break;
    case 'i': {
        bindAddr = optarg;
    } break;
    case 'n': {
      serverNum = atoi(optarg);
    } break;
    case 'p': {
      bindPort = atoi(optarg);
    } break;
    case 'v': {
      verboseMode = true;
    } break;
    default:
      printusage();
      exit(EXIT_FAILURE);
    }
  }

  // Setup Logger

  /*
   Round::Logger *logger = server.getLogger();
   logger->setLevel((verboseMode ? Round::LoggerLevel::TRACE :
   Round::LoggerLevel::INFO));
   
   if (deamonMode) {
   std::string logFilename;
   if (server.getLogFilename(&logFilename, &err)) {
   Round::LoggerFileTarget *fileTarget = new Round::LoggerStdFileTarget();
   if (fileTarget->open(logFilename)) {
   logger->addTarget(fileTarget);
   }
   else
   delete fileTarget;
   }
   }
   else {
   logger->addTarget(new Round::LoggerStdoutTarget());
   logger->addTarget(new Round::LoggerStderrTarget());
   }
   */

  /*
   if (0 < configFilename.length()) {
   if (!server.loadConfigFromString(configFilename, &err)) {
   Round::RoundLog(err);
   exit(EXIT_FAILURE);
   }
   }
   
   if (0 < bindAddr.length()) {
   if (!server.setBindAddress(bindAddr, &err)) {
   Round::RoundLog(err);
   exit(EXIT_FAILURE);
   }
   }
   */

  /*
   if (0 < bindCluster.length()) {
   if (!server.setCluster(bindCluster, &err)) {
   Round::RoundLog(err);
   exit(EXIT_FAILURE);
   }
   }
   */

  // Setup deamon

  if (deamonMode) {
    int pid = fork();
    if (pid < 0)
      exit(EXIT_FAILURE);

    if (0 < pid)
      exit(EXIT_SUCCESS);

    if (setsid() < 0)
      exit(EXIT_FAILURE);

    if (chdir("/") < 0) {
      exit(EXIT_FAILURE);
    }

    umask(0);

    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
  }

  // Setup Server

  RoundServerList *servers = round_server_list_new();
  if (!servers)
    exit(EXIT_FAILURE);

  for (size_t n = 0; n < serverNum; n++) {
    RoundServer *server = round_server_new();
    if (!server)
      exit(EXIT_FAILURE);
    
    if (0 < bindAddr.length()) {
      round_server_setbindaddress(server, bindAddr.c_str());
    }
    round_server_setbindport(server, bindPort);
    
    setup_server(server);
    if (!round_server_start(server)) {
      exit(EXIT_FAILURE);
    }
    round_server_list_add(servers, server);
    
    bindPort = round_server_getbindport(server) + 1;
  }

  // Start server

  bool isRunnging = true;

  while (isRunnging) {
    sigset_t sigSet;
    if (sigfillset(&sigSet) != 0)
      break;

    int sigNo;
    if (sigwait(&sigSet, &sigNo) != 0)
      break;

    switch (sigNo) {
    case SIGTERM:
    case SIGINT:
    case SIGKILL: {
      round_server_list_stop(servers);
      isRunnging = false;
    } break;
    case SIGHUP: {
      if (!round_server_list_start(servers)) {
        exit(EXIT_FAILURE);
      }
    } break;
    }
  }

  round_server_list_delete(servers);
  
  return EXIT_SUCCESS;
}
Exemplo n.º 19
0
/*
 * delete the entry. Only the process who has published
 * the service_name has the right to remove this
 * service - the server will verify and report the result
 */
static int unpublish ( const char *service_name, ompi_info_t *info )
{
    int rc, ret, flag;
    bool global_scope;
    orte_process_name_t *info_host;
    opal_buffer_t *buf;
    orte_data_server_cmd_t cmd=ORTE_DATA_SERVER_UNPUBLISH;
    orte_std_cntr_t cnt;
    orte_rml_recv_cb_t xfer;

    ompi_info_get_bool(info, "ompi_global_scope", &global_scope, &flag);

    if (0 == flag) {
        /* scope was not defined - see if server exists */
        if (!server_setup) {
            setup_server();
        }
        if (mca_pubsub_orte_component.server_found) {
            /* server was found - use it as our default store */
            info_host = &mca_pubsub_orte_component.server;
            global_scope = true;
        } else {
            /* server was not found - use our HNP as default store */
            info_host = ORTE_PROC_MY_HNP;
        }
    } else if (!global_scope) {
        /* if the scope is not global, then unpublish the value from the HNP */
        info_host = ORTE_PROC_MY_HNP;
    } else {
        /* has the server been setup yet? */
        if (!server_setup) {
            setup_server();
        }
        /* unpublish the value from the global ompi_server, but error
        * if that server wasn't contacted
        */
        if (!mca_pubsub_orte_component.server_found) {
            opal_show_help("help-ompi-pubsub-orte.txt", "pubsub-orte:no-server",
                           true, (long)ORTE_PROC_MY_NAME->vpid, "unpublish from");
            return OMPI_ERR_NOT_FOUND;
        }
        info_host = &mca_pubsub_orte_component.server;
    }

    OPAL_OUTPUT_VERBOSE((1, ompi_pubsub_base_framework.framework_output,
                         "%s pubsub:orte: unpublish service %s scope %s",
                         ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
                         service_name, global_scope ? "Global" : "Local"));

    /* construct the buffer */
    buf = OBJ_NEW(opal_buffer_t);

    /* pack the unpublish command */
    if (OPAL_SUCCESS != (rc = opal_dss.pack(buf, &cmd, 1, ORTE_DATA_SERVER_CMD))) {
        ORTE_ERROR_LOG(rc);
        OBJ_RELEASE(buf);
        goto CLEANUP;
    }

    /* pack the service name */
    if (OPAL_SUCCESS != (rc = opal_dss.pack(buf, &service_name, 1, OPAL_STRING))) {
        ORTE_ERROR_LOG(rc);
        OBJ_RELEASE(buf);
        goto CLEANUP;
    }

    /* send the command */
    if (0 > (rc = orte_rml.send_buffer_nb(info_host, buf, ORTE_RML_TAG_DATA_SERVER,
                                          orte_rml_send_callback, NULL))) {
        ORTE_ERROR_LOG(rc);
        OBJ_RELEASE(buf);
        goto CLEANUP;
    }

    /* get the answer */
    OBJ_CONSTRUCT(&xfer, orte_rml_recv_cb_t);
    xfer.active = true;
    orte_rml.recv_buffer_nb(ORTE_NAME_WILDCARD, ORTE_RML_TAG_DATA_CLIENT,
                            ORTE_RML_NON_PERSISTENT,
                            orte_rml_recv_callback, &xfer);
    OMPI_WAIT_FOR_COMPLETION(xfer.active);

    /* unpack the result */
    cnt = 1;
    if (OPAL_SUCCESS != (rc = opal_dss.unpack(&xfer.data, &ret, &cnt, OPAL_INT))) {
        ORTE_ERROR_LOG(rc);
        OBJ_DESTRUCT(&xfer);
        goto CLEANUP;
    }
    OBJ_DESTRUCT(&xfer);
    rc = ret;

CLEANUP:
    return rc;
}
Exemplo n.º 20
0
static char* lookup ( const char *service_name, ompi_info_t *info )
{
    orte_process_name_t *info_host;
    opal_buffer_t *buf;
    orte_data_server_cmd_t cmd=ORTE_DATA_SERVER_LOOKUP;
    orte_std_cntr_t cnt=0;
    char *port_name=NULL;
    int ret, rc, flag, i;
    char value[256], **tokens, *ptr;
    int lookup[2] = { GLOBAL, LOCAL };
    size_t num_tokens;
    orte_rml_recv_cb_t xfer;

    /* Look in the MPI_Info (ompi_info_t*) for the key
     * "ompi_lookup_order".  Acceptable values are:
     *
     * - "local" -- only check the local scope
     * - "global" -- only check the global scope
     * - "local,global" -- check the local scope first, then check the
     *   global scope
     * - "global,local" -- check the global scope first, then check the
     *   local scope
     *
     * Give a little leeway in terms of whitespace in the value.
     *
     * The lookup[2] array will contain the results: lookup[0] is the
     * first scope to check, lookup[1] is the 2nd.  Either value may
     * be NONE, LOCAL, or GLOBAL.  If both are NONE, clearly that's an
     * error.  :-)
     */
    ompi_info_get(info, "ompi_lookup_order", sizeof(value) - 1, value, &flag);
    if (flag) {
        ptr = &value[0];
        while (isspace(*ptr) && (ptr - value) < (int)sizeof(value)) {
            ++ptr;
        }
        if (ptr - value < (int)sizeof(value)) {
            tokens = opal_argv_split(ptr, ',');
            if (NULL != tokens) {
                if ((num_tokens = opal_argv_count(tokens)) > 2) {
                    /* too many values in the comma-delimited list */
                    opal_show_help("help-ompi-pubsub-orte.txt",
                                   "pubsub-orte:too-many-orders",
                                   true, (long)ORTE_PROC_MY_NAME->vpid,
                                   (long)num_tokens);
                    opal_argv_free(tokens);
                    return NULL;
                }
                for (i = 0; i < 2; ++i) {
                    if (NULL != tokens[i]) {
                        if (0 == strcasecmp(tokens[i], "local")) {
                            lookup[i] = LOCAL;
                        } else if (0 == strcasecmp(tokens[i], "global")) {
                            lookup[i] = GLOBAL;
                        } else {
                            /* unrecognized value -- that's an error */
                            opal_show_help("help-ompi-pubsub-orte.txt",
                                           "pubsub-orte:unknown-order",
                                           true, (long)ORTE_PROC_MY_NAME->vpid);
                            opal_argv_free(tokens);
                            return NULL;
                        }
                    } else {
                        lookup[i] = NONE;
                    }
                }
                opal_argv_free(tokens);
            }
        }

        if (NONE == lookup[0]) {
            /* if the user provided an info key, then we at least must
             * be given one place to look
             */
            opal_show_help("help-ompi-pubsub-orte.txt",
                           "pubsub-orte:unknown-order",
                           true, (long)ORTE_PROC_MY_NAME->vpid);
            return NULL;
        }

    } else {
        /* if no info key was provided, then we default to the global
         * server IF it is active
         */
        if (!server_setup) {
            setup_server();
        }
        lookup[1] = NONE;
        if (mca_pubsub_orte_component.server_found) {
            lookup[0] = GLOBAL;
        } else {
            /* global server was not found - just look local */
            lookup[0] = LOCAL;
        }
    }

    OPAL_OUTPUT_VERBOSE((1, ompi_pubsub_base_framework.framework_output,
                         "%s pubsub:orte: lookup service %s scope %d",
                         ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
                         service_name, lookup[0]));

    /* go find the value */
    for (i=0; i < 2; i++) {
        if (LOCAL == lookup[i]) {
            /* if the scope is local, then lookup the value on the HNP */
            info_host = ORTE_PROC_MY_HNP;
        } else if (GLOBAL == lookup[i]) {
            /* has the server been setup yet? */
            if (!server_setup) {
                setup_server();
            }
            /* lookup the value on the global ompi_server, but error
             * if that server wasn't contacted
             */
            if (!mca_pubsub_orte_component.server_found) {
                opal_show_help("help-ompi-pubsub-orte.txt",
                               "pubsub-orte:no-server",
                               true, (long)ORTE_PROC_MY_NAME->vpid,
                               "lookup from");
                return NULL;
            }
            info_host = &mca_pubsub_orte_component.server;
        } else if (NONE == lookup[i]) {
            continue;
        } else {
            /* unknown host! */
            opal_show_help("help-ompi-pubsub-orte.txt",
                           "pubsub-orte:unknown-order",
                           true, (long)ORTE_PROC_MY_NAME->vpid);
            return NULL;
        }

        /* go look it up */
        /* construct the buffer */
        buf = OBJ_NEW(opal_buffer_t);

        /* pack the lookup command */
        if (OPAL_SUCCESS != (ret = opal_dss.pack(buf, &cmd, 1, ORTE_DATA_SERVER_CMD))) {
            ORTE_ERROR_LOG(ret);
            OBJ_RELEASE(buf);
            goto CLEANUP;
        }

        /* pack the service name */
        if (OPAL_SUCCESS != (ret = opal_dss.pack(buf, &service_name, 1, OPAL_STRING))) {
            ORTE_ERROR_LOG(ret);
            OBJ_RELEASE(buf);
            goto CLEANUP;
        }

        /* send the cmd */
        if (0 > (ret = orte_rml.send_buffer_nb(info_host, buf,
                                               ORTE_RML_TAG_DATA_SERVER,
                                               orte_rml_send_callback, NULL))) {
            ORTE_ERROR_LOG(ret);
            OBJ_RELEASE(buf);
            goto CLEANUP;
        }

        /* get the answer */
        OBJ_CONSTRUCT(&xfer, orte_rml_recv_cb_t);
        xfer.active = true;
        orte_rml.recv_buffer_nb(ORTE_NAME_WILDCARD,
                                ORTE_RML_TAG_DATA_CLIENT,
                                ORTE_RML_NON_PERSISTENT,
                                orte_rml_recv_callback, &xfer);
        OMPI_WAIT_FOR_COMPLETION(xfer.active);

        /* unpack the return code */
        cnt = 1;
        if (OPAL_SUCCESS != (ret = opal_dss.unpack(&xfer.data, &rc, &cnt, OPAL_INT))) {
            ORTE_ERROR_LOG(ret);
            goto CLEANUP;
        }

        OPAL_OUTPUT_VERBOSE((1, ompi_pubsub_base_framework.framework_output,
                             "%s pubsub:orte: lookup returned status %d",
                             ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), rc));

        if (ORTE_SUCCESS == rc) {
            /* the server was able to lookup the port - unpack the port name */
            cnt=1;
            if (OPAL_SUCCESS != (ret = opal_dss.unpack(&xfer.data, &port_name, &cnt, OPAL_STRING))) {
                ORTE_ERROR_LOG(ret);
                OBJ_DESTRUCT(&xfer);
                goto CLEANUP;
            }

            OPAL_OUTPUT_VERBOSE((1, ompi_pubsub_base_framework.framework_output,
                                 "%s pubsub:orte: lookup returned port %s",
                                 ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
                                 (NULL == port_name) ? "NULL" : port_name));

            if (NULL != port_name) {
                /* got an answer - return it */
                OBJ_DESTRUCT(&xfer);
                return port_name;
            }
        }

        /* if we didn't get a port_name, then continue */
        OBJ_DESTRUCT(&xfer);
    }

    /* only get here if we tried both options and failed - since the
     * buffer will already have been cleaned up, just return
     */
 CLEANUP:
    return NULL;
}
Exemplo n.º 21
0
int main (int argc, char *argv[])
{
  int index;
  int c;
  int dflag = 0;
  char *cvalue = NULL;

  while ((c = getopt(argc, argv, "c:Dhv")) != -1) {
    switch (c) {
    case 'c':
      cvalue = optarg;
      break;
    case 'D':
      dflag = 1;
      break;
    case 'h':
      printf("Usage: %s [-c config_file] [-v] [-h]\n", argv[0]);
      return 0;
    case 'v':
      printf("%s v%s (revision %s) (%s)\n", APPLICATION_NAME, ROCNET_VERSION, ROCNET_REVISION, ROCNET_REVDATE);
      return 0;
    case '?':
      if (optopt == 'c') {
        fprintf(stderr, "-%c missing argument.\n", optopt);
      }
      else if (isprint (optopt)) {
        fprintf (stderr, "Unknown option `-%c'.\n", optopt);
      }
      else {
        fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);
      }
      return 1;
    default:
      abort();
    }
  }

  for (index = optind; index < argc; index++) {
    printf("Non-option argument %s\n", argv[index]);
  }

  // setup logging now
  setlogmask(LOG_UPTO(LOG_DEBUG));
  openlog(PROG_ID, LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);
  syslog(LOG_NOTICE, "%s starting", PROG_ID);

  if (cvalue){
    parse_file(cvalue);
  }
  else {
    parse_file(FILE_PATH);
  }

  if (setup_server() < 0) {
    syslog(LOG_ERR, "%s exiting [setup_server() failed]", PROG_ID);
    exit(EXIT_FAILURE);
  }

  // should we run as a daemon
  if (dflag) {
    if (daemon(0,0) < 0) {
      syslog(LOG_ERR, "error creating daemon: %s", strerror(errno));
      exit(EXIT_FAILURE);
    }
  }
  else {
    print_config();
    printf("-------\n");
    printItemsList();
    printf("\t\t-------\n");
  }

  start_agent();

  return 0;
}
Exemplo n.º 22
0
/* Main Engine.
 * Coordinates all the required setup, sending & receiving from users
 */
void
Server::start () {
	// client address structure (to be recieved)
	struct sockaddr_in client;
	socklen_t client_len = sizeof (struct sockaddr_storage);

	// message structure
	im_message msg;
	size_t msg_len = sizeof (msg);

	cout << "Server: Starting... \n";

	// Setup server
	if (!setup_server ()) {
		cerr << "Server: Setup Failed\n ";
		return;
	}

	cout << "Server: Start Successful\n";

	// receive message from users
	while (1) {
		int len = 0;
		memset (&msg, 0, sizeof (msg));

		len = recvfrom (master_socket, &msg, msg_len, 0,
			(struct sockaddr *) &client, &client_len);

		if (len == -1) continue;
		else if (len != msg_len) {
			// Some problem in the message sent
			cerr << "Some problem occurred in sending the message\n";
		}
		
		else {
#ifdef _DEBUG_
			char host[NI_MAXHOST], service[NI_MAXSERV];
			int s = getnameinfo ((struct sockaddr *) &client, client_len, host, NI_MAXHOST, service, NI_MAXSERV, NI_NUMERICSERV);

			if (s == 0)
				printf ("Received %d bytes from %s:%s\n",
						len, host, service);
			else 
				fprintf (stderr, "getaddrnameinfo: %s\n", gai_strerror (s));
#endif

			// check the type of message received
			if (msg.type == REGISTRATION_MESSAGE) {
				// register the user
				if (!register_user (&msg, &client)) 
					cerr << "Server: cannot register the user " << msg.from << endl;
				else 	cout << "Server: registered user " << msg.from << endl;
			}

			else if (msg.type == DEREGISTRATION_MESSAGE) {
				// deregister the user
				if (!deregister_user (&msg, &client)) 
					cerr << "Server: cannot deregister the user " << msg.from << endl;
				else 	cout << "Server: deregistered user " << msg.from << endl;
			}

			else {
				// instant message
				if (!send_instant_msg (&msg, &client)) {
					cerr << "Server: cannot send message from " << msg.from;
			       		cerr << "to " << msg.to << endl;
				} else {
					cout << "Server:  message sent from " << msg.from;
			       		cout << " to " << msg.to << endl;
				}
			 }
		}
	}
}
Exemplo n.º 23
0
int main(int argc, char **argv)
{
    const char *bind_addr = NULL;
    const char *port = NULL;
    const char *dest = NULL;
#ifdef ENABLE_FORK
    int daemonize = 0;
#endif
#ifdef ENABLE_CHGUSER
    const char *user = NULL;
#endif

    (void)argc; /* unused */
    while(*(++argv) != NULL)
    {
        if(strcmp(*argv, "-h") == 0 || strcmp(*argv, "--help") == 0)
        {
            print_help(stdout);
            return 0;
        }
        else if(strcmp(*argv, "-b") == 0 || strcmp(*argv, "--bind") == 0)
        {
            if(bind_addr != NULL)
            {
                fprintf(stderr, "Error: --bind was passed multiple times\n");
                return 1;
            }
            if(*(++argv) == NULL)
            {
                fprintf(stderr, "Error: missing argument for --bind\n");
                return 1;
            }
            bind_addr = *argv;
        }
        else if(strcmp(*argv, "-p") == 0 || strcmp(*argv, "--port") == 0)
        {
            if(port != NULL)
            {
                fprintf(stderr, "Error: --port was passed multiple times\n");
                return 1;
            }
            if(*(++argv) == NULL)
            {
                fprintf(stderr, "Error: missing argument for --port\n");
                return 1;
            }
            port = *argv;
        }
        else if(strcmp(*argv, "-d") == 0 || strcmp(*argv, "--daemon") == 0)
        {
#ifdef ENABLE_FORK
            daemonize = 1;
#else
            fprintf(stderr, "Error: --daemon is not available\n");
            return 1;
#endif
        }
        else if(strcmp(*argv, "-u") == 0 || strcmp(*argv, "--user") == 0)
        {
#ifdef ENABLE_CHGUSER
            if(user != NULL)
            {
                fprintf(stderr, "Error: --user was passed multiple times\n");
                return 1;
            }
            if(*(++argv) == NULL)
            {
                fprintf(stderr, "Error: missing argument for --user\n");
                return 1;
            }
            user = *argv;
#else
            fprintf(stderr, "Error: --user is not available\n");
            return 1;
#endif
        }
        else
        {
            if(dest != NULL)
            {
                fprintf(stderr, "Error: multiple destinations specified\n");
                return 1;
            }
            dest = *argv;
        }
    }

    if(port == NULL)
        port = "80";

    if(dest == NULL)
    {
        fprintf(stderr, "Error: no destination specified\n");
        return 1;
    }

#ifdef __WIN32__
    {
        /* Initializes WINSOCK */
        WSADATA wsa;
        if(WSAStartup(MAKEWORD(1, 1), &wsa) != 0)
        {
            fprintf(stderr, "Error: can't initialize WINSOCK\n");
            return 3;
        }
    }
#endif

    {
        int serv_sock;

        /* Poor man's exception handling... */
        int ret = setup_server(&serv_sock, bind_addr, port);
        if(ret != 0)
            return ret;

#ifdef ENABLE_CHGUSER
        if(user != NULL)
        {
            struct passwd *pwd = getpwnam(user);
            if(pwd == NULL)
            {
                fprintf(stderr, "Error: user %s is unknown\n", user);
                return 2;
            }
            if(setresuid(pwd->pw_uid, pwd->pw_uid, pwd->pw_uid) == -1)
            {
                fprintf(stderr, "Error: can't change user to %s\n", user);
                return 2;
            }
        }
#endif

#ifdef ENABLE_FORK
        if(daemonize)
        {
            switch(fork())
            {
            case -1:
                perror("Error: fork() failed");
                break;
            case 0:
                /* child: go on... */
                fclose(stdin);
                fclose(stdout);
                fclose(stderr);
                break;
            default:
                /* parent: exit with success */
                return 0;
                break;
            }
        }
#endif

        ret = serve(serv_sock, dest);
        my_closesocket(serv_sock);
        return ret;
    }
}
Exemplo n.º 24
0
PROCESS_THREAD(tftpd_process, ev, data)
{
    static struct etimer t;
    static tftp_header *h;
    static int len, block, ack;
    static int tries;
    static int fd = -1;
#if WITH_EXEC
    static char *elf_err;
#endif

    PROCESS_BEGIN();

    etimer_set(&t, CLOCK_CONF_SECOND*3);
    PROCESS_WAIT_EVENT_UNTIL(ev == PROCESS_EVENT_TIMER);

    setup_server();
#if WITH_EXEC
    elfloader_init();
#endif

	print_local_addresses();

    while(1) {
        /* connection from client */
        RECV_PACKET(h);
        len = 0;
        init_config();

        if(h->op == uip_htons(TFTP_RRQ)) {
            connect_back();
            PRINTF("< rrq for %s\n", h->filename);
            len += strlen(h->filename)+1;

            if(strcmp("octet", h->filename+len)) {
                send_error(EUNDEF, "only octet mode supported");
                goto close_connection;
            }
            len += strlen(h->filename+len)+1; /* skip mode */

            parse_opts(h->options+len, uip_datalen()-len-2);

            if(config.to_ack & OACK_ERROR) {
                send_error(EOPTNEG, "");
                goto close_connection;
            } 

            fd = cfs_open(h->filename, CFS_READ);
            if(fd<0) {
                send_error(ENOTFOUND, "");
                goto close_connection;
            }

            block = 0; ack = 0;
            tries = TFTP_MAXTRIES;

            PRINTF("starting transfer...\n");

            for(;;) {
                if(send_oack())
                    len = config.blksize; /* XXX hack to prevent loop exit*/
                else
                    len = send_data(fd, block+1);

                if(len<0) {
                    send_error(EUNDEF, "read failed");
                    goto close_file;
                }

                RECV_PACKET_TIMEOUT(h,t);

                if(ev == PROCESS_EVENT_TIMER) {
                    PRINTF("ack timed out, tries left: %d\n", tries);
                    if(--tries<=0) goto close_file;
                    continue;
                }

                if(h->op != uip_htons(TFTP_ACK)) {
                    send_error(EBADOP, "");
                    goto close_file;
                }

                config.to_ack = 0;
                tries = TFTP_MAXTRIES;
                ack = uip_htons(h->block_nr);
                if(ack == block+1) block++;

                if(len < config.blksize && ack == block) goto done;
            }
        }
        
        else if(h->op == uip_htons(TFTP_WRQ)) {
            connect_back();
            PRINTF("< wrq for %s\n", h->filename);
            len += strlen(h->filename)+1;
            strncpy(config.filename, h->filename, sizeof(config.filename)-1);

            if(strcmp("octet", h->filename+strlen(h->filename)+1)) {
                send_error(EUNDEF, "only octet mode supported");
                goto close_connection;
            }
            len += strlen(h->filename+len)+1; /* skip mode */

            parse_opts(h->options+len, uip_datalen()-len-2);

            if(config.to_ack & OACK_ERROR) {
                send_error(EOPTNEG, "");
                goto close_connection;
            } 

            cfs_remove(h->filename);
            fd = cfs_open(h->filename, CFS_WRITE);
            if(fd<0) {
                send_error(EACCESS, "");
                goto close_connection;
            }

            block = 0; ack = 0;
            tries = TFTP_MAXTRIES;

            PRINTF("starting transfer...\n");

            if(!send_oack())
                send_ack(block);

            for(;;) {
                RECV_PACKET_TIMEOUT(h,t);

                if(ev == PROCESS_EVENT_TIMER) {
                    PRINTF("data timed out, tries left: %d\n", tries);
                    if(--tries<=0) goto close_file;
                    len = config.blksize; /* XXX hack to prevent loop exit*/
                    goto resend_ack;
                }

                if(h->op != uip_htons(TFTP_DATA)) {
                    send_error(EBADOP, "");
                    goto close_file;
                }

                config.to_ack = 0;
                tries = TFTP_MAXTRIES;
                ack = uip_htons(h->block_nr);
                if(ack != block+1) continue;
                /* else */ block++;

                len = recv_data(fd, block);
                if(len<0) {
                    send_error(EUNDEF, "write failed");
                    goto close_file;
                }

#if WITH_EXEC
                if(len < config.blksize) {
                    if(config.exec) {
                        if(exec_file(config.filename, &elf_err) != 0) {
                            send_error(EUNDEF, elf_err);
                            goto close_file;
                        }
                    }
                }
#endif

resend_ack:

                if(!send_oack())
                    send_ack(block);

                if(len < config.blksize) goto done;
            }
        }

done:
            PRINTF("done.\n");

close_file:
        if(fd>=0)
            cfs_close(fd);
        fd = -1;

close_connection:
        if(client_conn)
            uip_udp_remove(client_conn);
        client_conn = 0;

        PRINTF("connection closed.\n");
    } 
    PROCESS_END();
}
Exemplo n.º 25
0
void
setup_output()
{
    char hdr[1024];
    hdr[sizeof(hdr)-1] = 0;
    hdr[0] = 0;

    lastBytesRead = pcm->bytesRead();
    lastBytesWritten = pcm->bytesWritten();
    threadspercore = new int[gbl.ncores];
    labels[fThreads].max = gbl.ncpus;
    labels[fInst].max = gbl.ncores * 4 * gbl.hz;
    labels[fFlopsSP].max = gbl.ncores * 8 * 2 * gbl.hz;
    labels[fFlopsDP].max = gbl.ncores * 4 * 2 * gbl.hz;

    hdrLabels[0] = "Time";
    hdrLabels[1] = "Threads";
    hdrIndexes[0] - fTime;
    hdrIndexes[1] = fThreads;
    int j = 2;
    for (int i = 0; i < nfields; ++i)
        if (i != fTime && i != fThreads)
        {
            hdrLabels[j] = labels[i].name;
            hdrIndexes[j] = i;
            ++j;
        }
    bool first = true;
    for (int i = 0; i < nfields; ++i)
    {
        if (first)
            first = false;
        else
            strncat(hdr, ",", sizeof(hdr)-1);
        strncat(hdr, hdrLabels[i], sizeof(hdr)-1);
    }
    strncat(hdr, "\n", sizeof(hdr)-1);

    if (gbl.server)
    {
        setup_server();
    }
    else if (gbl.outfile)
    {
        outfile = fopen(gbl.outfile, "w");
        if (outfile == NULL)
            err(1, "create %s", gbl.outfile);
    }

    gbl.hdr[0] = 0;
    gbl.hdr[sizeof(gbl.hdr)-1] = 0;
    if (gbl.server)
    {
        for (int i = 0; i < nfields; ++i)
            if (i != fTime)
                snprintf(gbl.hdr+strlen(gbl.hdr), sizeof(gbl.hdr)-1,
                    "%s=%g,%s,%g\n",
                    labels[i].name,
                    labels[i].max,
                    labels[i].units,
                    labels[i].factor);
        strncat(gbl.hdr, hdr, sizeof(gbl.hdr)-1);
    }
    else if (outfile)
    {
        for (int i = 0; i < nfields; ++i)
            if (i != fTime)
                fprintf(outfile, "%s=%g,%s,%g\n",
                    labels[i].name,
                    labels[i].max,
                    labels[i].units,
                    labels[i].factor);
        fprintf(outfile, hdr);
    }

    starttsc = _rdtsc();
}
Exemplo n.º 26
0
int main( void )
{
	
	int* connfd;
	struct sockaddr_in cliaddr;
	socklen_t clilen;
	pthread_t mythread;
	int n, index;
	char buffer[1000];	
	char* banner = "Hello This is the server Please enter your name: "; 
	char* banner2 = "SORRY....chat room is full, So you have to wait until you get the chance....\n "; 
	
	/* Install signal handler for SIGINT */
	signal(SIGINT,cleanup);
	
	listenfd = setup_server();						

	listen(listenfd,MAXCLIENTS);

	clilen = sizeof(cliaddr);
	
	/* Initialise any synchronisation variables like mutexes, attributes and memory */
		

	while(!quit){
				
		/* Accept an incoming connection  */
		
		connfd = malloc(sizeof(int));
		*connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);		
		
		/** find the next free index **/
		index = next_free(); 
		
		if(index == -1){
			send(*connfd,banner2,strlen(banner2),0);
			close(*connfd);
			
		}
		
		else{
		
		send(*connfd,banner,strlen(banner),0);
		
		n = recv(*connfd,buffer,MAXMSG,0);
		
		buffer[n]=0;
			
		/* Allocate and set up new client_t struct in clients array */
		
		clients[index] = malloc(sizeof(client_t));
		clients[index]->index = index;
		clients[index]->sd = *connfd;
		clients[index]->name = buffer;
		
		/** threads are created here **/	
		if ( pthread_create( &mythread, NULL, handle_client, connfd) ){
				printf("error creating thread.");
				abort();
		}
		
		clients[index]->tid = mythread;
				
		
		/* Create a DETACHED thread to handle the new client until the quit is set */
		}
	}

	puts("Shutting down client connections...\n");
	close(listenfd);
	
	return 0;
}
Exemplo n.º 27
0
//----------------------- funcao principal do programa ------------------------
int main(int argc, char *argv[])
{
	// usa porta predefinida
	port = SERVERPORT;

	// configura socket do servidor
	setup_server();
	
	// inicializa estrutura para verificacao de eventos de leitura no socket
	int pollret;	
	for (pollret = 0; pollret < MAXCONCLIENTS; pollret++)
	{
		sockets[pollret].fd = -1;
		sockets[pollret].events = POLLIN | POLLPRI;
	}
	
	conclients = 0;
	// thread p aguardar e estabelecer novas conexoes...
	if (pthread_create(&thread, NULL, acceptconnections, 0))
		fatal("thread_creation: %s.", strerror(errno));	
	
	// recebe mensagens dos clientes e as reenvia para todos os clientes 
	// conectados, enquanto houver clientes conectados 
	msg_t *msg;
	msg = (msg_t *) malloc (sizeof (msg_t));
	int count;
	do {
		// aguarda por evento nos sockets
		while (!conclients || !(pollret = poll(sockets, conclients, 1000)));
		
		// verifica os eventos ocorridos nos sockets dos clientes
		for (count = 0; count < conclients; count++)
		{
			msg->msgtype = Message;

			// se ha conteudo a ser lido no socket
			if ( (sockets[count].revents & POLLIN) ||
			     (sockets[count].revents & POLLPRI))
			{
				// recebe msg do cliente e reenvia a todos
				recv(sockets[count].fd, msg, sizeof(msg_t), 0);
				if (msg->msgtype != Logout)
				{
					printf("%s envia: %s\n", msg->user, msg->msgbuff);
					sendtoall(msg);
				}
			}

			// se cliente solicitou logout ou ocorreu erro com seu socket
			if ( (sockets[count].revents & POLLHUP) ||
			     (sockets[count].revents & POLLNVAL) || 
			     msg->msgtype == Logout )
			{
				// gera msg para avisar sobre a saida do usuario
				printf("Usuario '%s' desconectou-se.\n", conusers[count]);
				strcpy(msg->user, "SERVER");
				strcpy(msg->msgbuff, "Usuario '");
				strcat(msg->msgbuff, conusers[count]);
				strcat(msg->msgbuff, "' desconectou-se.");
				msg->msgtype = Message;
				// remove usuario
				removeclientat(count);
				// informa os demais da saida do usuario
				sendtoall(msg);
				// cliente desconectado, retorna o contador
				count--;
				// se nao ha clientes conectados, finaliza o servidor
				if (!conclients)
					conclients = -1;
			}
		}
	} while (conclients != -1);

	// encerra o socket do servidor
	close(serversock);

	return 0;
}
Exemplo n.º 28
0
void Socket::before_fork()
{
    setup_server();
}
Exemplo n.º 29
0
int main() {
  int listening_socket, client_socket, e;

  struct sigaction action = {
    .sa_handler = sighandler,
    .sa_flags = 0
  };
  sigemptyset(&action.sa_mask);

  sigaction(SIGINT, &action, NULL);

  int listener = 1;

  listening_socket = setup_server(PORT);
  if (listening_socket < 0) {
    perror("Error setting up server");
    exit(-1);
  }

  struct user client;

  while (running) {
    if (listener) {
      printf("<server> listening on %d\n", PORT);
      client_socket = accept(listening_socket, NULL, NULL); // blocks here on connection
      e = handshake(client_socket, &client);
      printf("<server> connected: %s\n", client.name);
      fflush(stdout);
      listener = fork();
      if (listener) {
        close(client_socket);
      } else {
        close(listening_socket);
      }
    } else {
      e = handle_request(client_socket, client);
      if (e < 0) {
        running = 0;
      }
    }
  }

  if (listener) {
    close(listening_socket);
  } else {
    remove(client.name);
    struct signal sig = new_disconnect_sig();
    write(client_socket, &sig, sizeof(sig));
    close(client_socket);
  }

  return 0;
}

int setup_server(int port) {
  int listening_socket, e;

  listening_socket = socket(AF_INET, SOCK_STREAM, 0);
  if (listening_socket < 0) return listening_socket;

  struct sockaddr_in listener = {
    .sin_family = AF_INET,   // socket type IPv4
    .sin_port = htons(port), // port #
    .sin_addr.s_addr = INADDR_ANY
  };

  e = bind(listening_socket, (struct sockaddr *)&listener, sizeof(listener));
  if (e < 0) return e;

  e = listen(listening_socket, 1);
  if (e < 0) return e;

  return listening_socket;
}

int fetch_a_message(int socket_id, char *pipe_path, struct signal* sig) {
  int e;

  int pipe_id = open(pipe_path, O_RDONLY | O_NONBLOCK);
  if (pipe_id < 0) return -1;

  fd_set fd;
  FD_ZERO(&fd);
  FD_SET(socket_id, &fd);
  FD_SET(pipe_id, &fd);
  int m = socket_id > pipe_id ? socket_id : pipe_id;

  select(m+1, &fd, NULL, NULL, NULL);

  if ( FD_ISSET(socket_id, &fd) ) {
    e = read(socket_id, sig, sizeof(*sig));
  } else if ( FD_ISSET(pipe_id, &fd) ){
    e = read(pipe_id, sig, sizeof(*sig));
  } else {
    e = 0;
  };

  close(pipe_id);

  return e;
}
Exemplo n.º 30
0
void ICACHE_FLASH_ATTR init_done() {
    setup_server();
}