Exemplo n.º 1
0
Net::Net(){
  // Initialize Ethernet
  byte mac[]={
    0x90, 0xA2, 0xDA, 0x0D, 0x02, 0xD0    };
  IPAddress ip(192,168,1, 77);
  IPAddress dns(192,168,1, 1);
  IPAddress gateway(192,168,1, 1);
  IPAddress subnet(255,255,255,0);
  Ethernet.begin(mac, ip, dns, gateway, subnet);
  // Processors
  processor=NULL;
  processorCount=0;
  // Enable interrupts
  EthernetInterrupt::begin(0);
}
Exemplo n.º 2
0
bool AtDrv::setApSSID(char *ssid, int type, const char *password)
{
	bool ret = false;
	IPAddress ipStart(192, 168, 43, 100);
	IPAddress ipEnd(192, 168, 43, 200);
	IPAddress mask(255, 255, 255, 0);
	IPAddress gateway(192, 168, 43, 1);
	IPAddress dns1(192, 168, 43, 1);
	IPAddress dns2(8, 8, 8, 8);
	IPAddress netIp(192, 168, 43, 1);

	if(!isAtMode()) {
		if(!switchToAtMode()) {
			INFO1("Can't switch to at mode");
			goto end;
		}
	}
	
	if(!setNetMode(NET_MODE_WIFI_AP))
		goto end;
	
	if(!setWiFiConfig(ssid, type, password))
		goto end;
    
 	if(!setDhcpd(true))
		goto end;
    
 	if(!setDhcpdIp(ipStart, ipEnd, mask, gateway))
		goto end;
    
 	if(!setDhcpdDns(dns1, dns2))
		goto end;  

 	if(!setDhcpdTime(86400))
		goto end;
    
 	if(!setNetIp(netIp, mask, gateway))
		goto end;
    
 	if(!setNetDns(dns1, dns2))
		goto end;      

	netCommit();

	ret = true;
end:
	return ret;
}
Exemplo n.º 3
0
/**
 *  @brief 根据URL,获取要连接主机的IP地址和端口号
 *  @param aUri 请求的URL信息
 *  @return void 
 */
