bool init_and_export_converters() {

  if (export_type_conversions_once)
    return false;
  
  std::cerr << "PYTHON TYPE CONVERTERS exported" << std::endl;
  export_type_conversions_once = true;

  // Py_Init and array import
  py_init();
  
  // => py::list
  expose_template_type<int>();
  expose_template_type<float>();
  expose_template_type<double>();

  // std::vector => py::list
  expose_template_type< std::vector<int> >();
  expose_template_type< std::vector<float> >();
  expose_template_type< std::vector<double> >();

  expose_template_type< std::vector<cv::Point> >();
  expose_template_type< std::vector<cv::Point2f> >();
  expose_template_type< std::vector<cv::KeyPoint> >();

  expose_template_type<std::vector<std::vector<cv::Point2f> > >();
  
  expose_template_type< std::vector<cv::Mat> >();
  expose_template_type< std::vector<cv::Mat1b > >();
  expose_template_type< std::vector<cv::Mat1f > >();

  // std::map => py::dict
  expose_template_type<std::map<int, std::vector<int> > >();
  expose_template_type<std::map<int, std::vector<float> > >();
  expose_template_type<std::map<std::string, float> >();

  // various converters to cv::Mat
  py::to_python_converter<cv::Point, Point_to_mat>();
  py::to_python_converter<cv::Point2f, Point2f_to_mat>();
  py::to_python_converter<cv::Point3f, Point3f_to_mat>();
  py::to_python_converter<cv::Vec3f, Vec3f_to_mat>();

  // register the to-from-python converter for each of the types
  Mat_PyObject_converter< cv::Mat >();
  
  // 1-channel
  Mat_PyObject_converter< cv::Mat1b >();
  Mat_PyObject_converter< cv::Mat1s >();
  Mat_PyObject_converter< cv::Mat1w >();
  Mat_PyObject_converter< cv::Mat1i >();
  Mat_PyObject_converter< cv::Mat1f >();
  Mat_PyObject_converter< cv::Mat1d >();

  // 2-channel
  Mat_PyObject_converter< cv::Mat2b >();
  Mat_PyObject_converter< cv::Mat2s >();
  Mat_PyObject_converter< cv::Mat2w >();
  Mat_PyObject_converter< cv::Mat2i >();
  Mat_PyObject_converter< cv::Mat2f >();
  Mat_PyObject_converter< cv::Mat2d >();

  // 3-channel
  Mat_PyObject_converter< cv::Mat3b >();
  Mat_PyObject_converter< cv::Mat3s >();
  Mat_PyObject_converter< cv::Mat3w >();
  Mat_PyObject_converter< cv::Mat3i >();
  Mat_PyObject_converter< cv::Mat3f >();
  Mat_PyObject_converter< cv::Mat3d >();

  // add more if needed

  return true;
}
Beispiel #2
0
int main(int ac, const char** av)
{
  const struct test_desc tests[] =
  {
    /* TEST_DESC(hi), */
    /* TEST_DESC(hix), */
    TEST_DESC(matmul),
    /* TEST_DESC(arr), */
    TEST_DESC_INVALID
  };

  static const size_t n = 10000;

  size_t i;
  size_t j;
  uint64_t ticks[2];
  double us[2];

  if (py_init())
  {
    printf("py_init() error\n");
    return -1;
  }

  for (i = 0; tests[i].name != NULL; ++i)
  {
    const struct test_desc* const t = &tests[i];
    py_handle_t py;

    printf("---");
    printf("--- %s test\n", t->name);

    if (py_open(&py))
    {
      printf("py_open error\n");
      continue ;
    }

    if (py_compile(&py, t->py_str))
    {
      printf("py_compile error\n");
      goto on_close;
    }

    /* add variables */
    if (t->post_compile(&py))
    {
      printf("py_post_compile error\n");
      goto on_close;
    }

    /* execute python version */
    ticks[0] = rdtsc();
    for (j = 0; j != n; ++j)
    {
      /* if (j && ((j % 100) == 0)) py_collect(&py); */

      t->pre_exec(&py);

      if (py_execute(&py))
      {
	printf("py_execute error (%zu)\n", j);
	goto on_close;
      }
    }
    ticks[1] = rdtsc();
    us[0] = (double)ticks_to_us(sub_ticks(ticks[0], ticks[1])) / 1000000.0;

    py_print_out_vars(&py);

    /* execute c version */
    ticks[0] = rdtsc();
    for (j = 0; j != n; ++j)
    {
      t->pre_exec(&py);
      t->c(&py);
    }
    ticks[1] = rdtsc();
    us[1] = (double)ticks_to_us(sub_ticks(ticks[0], ticks[1])) / 1000000.0;

    py_print_out_vars(&py);

    printf("py = %lfus, c = %lfus\n", us[0], us[1]);

  on_close:
    py_close(&py);
  }

  py_fini();

  return 0;
}
Beispiel #3
0
int main(int argc, char *argv[])
{
	char wait_forever = 0, quiet = 0, reconnect = 0, reconnect_wait = 0;
	char *config_search_dirs[3], *plugin_search_dirs[3];
	char *config_filename = DEFAULT_CONFIG_FILE;
	char home_config_dir[HOME_DIR_LEN];
	char home_plugin_dir[HOME_DIR_LEN];
	char *tmp;
	const char *dev_name = NULL;
	int c, i;
	char *str_addr;
	bdaddr_t bdaddr, current_bdaddr;
	sigset_t sigset;
	int signum, ret=0;
	struct uinput_listen_data uinput_listen_data;
	pthread_t uinput_listen_thread;

	init = 1;

	/* Parse Options */
	while (1) {
		int option_index = 0;

		static struct option long_options[] = {
			{"help", 0, 0, 'h'},
			{"version", 0, 0, 'v'},
			{"config", 1, 0, 'c'},
			{"daemon", 0, 0, 'd'},
			{"quiet", 0, 0, 'q'},
			{"reconnect", 2, 0, 'r'},
			{"wait", 0, 0, 'w'},
			{"name", 1, 0, 'n'},
			{0, 0, 0, 0}
		};

		c = getopt_long (argc, argv, "hvc:dqr::wn:", long_options, &option_index);

		if (c == -1) {
			break;
		}

		switch (c) {
		case 'h':
			print_usage();
			return 0;
			break;
		case 'v':
			printf("CWiid Version %s\n", PACKAGE_VERSION);
			return 0;
			break;
		case 'c':
			config_filename = optarg;
			break;
		case 'd':
			wait_forever = 1;
			quiet = 1;
			reconnect = 1;
			break;
		case 'q':
			quiet = 1;
			break;
		case 'r':
			reconnect = 1;
			if (optarg) {
				reconnect_wait = strtol(optarg, &tmp, 10);
				if (*tmp != '\0') {
					wminput_err("bad reconnect wait time");
					return -1;
				}
			}
			break;
		case 'w':
			wait_forever = 1;
			break;
		case 'n':
			dev_name = optarg;
			break;
		case '?':
			printf("Try `wminput --help` for more information\n");
			return 1;
			break;
		default:
			return -1;
			break;
		}
	}

	if (c_init()) {
		return -1;
	}

#ifdef HAVE_PYTHON
	if (py_init()) {
		return -1;
	}
#endif

	/* Load Config */
	/* Setup search directory arrays */
	if ((tmp = getenv("HOME")) == NULL) {
		wminput_err("Unable to find home directory");
		config_search_dirs[0] = WMINPUT_CONFIG_DIR;
		plugin_search_dirs[0] = CWIID_PLUGINS_DIR;
		config_search_dirs[1] = plugin_search_dirs[1] = NULL;
	}
	else {
		snprintf(home_config_dir, HOME_DIR_LEN, "%s/.cwiid/wminput", tmp);
		snprintf(home_plugin_dir, HOME_DIR_LEN, "%s/.cwiid/plugins", tmp);
		config_search_dirs[0] = home_config_dir;
		plugin_search_dirs[0] = home_plugin_dir;
		config_search_dirs[1] = WMINPUT_CONFIG_DIR;
		plugin_search_dirs[1] = CWIID_PLUGINS_DIR;
		config_search_dirs[2] = plugin_search_dirs[2] = NULL;
	}

	if (conf_load(&conf, config_filename, config_search_dirs,
	  plugin_search_dirs, dev_name)) {
		return -1;
	}

	/* Determine BDADDR */
	/* priority: command-line option, environment variable, BDADDR_ANY */
	if (optind < argc) {
		if (str2ba(argv[optind], &bdaddr)) {
			wminput_err("invalid bdaddr");
			bdaddr = *BDADDR_ANY;
		}
		optind++;
		if (optind < argc) {
			wminput_err("invalid command-line");
			print_usage();
			conf_unload(&conf);
			return -1;
		}
	}
	else if ((str_addr = getenv(WIIMOTE_BDADDR)) != NULL) {
		if (str2ba(str_addr, &bdaddr)) {
			wminput_err("invalid address in %s", WIIMOTE_BDADDR);
			bdaddr = *BDADDR_ANY;
		}
	}
	else {
		bdaddr = *BDADDR_ANY;
	}

	sigemptyset(&sigset);
	sigaddset(&sigset, SIGTERM);
	sigaddset(&sigset, SIGINT);
	sigaddset(&sigset, SIGUSR1);

	do {
		bacpy(&current_bdaddr, &bdaddr);

		/* Wiimote Connect */
		if (!quiet) {
			printf("Put Wiimote in discoverable mode now (press 1+2)...\n");
		}
		if (wait_forever) {
			if (!bacmp(&current_bdaddr, BDADDR_ANY)) {
				if (cwiid_find_wiimote(&current_bdaddr, -1)) {
					wminput_err("error finding wiimote");
					conf_unload(&conf);
					return -1;
				}
			}
			/* TODO: avoid continuously calling cwiid_open */
			cwiid_set_err(cwiid_err_connect);
			while (!(wiimote = cwiid_open(&current_bdaddr, CWIID_FLAG_MESG_IFC)));
			cwiid_set_err(cwiid_err_default);
		}
		else {
			if ((wiimote = cwiid_open(&current_bdaddr, CWIID_FLAG_MESG_IFC)) == NULL) {
				wminput_err("unable to connect");
				conf_unload(&conf);
				return -1;
			}
		}
		if (cwiid_set_mesg_callback(wiimote, &cwiid_callback)) {
			wminput_err("error setting callback");
			conf_unload(&conf);
			return -1;
		}

		if (c_wiimote(wiimote)) {
			conf_unload(&conf);
			return -1;
		}
#ifdef HAVE_PYTHON
		if (py_wiimote(wiimote)) {
			conf_unload(&conf);
			return -1;
		}
#endif

		/* init plugins */
		for (i=0; (i < CONF_MAX_PLUGINS) && conf.plugins[i].name; i++) {
			switch (conf.plugins[i].type) {
			case PLUGIN_C:
				if (c_plugin_init(&conf.plugins[i], i)) {
					wminput_err("error on %s init", conf.plugins[i].name);
					conf_unload(&conf);
					cwiid_close(wiimote);
					return -1;
				}
				break;
#ifdef HAVE_PYTHON
			case PLUGIN_PYTHON:
				if (py_plugin_init(&conf.plugins[i], i)) {
					wminput_err("error %s init", conf.plugins[i].name);
					conf_unload(&conf);
					cwiid_close(wiimote);
					return -1;
				}
				break;
#endif
			}
		}

		if (wminput_set_report_mode()) {
			conf_unload(&conf);
			cwiid_close(wiimote);
			return -1;
		}

		uinput_listen_data.wiimote = wiimote;
		uinput_listen_data.conf = &conf;
		if (pthread_create(&uinput_listen_thread, NULL,
		                   (void *(*)(void *))uinput_listen,
		                   &uinput_listen_data)) {
			wminput_err("error starting uinput listen thread");
			conf_unload(&conf);
			cwiid_close(wiimote);
			return -1;
		}

		if (!quiet) {
			printf("Ready.\n");
		}

		init = 0;

		/* wait */
		sigprocmask(SIG_BLOCK, &sigset, NULL);
		sigwait(&sigset, &signum);
		sigprocmask(SIG_UNBLOCK, &sigset, NULL);

		if ((signum == SIGTERM) || (signum == SIGINT)) {
			reconnect = 0;
		}

		if (pthread_cancel(uinput_listen_thread)) {
			wminput_err("Error canceling uinput listen thread");
			ret = -1;
		}
		else if (pthread_join(uinput_listen_thread, NULL)) {
			wminput_err("Error joining uinput listen thread");
			ret = -1;
		}

		c_wiimote_deinit();
#ifdef HAVE_PYTHON
		py_wiimote_deinit();
#endif

		/* disconnect */
		if (cwiid_close(wiimote)) {
			wminput_err("Error on wiimote disconnect");
			ret = -1;
		}

		if (reconnect && reconnect_wait) {
			sleep(reconnect_wait);
		}
	} while (reconnect);

	if (conf_unload(&conf)) {
		ret = -1;
	}

	c_deinit();
#ifdef HAVE_PYTHON
	py_deinit();
#endif

	if (!quiet) {
		printf("Exiting.\n");
	}

	return ret;
}
Beispiel #4
0
//==============================================================================
int main(int argc, char *argv[])
{
  //---------------------------------------------------------------------------
  #ifdef USE_PYTHON_APP
  exec_interactive_interpreter(argc, argv);
  #endif
  //---------------------------------------------------------------------------
  if(argc > 1)
  {
    if((strcmp(argv[1], CMD_S_VERSION) == 0) || ((strcmp(argv[1], CMD_VERSION) == 0)))
    {
      print_version();
      return 0;
    }
    if((strcmp(argv[1], CMD_S_HELP) == 0) || ((strcmp(argv[1], CMD_HELP) == 0)))
    {
      print_help(1);
      return 0;
    }
    if((strcmp(argv[1], CMD_S_CONFIG) == 0) || ((strcmp(argv[1], CMD_CONFIG) == 0)))
    {
      if(read_config() >= ERROR_WARNING)
        log_add_fmt(LOG_ERROR, "main,\nmessage: %s",
                    last_error()->message);
      print_config();
      return 0;
    }
  }
  //---------------------------------------------------------------------------
  print_version();
  //---------------------------------------------------------------------------
  if(read_config() >= LOG_ERROR)
    log_add_fmt(LOG_ERROR, "main,\nmessage: %s",
                last_error()->message);
  print_config();
  //---------------------------------------------------------------------------
  log_add(LOG_INFO, "application started");
  log_add(LOG_INFO, "-------------------");
  //---------------------------------------------------------------------------
  if(sock_init() >= ERROR_NORMAL)
    goto exit;
  //---------------------------------------------------------------------------
  #ifdef USE_PYTHON
  if(py_init() >= ERROR_NORMAL)
    goto exit;
  #endif
  //---------------------------------------------------------------------------
  #ifdef PI_DEVICE
  if(gpio_init() >= ERROR_NORMAL)
    goto exit;
  #endif
  //---------------------------------------------------------------------------
  char command[256];
  if(argc > 1)
  {
    // Read params
    for(int i = 1; i < argc; i++)
    {
      if((strcmp(argv[i], PARAM_S_PORT) == 0) || ((strcmp(argv[i], PARAM_PORT) == 0)))
      {
        cmd_server_port = atoi(argv[++i]);
      }
      else if((strcmp(argv[i], PARAM_S_WEB_PORT) == 0) || ((strcmp(argv[i], PARAM_WEB_PORT) == 0)))
      {
        web_server_port = atoi(argv[++i]);
      }
      else if((strcmp(argv[i], PARAM_S_WS_PORT) == 0) || ((strcmp(argv[i], PARAM_WS_PORT) == 0)))
      {
        ws_server_port = atoi(argv[++i]);
      }
      else if((strcmp(argv[i], PARAM_S_HOST) == 0) || ((strcmp(argv[i], PARAM_HOST) == 0)))
      {
        strcpy((char*)cmd_server_host, argv[++i]);
      }
      else if((strcmp(argv[i], PARAM_S_COUNT) == 0) || ((strcmp(argv[i], PARAM_COUNT) == 0)))
      {
        cmd_clients_count = atoi(argv[++i]);
      }
    }
    // Read cmd
    for(int i = 1; i < argc; i++)
    {
      if((strcmp(argv[i], CMD_S_ALL) == 0) || ((strcmp(argv[i], CMD_ALL) == 0)))
      {
        strcpy(command, CMD_ALL);
      }
      else if((strcmp(argv[i], CMD_S_SERVER) == 0) || ((strcmp(argv[i], CMD_SERVER) == 0)))
      {
        strcpy(command, CMD_SERVER);
      }
      else if((strcmp(argv[i], CMD_S_WEB_SERVER) == 0) || ((strcmp(argv[i], CMD_WEB_SERVER) == 0)))
      {
        strcpy(command, CMD_WEB_SERVER);
      }
      else if((strcmp(argv[i], CMD_S_WS_SERVER) == 0) || ((strcmp(argv[i], CMD_WS_SERVER) == 0)))
      {
        strcpy(command, CMD_WS_SERVER);
      }
      else if((strcmp(argv[i], CMD_S_CLIENT) == 0) || ((strcmp(argv[i], CMD_CLIENT) == 0)))
      {
        strcpy(command, CMD_CLIENT);
      }
    }

    handle_command_str(NULL, command);
  }
  //---------------------------------------------------------------------------
  if(history_load() >= ERROR_NORMAL)
    log_add_fmt(LOG_ERROR, "main,\nmessage: %s",
                last_error()->message);
  log_add(LOG_INFO, "command mode");
  //---------------------------------------------------------------------------
  strcpy(command, "\0");
  while(TRUE)
  {
//    char ch = getcode();
//    if(ch == '\033')
//    {
//      getchar(); // skip the [
//      ch = getchar();
//      switch(ch)
//      {
//        case 'A': // arrow up
//        {
//          strcpy(command, history_prev());
//          break;
//        }
//        case 'B': // arrow down
//        {
//          strcpy(command, history_next());
//          break;
//        }
//      }
//      if(strlen(command) != 0)
//      {
//        printf("%s\n", command);
//        continue;
//      }
//    }

//    if(strlen(command) == 0)
//    {
//      printf("manual input\n");
      fgets(command, sizeof(command), stdin);
      history_add(command);
//    };

    switch(handle_command_str(NULL, command))
    {
      case EXEC_NONE:
      {
        make_last_error(ERROR_NONE, errno, "exit by user command");
        goto exit;
      }
      case EXEC_UNKNOWN:
        log_add_fmt(LOG_CMD, "unknown command: %s",
                    command);
        break;
      case EXEC_DONE:
        log_add_fmt(LOG_CMD, "done command: %s",
                    command);
        break;
    }
    strcpy(command, "\0");
  }
  //---------------------------------------------------------------------------
  exit:
  sock_deinit();
  #ifdef PI_DEVICE
  gpio_close();
  #endif
  //---------------------------------------------------------------------------
  #ifdef USE_PYTHON
  py_final();
  #endif
  //---------------------------------------------------------------------------
  log_add_fmt(LOG_INFO, "application finished, result: %s\n", last_error()->message);
  //---------------------------------------------------------------------------
  return 0;
  //---------------------------------------------------------------------------
}
Beispiel #5
0
int main(int argc, char *argv[])
{
    PIN_Init(argc, argv);
    PIN_InitSymbols();

    py_init();

    pyrun_simple_string("_pin_function_addr = {}");

    char buf[256];
    for (uint32_t idx = 0; idx < ARRAYSIZE(g_functions); idx++) {
        sprintf(buf, "_pin_function_addr['%s'] = "FMTPTR,
            (const char *) g_functions[idx][0],
            (uintptr_t) g_functions[idx][1]);
        pyrun_simple_string(buf);
    }

#if x86
    pyrun_simple_string("x86, x64 = True, False");
#else
    pyrun_simple_string("x86, x64 = False, True");
#endif

#define G(value) \
    sprintf(buf, "%s = %d", #value, value); pyrun_simple_string(buf);

#include "pyn-globals.h"

    // we want to execute pyn.py in the current namespace
    pyrun_simple_string("exec open('pyn.py', 'rb').read()");

    // turns out that IARG_END is a macro which puts IARG_FILE_NAME and
    // IARG_LINE_NO, with their values accordingly, in the argument list as
    // well.. as we take care of this inside our *_InsertCall statements, we
    // can ignore the "real" meaning of IARG_END, and just assign it IARG_LAST
    // TODO actually add some special handling for IARG_END / whatever
    pyrun_simple_string("IARG_END = IARG_LAST");

    // manually parse argv, because KNOB - do you even parse?!
    for (int i = 0, tool_arg_start = -1; i < argc; i++) {
        // end of parameters to our pintool
        if(!strcmp(argv[i], "--")) break;

        // -t specifies our pintool, after that come args to our tool
        if(!strcmp(argv[i], "-t")) {
            tool_arg_start = i + 2;
            continue;
        }

        // check if we're already in the arguments to our tool
        if(tool_arg_start < 0 || i < tool_arg_start) continue;

        // python code injection!!1
        snprintf(buf, sizeof(buf), "exec open('%s', 'rb').read()", argv[i]);
        pyrun_simple_string(buf);
    }

    void *py_globals = NULL, *py_value;
    sprintf(buf, "import ctypes; ctypes.memmove("FMTPTR", "
            "ctypes.byref(ctypes.c_int(id(globals()))), %d)",
            (uintptr_t) &py_globals, sizeof(uintptr_t));
    pyrun_simple_string(buf);

    // generic callback registration function
#define CALLBACK_REG(name, api) \
    g_##name##_callback = pydict_get_item_string(py_globals, #name); \
    if(g_##name##_callback != NULL) { \
        api(&name##_callback, NULL); \
    }

    // callback registration function for callbacks
    // with only one integer as parameter, and which return void
#define CALLBACK_REG1(name, api, cast) \
    py_value = pydict_get_item_string(py_globals, #name); \
    if(py_value != NULL) { \
        api((cast##CALLBACK) &single_int_callback, py_value); \
    }

#define CALLBACK_REG1EX(name, wrapper, api, cast) { \
    static void *_##name##_args[3] = { \
        pyn_callback_helper, \
        pydict_get_item_string(py_globals, #name), \
        pydict_get_item_string(py_globals, #wrapper), \
    }; \
    if(_##name##_args[1] != NULL) { \
        api((cast##CALLBACK) &two_obj_one_int_callback, _##name##_args); \
    }}

    if(py_globals != NULL) {
        void *pyn_callback_helper = pydict_get_item_string(
            py_globals, "_callback_helper");

        CALLBACK_REG1(fini, PIN_AddFiniFunction, FINI_);
        CALLBACK_REG(child, PIN_AddFollowChildProcessFunction);
        CALLBACK_REG1(img_load, IMG_AddInstrumentFunction, IMAGE);
        CALLBACK_REG1EX(img_load2, Image, IMG_AddInstrumentFunction, IMAGE);
        CALLBACK_REG1(img_unload, IMG_AddUnloadFunction, IMAGE);
        CALLBACK_REG1EX(img_unload2, Image, IMG_AddUnloadFunction, IMAGE);
        CALLBACK_REG1(routine, RTN_AddInstrumentFunction, RTN_INSTRUMENT_);
        CALLBACK_REG1EX(routine2, Routine,
            RTN_AddInstrumentFunction, RTN_INSTRUMENT_);
        CALLBACK_REG1(trace, TRACE_AddInstrumentFunction, TRACE_INSTRUMENT_);
        CALLBACK_REG1EX(trace2, Trace,
            TRACE_AddInstrumentFunction, TRACE_INSTRUMENT_);
        CALLBACK_REG1(instr, INS_AddInstrumentFunction, INS_INSTRUMENT_);
        CALLBACK_REG1EX(instr2, Instruction,
            INS_AddInstrumentFunction, INS_INSTRUMENT_);
        CALLBACK_REG(syscall_entry, PIN_AddSyscallEntryFunction);
        CALLBACK_REG(syscall_exit, PIN_AddSyscallExitFunction);
    }

    PIN_StartProgram();
    py_fini();
    return 0;
}
Beispiel #6
0
int main (int argc, char **argv) {
  signal (SIGSEGV, termination_signal_handler);
  signal (SIGABRT, termination_signal_handler);
  signal (SIGBUS, termination_signal_handler);
  signal (SIGQUIT, termination_signal_handler);
  signal (SIGFPE, termination_signal_handler);

  signal (SIGPIPE, SIG_IGN);
  
  signal (SIGTERM, sig_term_handler);
  signal (SIGINT, sig_term_handler);

  rl_catch_signals = 0;


  log_level = 10;
  
  args_parse (argc, argv);
  
  change_user_group ();

  if (port > 0) {
    struct sockaddr_in serv_addr;
    int yes = 1;
    sfd = socket (AF_INET, SOCK_STREAM, 0);
    if (sfd < 0) {
      perror ("socket");
      exit(1);
    }

    if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0) {
      perror("setsockopt");
      exit(1);
    }
    memset (&serv_addr, 0, sizeof (serv_addr));
    
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = accept_any_tcp ? INADDR_ANY : htonl (0x7f000001);
    serv_addr.sin_port = htons (port);
 
    if (bind (sfd, (struct sockaddr *) &serv_addr, sizeof (serv_addr)) < 0) {
      perror ("bind");
      exit(1);
    }

    listen (sfd, 5);
  } else {
    sfd = -1;
  }
  
  if (unix_socket) {
    assert (strlen (unix_socket) < 100);
    struct sockaddr_un serv_addr;

    usfd = socket (AF_UNIX, SOCK_STREAM, 0);
    if (usfd < 0) {
      perror ("socket");
      exit(1);
    }

    memset (&serv_addr, 0, sizeof (serv_addr));
    
    serv_addr.sun_family = AF_UNIX;

    snprintf (serv_addr.sun_path, sizeof(serv_addr.sun_path), "%s", unix_socket);
 
    if (bind (usfd, (struct sockaddr *) &serv_addr, sizeof (serv_addr)) < 0) {
      perror ("bind");
      exit(1);
    }

    listen (usfd, 5);    
  } else {
    usfd = -1;
  }

  if (daemonize) {
    signal (SIGHUP, sighup_handler);
    reopen_logs ();
  }
  signal (SIGUSR1, sigusr1_handler);

  if (!disable_output) {
    printf (
      "Telegram-cli version " TELEGRAM_CLI_VERSION ", Copyright (C) 2013-2015 Vitaly Valtman\n"
      "Telegram-cli comes with ABSOLUTELY NO WARRANTY; for details type `show_license'.\n"
      "This is free software, and you are welcome to redistribute it\n"
      "under certain conditions; type `show_license' for details.\n"
      "Telegram-cli uses libtgl version " TGL_VERSION "\n"
#ifndef TGL_AVOID_OPENSSL 
      "Telegram-cli includes software developed by the OpenSSL Project\n"
      "for use in the OpenSSL Toolkit. (http://www.openssl.org/)\n"
#endif
#ifdef USE_PYTHON
      "Telegram-cli uses libpython version " PY_VERSION "\n"
#endif
    );
  }
  running_for_first_time ();
  parse_config ();

  #ifdef __FreeBSD__
  tgl_set_rsa_key (TLS, "/usr/local/etc/" PROG_NAME "/server.pub");
  #else
  tgl_set_rsa_key (TLS, "/etc/" PROG_NAME "/server.pub");
  #endif
  tgl_set_rsa_key (TLS, "tg-server.pub");

  tgl_set_rsa_key_direct (TLS, tglmp_get_default_e (), tglmp_get_default_key_len (), tglmp_get_default_key ());

  get_terminal_attributes ();

  #ifdef USE_LUA
  if (lua_file) {
    lua_init (lua_file, lua_param);
  }
  #endif
  #ifdef USE_PYTHON
  if (python_file) {
    py_init (python_file);
  }
  #endif


  inner_main ();
  
  return 0;
}