void CSocketEngine::WeaveUrl(const TDesC8& aUriOld){
  iSocketId=0;
  iData1.Zero();
  TPtrC8 x_online_host;//得到主机字符串 
  HBufC8* hUri=HBufC8::NewL(aUriOld.Length()+512);
  TPtr8 aUri(hUri->Des());
  aUri.Copy(aUriOld);
  DeleteBlank(aUri);
  if(aUri.FindF(_L8("http://"))!=KErrNotFound) x_online_host.Set(aUri.Mid(7));//"http://"以后的字符串 host:80/dir/file
  else x_online_host.Set(aUri);
  if(x_online_host.Find(_L8("/"))!=KErrNotFound) iAddress.Copy(x_online_host.Mid(x_online_host.Find(_L8("/")),x_online_host.Length()-(x_online_host.Find(_L8("/")))));
  else iAddress.Copy(_L8("/"));
  // iAddress:  /dir/file

  HBufC* hHost=HBufC::NewL(x_online_host.Length()+512);
  TPtr bufHost(hHost->Des());
  TBuf8<16> bufPort;
  TInt port;
  
  if(x_online_host.Find(_L8("/"))!=KErrNotFound) iHostName.Copy(x_online_host.Left(x_online_host.Find(_L8("/"))));
  else iHostName.Copy(x_online_host);
  if(iHostName.Find(_L8(":"))!=KErrNotFound){
    bufHost.Copy(iHostName.Mid(0,iHostName.Find(_L8(":")))); // 192.168.0.1 or www.3g.cn
    bufPort.Copy(iHostName.Mid(iHostName.Find(_L8(":"))+1,iHostName.Length()-iHostName.Find(_L8(":"))-1));
  }else{
    bufHost.Copy(iHostName);//  192.168.0.1 or www.3g.cn
    iHostName.Append(_L8(":80"));
    bufPort=_L8("80");
  }

  TLex8 ch(bufPort);
  ch.Val(port);
  
  //如果是通过移动网关,则发送请求主机地址为10.0.0.172,真实主机地址放在x_online_host
  if(IsPassWGW){
    TPtrC16 gateway(_L("10.0.0.172"));
    ConnectQServer(gateway,80);
  }else{
    ConnectQServer(bufHost,port);
  }

  preUri.Copy(aUri);
  
  delete hHost;
  delete hUri;
}
Exemplo n.º 4
0
//...............................................................................
//  start STA
//...............................................................................
void WIFI::startSTA() {
  String ssid = ffs.cfg.readItem("wifi_ssid");
  String psk  = ffs.cfg.readItem("wifi_password");
  staMode     = ffs.cfg.readItem("wifi"); // off, dhcp, manual
  apMode      = ffs.cfg.readItem("ap");   // on, off, auto
  IPAddress address(0, 0, 0, 0);
  IPAddress gateway(0, 0, 0, 0);
  IPAddress netmask(0, 0, 0, 0);
  IPAddress dns(0, 0, 0, 0);

  //if (ssid != "") validSSID = true; else validSSID = false;
  validSSID = ssid != "" ? true : false;

  WiFi.softAPdisconnect(true);
  WiFi.mode(WIFI_STA);

  if (staMode == "dhcp") {
    logging.info("WiFi staMode=dhcp");
  } else { // switch to static mode
    address.fromString(ffs.cfg.readItem("wifi_ip"));
    gateway.fromString(ffs.cfg.readItem("wifi_gateway"));
    netmask.fromString(ffs.cfg.readItem("wifi_netmask"));
    dns.fromString(ffs.cfg.readItem("wifi_dns"));
    logging.info("WiFi staMode=manual");
    logging.debug("  IP address: " + address.toString());
    logging.debug("  gateway:    " + gateway.toString());
    logging.debug("  netmask:    " + netmask.toString());
    logging.debug("  DNS server: " + dns.toString());

    if (WiFi.config(address, gateway, netmask, dns)) {
      logging.debug("WiFi configuration applied");
      // logging.info("local IP address switched to: " +
      // WiFi.localIP().toString());
    } else {
      logging.error("could not apply WiFi configuration");
    }
  }

  logging.info("try to connect to SSID: " + ssid);
  WiFi.begin(ssid.c_str(), psk.c_str());
}
Exemplo n.º 5
0
void
get_route(int socket, route_entry &route)
{
	union {
		route_entry request;
		uint8 buffer[512];
	};

	request = route;

	if (ioctl(socket, SIOCGETRT, buffer, sizeof(buffer)) < 0) {
		fprintf(stderr, "%s: Could not get route: %s\n",
			kProgramName, strerror(errno));
		return;
	}

	// find family
	const address_family *family = NULL;
	for (int32 i = 0; kFamilies[i].family >= 0; i++) {
		if (route.destination->sa_family == kFamilies[i].family) {
			family = &kFamilies[i];
			break;
		}
	}

	if (family != NULL) {
		BNetworkAddress destination(*request.destination);
		BNetworkAddress mask(*request.mask);
		printf("%s", destination.ToString().String());
		printf("/%zd ", mask.PrefixLength());

		BNetworkAddress gateway(*request.gateway);
		if (request.flags & RTF_GATEWAY)
			printf("gateway %s ", gateway.ToString().String());

		BNetworkAddress source(*request.source);
		printf("source %s\n", source.ToString().String());
	} else {
		printf("unknown family ");
	}
}
Exemplo n.º 6
0
//...............................................................................
//  start accesspoint
//...............................................................................
void WIFI::startAP(int state) {
  if (state) {
    logging.debug("starting access point");
    //Dl;
    WiFi.mode(WIFI_AP);
    //Dl;
    IPAddress apIP(192,168,4,1);
    IPAddress gateway(192,168,4,1);
    IPAddress subnet(255,255,255,0);
    //Dl;
    String apSSID = ffs.cfg.readItem("ap_ssid");
    String apPSK = ffs.cfg.readItem("ap_password");
    //Dl;

    logging.info("configuring access point");
    logging.debug("  IP address: " + apIP.toString());
    logging.debug("  gateway:    " + gateway.toString());
    logging.debug("  subnet:     " + subnet.toString());
    if (WiFi.softAPConfig(apIP, gateway, subnet)){
      if (WiFi.softAP(apSSID.c_str(), apPSK.c_str())) {
        logging.info("access point is now on");
      } else {
        logging.error("starting access point failed");
      }
    } else {
      logging.error("access point configuration failed");
    }
    if (on_ap_no_stations_connected != nullptr) on_ap_no_stations_connected();

  } else {
    logging.debug("stopping access point");
    WiFi.mode(WIFI_STA);
    WiFi.softAPdisconnect(true);
    logging.info("access point is now off");
  }
}
int main(int argc, char** argv)
{
	bool res = ::wxInitialize();
	if (!res) {
		::fprintf(stderr, "ircddbgatewayd: failed to initialise the wxWidgets library, exiting\n");
		return -1;
	}

	wxCmdLineParser parser(argc, argv);
	parser.AddSwitch(NOLOGGING_SWITCH, wxEmptyString, wxEmptyString, wxCMD_LINE_PARAM_OPTIONAL);
	parser.AddSwitch(DAEMON_SWITCH,    wxEmptyString, wxEmptyString, wxCMD_LINE_PARAM_OPTIONAL);
	parser.AddOption(LOGDIR_OPTION,    wxEmptyString, wxEmptyString, wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL);
	parser.AddOption(CONFDIR_OPTION,   wxEmptyString, wxEmptyString, wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL);
	parser.AddParam(NAME_PARAM, wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL);

	int cmd = parser.Parse();
	if (cmd != 0) {
		::wxUninitialize();
		return 0;
	}

	bool  nolog = parser.Found(NOLOGGING_SWITCH);
	bool daemon = parser.Found(DAEMON_SWITCH);

	wxString logDir;
	bool found = parser.Found(LOGDIR_OPTION, &logDir);
	if (!found)
		logDir.Clear();

	wxString confDir;
	found = parser.Found(CONFDIR_OPTION, &confDir);
	if (!found)
		confDir = CONF_DIR;

	wxString name;
	if (parser.GetParamCount() > 0U)
		name = parser.GetParam(0U);

	if (daemon) {
		pid_t pid = ::fork();

		if (pid < 0) {
			::fprintf(stderr, "ircddbgatewayd: error in fork(), exiting\n");
			::wxUninitialize();
			return 1;
		}

		// If this is the parent, exit
		if (pid > 0)
			return 0;

		// We are the child from here onwards
		::setsid();

		::chdir("/");

		::umask(0);
	}

	CIRCDDBGatewayAppD gateway(nolog, logDir, confDir, name);

	if (!gateway.init()) {
		::wxUninitialize();
		return 1;
	}

	gateway.run();

	::wxUninitialize();
	return 0;
}
Exemplo n.º 8
0
int main(int argc, char *argv[])
{
	int index;
	int c;

	std::string ptp_dev("tun0");
	std::string app_name("tunnel");
	std::string endpoint("dtn:none");
	unsigned int lifetime = 60;
	bool daemonize = false;
	bool stop_daemon = false;
	std::string pidfile;
	bool throughput = false;

#ifdef HAVE_LIBDAEMON
	while ((c = getopt (argc, argv, "td:s:l:hDkp:")) != -1)
#else
	while ((c = getopt (argc, argv, "td:s:l:h")) != -1)
#endif
	switch (c)
	{
#ifdef HAVE_LIBDAEMON
		case 'D':
			daemonize = true;
			break;

		case 'k':
			daemonize = true;
			stop_daemon = true;
			break;

		case 'p':
			pidfile = optarg;
			break;
#endif
		case 'd':
			ptp_dev = optarg;
			break;

		case 't':
			throughput = true;
			break;

		case 's':
			app_name = optarg;
			break;

		case 'l':
			lifetime = atoi(optarg);
			break;

		default:
			print_help(argv[0]);
			return 1;
	}

	int optindex = 0;
	for (index = optind; index < argc; ++index)
	{
		switch (optindex)
		{
		case 0:
			endpoint = std::string(argv[index]);
			break;
		}

		optindex++;
	}

	// print help if not enough parameters are set
	if (!stop_daemon && (optindex < 1)) { print_help(argv[0]); exit(0); }

	// catch process signals
	ibrcommon::SignalHandler sighandler(term);
	sighandler.handle(SIGINT);
	sighandler.handle(SIGTERM);
	sighandler.handle(SIGQUIT);

	//initialize sighandler after possible exit call
	sighandler.initialize();

	// logging options
	//const unsigned char logopts = ibrcommon::Logger::LOG_DATETIME | ibrcommon::Logger::LOG_LEVEL;
	const unsigned char logopts = 0;

	// error filter
	const unsigned char logerr = ibrcommon::Logger::LOGGER_ERR | ibrcommon::Logger::LOGGER_CRIT;

	// logging filter, everything but debug, err and crit
	const unsigned char logstd = ibrcommon::Logger::LOGGER_ALL ^ (ibrcommon::Logger::LOGGER_DEBUG | logerr);

	// syslog filter, everything but DEBUG and NOTICE
	const unsigned char logsys = ibrcommon::Logger::LOGGER_ALL ^ (ibrcommon::Logger::LOGGER_DEBUG | ibrcommon::Logger::LOGGER_NOTICE);

#ifdef HAVE_LIBDAEMON
	if (daemonize) {
		// enable syslog logging
		ibrcommon::Logger::enableSyslog(argv[0], LOG_PID, LOG_DAEMON, logsys);
	} else
#endif
	{
		// add logging to the cout
		ibrcommon::Logger::addStream(std::cout, logstd, logopts);

		// add logging to the cerr
		ibrcommon::Logger::addStream(std::cerr, logerr, logopts);
	}

#ifdef HAVE_LIBDAEMON
	if (daemonize)
	{
#ifdef HAVE_DAEMON_RESET_SIGS
		/* Reset signal handlers */
		if (daemon_reset_sigs(-1) < 0) {
			IBRCOMMON_LOGGER_TAG("Core", error) << "Failed to reset all signal handlers: " << strerror(errno) << IBRCOMMON_LOGGER_ENDL;
			return 1;
		}

		/* Unblock signals */
		if (daemon_unblock_sigs(-1) < 0) {
			IBRCOMMON_LOGGER_TAG("Core", error) << "Failed to unblock all signals: " << strerror(errno) << IBRCOMMON_LOGGER_ENDL;
			return 1;
		}
#endif
		pid_t pid;

		/* Set identification string for the daemon for both syslog and PID file */
		daemon_pid_file_ident = daemon_log_ident = daemon_ident_from_argv0(argv[0]);

		/* set the pid file path */
		if (pidfile.length() > 0) {
			__daemon_pidfile__ = new char[pidfile.length() + 1];
			::strcpy(__daemon_pidfile__, pidfile.c_str());
			daemon_pid_file_proc = __daemon_pid_file_proc__;
		}

		/* Check if we are called with -k parameter */
		if (stop_daemon)
		{
			int ret;

			/* Kill daemon with SIGTERM */

			/* Check if the new function daemon_pid_file_kill_wait() is available, if it is, use it. */
			if ((ret = daemon_pid_file_kill_wait(SIGTERM, 5)) < 0)
				IBRCOMMON_LOGGER_TAG("Core", warning) << "Failed to kill daemon: " << strerror(errno) << IBRCOMMON_LOGGER_ENDL;

			return ret < 0 ? 1 : 0;
		}

		/* Check that the daemon is not rung twice a the same time */
		if ((pid = daemon_pid_file_is_running()) >= 0) {
			IBRCOMMON_LOGGER_TAG("Core", error) << "Daemon already running on PID file " << pid << IBRCOMMON_LOGGER_ENDL;
			return 1;
		}

		/* Prepare for return value passing from the initialization procedure of the daemon process */
		if (daemon_retval_init() < 0) {
			IBRCOMMON_LOGGER_TAG("Core", error) << "Failed to create pipe." << IBRCOMMON_LOGGER_ENDL;
			return 1;
		}

		/* Do the fork */
		if ((pid = daemon_fork()) < 0) {

			/* Exit on error */
			daemon_retval_done();
			return 1;

		} else if (pid) { /* The parent */
			int ret;

			/* Wait for 20 seconds for the return value passed from the daemon process */
			if ((ret = daemon_retval_wait(20)) < 0) {
				IBRCOMMON_LOGGER_TAG("Core", error) << "Could not recieve return value from daemon process: " << strerror(errno) << IBRCOMMON_LOGGER_ENDL;
				return 255;
			}

			return ret;

		} else { /* The daemon */
			/* Close FDs */
			if (daemon_close_all(-1) < 0) {
				IBRCOMMON_LOGGER_TAG("Core", error) << "Failed to close all file descriptors: " << strerror(errno) << IBRCOMMON_LOGGER_ENDL;

				/* Send the error condition to the parent process */
				daemon_retval_send(1);

				/* Do a cleanup */
				daemon_retval_send(255);
				daemon_signal_done();
				daemon_pid_file_remove();

				return -1;
			}

			/* Create the PID file */
			if (daemon_pid_file_create() < 0) {
				IBRCOMMON_LOGGER_TAG("Core", error) << "Could not create PID file ( " << strerror(errno) << ")." << IBRCOMMON_LOGGER_ENDL;
				daemon_retval_send(2);

				/* Do a cleanup */
				daemon_retval_send(255);
				daemon_signal_done();
				daemon_pid_file_remove();

				return -1;
			}

			/* Send OK to parent process */
			daemon_retval_send(0);
		}
	}
#endif

	IBRCOMMON_LOGGER_TAG("Core", info) << "IBR-DTN IP <-> Bundle Tunnel" << IBRCOMMON_LOGGER_ENDL;

	// create a connection to the dtn daemon
	ibrcommon::vaddress addr("localhost", 4550);
	ibrcommon::socketstream conn(new ibrcommon::tcpsocket(addr));

	try {
		// set-up tun2bundle gateway
		TUN2BundleGateway gateway(app_name, conn, ptp_dev);
		_gateway = &gateway;

		IBRCOMMON_LOGGER_TAG("Core", info) << "Local:  " << app_name << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", info) << "Peer:   " << endpoint << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", info) << "Device: " << gateway.getDeviceName() << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", notice) << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", notice) << "Now you need to set-up the ip tunnel. You can use commands like this:" << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", notice) << "# sudo ip link set " << gateway.getDeviceName() << " up mtu 65535" << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", notice) << "# sudo ip addr add 10.0.0.1/24 dev " << gateway.getDeviceName() << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", notice) << IBRCOMMON_LOGGER_ENDL;

		timer_t timerid;
		struct sigevent sev;

		if (!daemonize && throughput) {
			// enable throughput timer
			signal(SIGRTMIN, timer_display_throughput);

			sev.sigev_notify = SIGEV_SIGNAL;
			sev.sigev_signo = SIGRTMIN;
			sev.sigev_value.sival_ptr = &timerid;

			// create a timer
			timer_create(CLOCK_MONOTONIC, &sev, &timerid);

			// arm the timer
			struct itimerspec its;
			size_t freq_nanosecs = 200000000;
			its.it_value.tv_sec = freq_nanosecs / 1000000000;;
			its.it_value.tv_nsec = freq_nanosecs % 1000000000;
			its.it_interval.tv_sec = its.it_value.tv_sec;
			its.it_interval.tv_nsec = its.it_value.tv_nsec;

			if (timer_settime(timerid, 0, &its, NULL) == -1) {
				IBRCOMMON_LOGGER_TAG("Core", error) << "Timer set failed." << IBRCOMMON_LOGGER_ENDL;
			}
		}

		// destination
		dtn::data::EID eid(endpoint);

		while (m_running)
		{
			gateway.process(eid, lifetime);
		}

		gateway.shutdown();
	} catch (const ibrcommon::Exception &ex) {
		if (m_running) {
			IBRCOMMON_LOGGER_TAG("Core", error) << ex.what() << IBRCOMMON_LOGGER_ENDL;
			return -1;
		}
	}

#ifdef HAVE_LIBDAEMON
	if (daemonize) {
		/* Do a cleanup */
		IBRCOMMON_LOGGER_TAG("Core", info) << "Stopped " << app_name << IBRCOMMON_LOGGER_ENDL;
		daemon_retval_send(255);
		daemon_signal_done();
		daemon_pid_file_remove();
	} else
#endif
	{
		std::cout << std::endl;
	}

	return 0;
}
Exemplo n.º 9
0
int main(int argc, char *argv[])
{
    int option, inotifyfd;
    char *env;
    char *opt_host = NULL;
    char *configfile = NULL;
    char *opt_basedir = NULL;

    env = getenv(ENV_PREFIX"_HOST");
    if ((env != NULL) && (strlen(env) != 0)) {
        if ((opt_host = malloc(strlen(env) + 1)) == NULL) {
            perror("malloc");
            exit(EXIT_FAILURE);
        }
        strcpy(opt_host, env);
        host = opt_host;
    }
    env = getenv(ENV_PREFIX"_SPEED");
    if ((env != NULL) && (strlen(env) != 0)) {
        sscanf(env, "%d", &speed);
    }
    env = getenv(ENV_PREFIX"_CONFIG");
    if ((env != NULL) && (strlen(env) != 0)) {
        if ((configfile = malloc(strlen(env) + 1)) == NULL) {
            perror("malloc");
            exit(EXIT_FAILURE);
        }
        strcpy(configfile, env);
    }
    env = getenv(ENV_PREFIX"_DIR");
    if ((env != NULL) && (strlen(env) != 0)) {
        if ((opt_basedir = malloc(strlen(env) + 1)) == NULL) {
            perror("malloc");
            exit(EXIT_FAILURE);
        }
        strcpy(opt_basedir, env);
        basedir = opt_basedir;
    }

    opterr = 1;
    while (1) {
        option = getopt(argc, argv, "h:s:c:d:");
        if (option == -1)
            break;
        switch (option) {
            case 'h':
                if ((opt_host = malloc(strlen(optarg) + 1)) == NULL) {
                    perror("malloc");
                    exit(EXIT_FAILURE);
                }
                strcpy(opt_host, optarg);
                host = opt_host;
                break;
            case 's':
                sscanf(optarg, "%d", &speed);
                break;
            case 'c':
                if ((configfile = malloc(strlen(optarg) + 1)) == NULL) {
                    perror("malloc");
                    exit(EXIT_FAILURE);
                }
                strcpy(configfile, optarg);
                break;
            case 'd':
                if ((opt_basedir = malloc(strlen(optarg) + 1)) == NULL) {
                    perror("malloc");
                    exit(EXIT_FAILURE);
                }
                strcpy(opt_basedir, optarg);
                basedir = opt_basedir;
                break;
            case '?':
                usage(argv[0]);
                exit(EXIT_FAILURE);
            default:
                break;
        }
    }

    printf("Gateway settings:\n");
    printf("\tHost: %s\n", host);
    printf("\tSpeed: %d\n", speed);
    printf("\tMonitoring device in: %s\n", basedir);
    if (configfile) {
        printf("\tConfig file: %s\n", configfile);
        if (loadports(configfile) < 0) {
            fprintf(stderr, "Warning: using defaults ports instead\n");
        }
    }

    if (addexistingdevices(basedir) < 0) {
        fprintf(stderr, "Warning: already connected device not managed\n");
    }

    if ((inotifyfd = getinotifyfd(basedir)) < 0) {
        fprintf(stderr, "Warning: monitoring disabled");
    }

    gateway(inotifyfd);

    return 0;
}
Exemplo n.º 10
0
int main(int argc, char** argv) {
	//Setting the signals to trigger the cleanup function
	signal(SIGTERM, Cleanup);
	signal(SIGINT, Cleanup);

	//Define and process command line arguments
	std::string log_dir;
	std::string gateway_socket_url;
	bool gateway_socket_url_defined;
	bool nanomsg;

	ArgParse::ArgParser arg_parser("KSync Server - Server side of a Client-Server synchonization system using rsync.");
	KSync::Utilities::set_up_common_arguments_and_defaults(arg_parser, log_dir, gateway_socket_url, gateway_socket_url_defined, nanomsg);

	int status;
	if((status = arg_parser.ParseArgs(argc, argv)) < 0) {
		printf("Problem parsing arguments\n");
		arg_parser.PrintHelp();
		return -1;
	}

	if(arg_parser.HelpPrinted()) {
		return 0;
	}

	if (log_dir == "") {
		if(KSync::Utilities::get_user_ksync_dir(log_dir) < 0) {
			printf("There was a problem getting the ksync user directory!\n");
			return -2;
		}
	}

	//Initialize logging:
	std::unique_ptr<g3::LogWorker> logworker;
	KSync::InitializeLogger(logworker, true, "KSync Server", log_dir);

	//Get gateway URL
	if (KSync::Utilities::GetGatewaySocketURL(gateway_socket_url, gateway_socket_url_defined) < 0) {
		LOGF(SEVERE, "There was a problem getting the gateway socket URL!");
		return -2;
	}

	LOGF(INFO, "Using the following socket url: %s", gateway_socket_url.c_str());

	//Initialize communication system
	std::shared_ptr<KSync::Comm::CommSystemInterface> comm_system;
	if (KSync::Utilities::GetCommSystem(comm_system, nanomsg) < 0) {
		LOGF(SEVERE, "There was a problem initializing the comm system!");
		return -2;
	}

	//Initialize command system
	std::shared_ptr<KSync::Commanding::SystemInterface> command_system(new KSync::Commanding::PSCommandSystem());

	//Initialize Gateway Thread socket
	std::shared_ptr<KSync::Comm::CommSystemSocket> gateway_thread_socket;
	if (comm_system->Create_Pair_Socket(gateway_thread_socket, 10) < 0) {
		LOGF(SEVERE, "There was a problem creating the gateway thread socket!");
		return -3;
	}

	std::string gateway_thread_socket_url;
	if(KSync::Utilities::get_default_gateway_thread_url(gateway_thread_socket_url) < 0) {
		LOGF(SEVERE, "There was a problem getting the default gateway thread socket url!");
		return -4;
	}

	if(gateway_thread_socket->Bind(gateway_thread_socket_url) < 0) {
		LOGF(SEVERE, "There was a problem binding the gateway thread socket!");
		return -5;
	}

	//Launch Gateway Thread
	std::thread gateway(KSync::Server::gateway_thread, comm_system, gateway_thread_socket_url, gateway_socket_url);

	//Acknowledge connection
	std::shared_ptr<KSync::Comm::CommObject> herald_obj;
	status = gateway_thread_socket->Recv(herald_obj);
	if(status == KSync::Comm::CommSystemSocket::Other) {
		LOGF(SEVERE, "Didn't receive connect herald!");
		return -6;
	} else if ((status == KSync::Comm::CommSystemSocket::Timeout)||
	           (status == KSync::Comm::CommSystemSocket::EmptyMessage)) {
		LOGF(SEVERE, "Herald retreive timed out!!!");
		return -7;
	} else {
		if(herald_obj->GetType() == KSync::Comm::SocketConnectHerald::Type) {
			KSync::Comm::SocketConnectAcknowledge ack;
			std::shared_ptr<KSync::Comm::CommObject> ack_obj = ack.GetCommObject();
			status = gateway_thread_socket->Send(ack_obj);
			if(status == KSync::Comm::CommSystemSocket::Other) {
				LOGF(SEVERE, "Couldn't send Acknowledgement!");
				return -7;
			} else if (status == KSync::Comm::CommSystemSocket::Timeout) {
				LOGF(SEVERE, "Retreival of Ack timed out!!");
				return -8;
			}
		} else {
			LOGF(SEVERE, "Didn't get a herald type (%i)!!\n", herald_obj->GetType());
			return -8;
		}
	}

	KSync::Comm::ClientCommunicatorList client_communicators;

	while(!finished) {
		//Check gateway thread
		std::shared_ptr<KSync::Comm::CommObject> recv_obj;
		status = gateway_thread_socket->Recv(recv_obj);
		if(status == KSync::Comm::CommSystemSocket::Other) {
			LOGF(SEVERE,"There was a problem checking the gateway thread socket!");
			return -9;
		} else if (status == KSync::Comm::CommSystemSocket::Timeout) {
		} else if (status == KSync::Comm::CommSystemSocket::EmptyMessage) {
		} else {
			// Handle connection request!!
			if(recv_obj->GetType() == KSync::Comm::GatewaySocketInitializationRequest::Type) {
				LOGF(INFO, "Received a connection request!");
				std::shared_ptr<KSync::Comm::GatewaySocketInitializationRequest> request;
				KSync::Comm::CommCreator(request, recv_obj);
				LOGF(INFO, "Received client id: (%lu)\n",request->GetClientId());
				std::shared_ptr<KSync::Comm::ClientCommunicator> client_communicator = client_communicators.find_first_if(request->GetClientId());
				if(client_communicator == nullptr) {
					LOGF(INFO, "Generating new client socket!");
					//Don't have a client with that ID yet! Handle creation of new socket
					client_communicator.reset(new KSync::Comm::ClientCommunicator(comm_system, request->GetClientId(), true));
					//std::string new_socket_url;
					//if(KSync::Utilities::get_client_socket_url(new_socket_url, request->GetClientId()) < 0) {
					//	LOGF(SEVERE, "Error! Couldn't get the client socket url!");
					//	return -10;
					//}

					//std::shared_ptr<KSync::Comm::CommSystemSocket> client_socket;
					//if (comm_system->Create_Pair_Socket(client_socket) < 0) {
					//	LOGF(SEVERE, "There was a problem creating the gateway thread socket!");
					//	return -10;
					//}

					//if (client_socket->SetRecvTimeout(1000) < 0) {
					//	LOGF(SEVERE, "There was a problem setting the recv timeout!");
					//	return -10;
					//}

					//if(client_socket->Bind(new_socket_url) < 0) {
					//	LOGF(SEVERE, "There was a problem binding the gateway thread socket!");
					//	return -10;
					//}

					client_communicators.push_front(*client_communicator);

					KSync::Comm::ClientSocketCreation socket_message;
					socket_message.SetClientUrl(new_socket_url);
					socket_message.SetBroadcastUrl(broadcast_url);
					std::shared_ptr<KSync::Comm::CommObject> socket_message_obj = socket_message.GetCommObject();
					LOGF(INFO, "Sending new client socket address!");
					status = gateway_thread_socket->Send(socket_message_obj);
					if(status == KSync::Comm::CommSystemSocket::Other) {
						LOGF(SEVERE, "Couldn't send response!");
						return -11;
					} else if (status == KSync::Comm::CommSystemSocket::Timeout) {
						LOGF(SEVERE, "Sending response timed out!!");
						return -12;
					}
				} else {
					//We have a client with that ID!
					LOGF(WARNING, "We already have a client with ID (%lu)!\n", request->GetClientId());
					KSync::Comm::GatewaySocketInitializationChangeId response;
					std::shared_ptr<KSync::Comm::CommObject> resp_obj = response.GetCommObject();
					status = gateway_thread_socket->Send(resp_obj);
					if(status == KSync::Comm::CommSystemSocket::Other) {
						LOGF(SEVERE, "There was a problem sending a response to the gateway thread socket!");
						return -11;
					} else if (status == KSync::Comm::CommSystemSocket::Timeout) {
						LOGF(SEVERE, "Sending response timedout!!");
						return -12;
					}
				}
			} else {
				LOGF(SEVERE, "Unsupported message from gateway thread! (%i) (%s)\n", recv_obj->GetType(), KSync::Comm::GetTypeName(recv_obj->GetType()));
				return -11;
			}
		}

		//Check client sockets
		for(auto client_socket_it = client_sockets.begin(); client_socket_it != client_sockets.end(); ++client_socket_it) {
			//Check for incoming messages
			recv_obj = 0;
			std::shared_ptr<KSync::Comm::CommSystemSocket> client_socket = client_socket_it->second;
			status = client_socket->Recv(recv_obj);
			if(status == KSync::Comm::CommSystemSocket::Other) {
				LOGF(WARNING, "There was a problem receiving a message from a client socket!");
			} else if ((status == KSync::Comm::CommSystemSocket::Timeout)||(status == KSync::Comm::CommSystemSocket::EmptyMessage)) {
			} else {
				if(recv_obj->GetType() == KSync::Comm::CommString::Type) {
					std::shared_ptr<KSync::Comm::CommString> message;
					KSync::Comm::CommCreator(message, recv_obj);
					LOGF(INFO, "Got message (%s)\n", message->c_str());
					std::shared_ptr<KSync::Comm::CommObject> send_obj = message->GetCommObject();
					status = client_socket->Send(send_obj);
					if(status == KSync::Comm::CommSystemSocket::Other) {
						LOGF(WARNING, "There was a problem sending a message on a client socket!");
					} else if (status == KSync::Comm::CommSystemSocket::Timeout) {
						LOGF(WARNING, "Sending a message on a client socket timed out!");
					}
				} else if (recv_obj->GetType() == KSync::Comm::ShutdownRequest::Type) {
					finished = true;
					KSync::Comm::ShutdownAck shutdown_ack;
					std::shared_ptr<KSync::Comm::CommObject> shutdown_obj = shutdown_ack.GetCommObject();
					status = client_socket->Send(shutdown_obj);
					if(status == KSync::Comm::CommSystemSocket::Other) {
						LOGF(WARNING, "There was a problem sending the shutdown ack");
					} else if (status == KSync::Comm::CommSystemSocket::Timeout) {
						LOGF(WARNING, "There was a timeout sending the shutdown ack");
					}
				} else if (recv_obj->GetType() == KSync::Comm::ExecuteCommand::Type) {
					std::shared_ptr<KSync::Comm::ExecuteCommand> exec_com;
					KSync::Comm::CommCreator(exec_com, recv_obj);
					LOGF(INFO, "Received command (%s)\n", exec_com->c_str());

					std::shared_ptr<KSync::Commanding::ExecutionContext> command_context = command_system->GetExecutionContext();
					command_context->LaunchCommand(exec_com->c_str());
					std::string std_out;
					std::string std_err;
					command_context->GetOutput(std_out, std_err);

					KSync::Comm::CommandOutput com_out;
					com_out.SetStdout(std_out);
					com_out.SetStderr(std_err);
					com_out.SetReturnCode(command_context->GetReturnCode());

					std::shared_ptr<KSync::Comm::CommObject> test_resp = com_out.GetCommObject();
					status = client_socket->Send(test_resp);
					if(status != KSync::Comm::CommSystemSocket::Success) {
						LOGF(WARNING, "There was a problem sending the test reponse!");
					}
				}
			}
		}
	}

	// Shutting down
	// Broadcast shutdown message
	KSync::Comm::ServerShuttingDown shutdown_message;
	std::shared_ptr<KSync::Comm::CommObject> shutdown_obj = shutdown_message.GetCommObject();
	status = broadcast_socket->Send(shutdown_obj);
	if(status == KSync::Comm::CommSystemSocket::Other) {
		LOGF(WARNING, "There was a problem sending the shutdown message!");
	} else if (status == KSync::Comm::CommSystemSocket::Timeout) {
		LOGF(WARNING, "There was a timeout sending the shutdown message!");
	} else {
		LOGF(WARNING, "Shutdown sent!");
	}
	// Shutdown gateway thread
	status = gateway_thread_socket->Send(shutdown_obj);
	if(status == KSync::Comm::CommSystemSocket::Other) {
		LOGF(WARNING, "There was a problem closing down the gateway thread!");
	} else if (status == KSync::Comm::CommSystemSocket::Timeout) {
		LOGF(WARNING, "There was a timeout closing down the gateway thread!");
	}
	//Join gateway thread
	gateway.join();
	return 0;
}