예제 #1
0
static gboolean
ip4_process_dhcpcd_rfc3442_routes (const char *str,
                                   NMIP4Config *ip4_config,
                                   guint32 *gwaddr)
{
	char **routes, **r;
	gboolean have_routes = FALSE;

	routes = g_strsplit (str, " ", 0);
	if (g_strv_length (routes) == 0)
		goto out;

	if ((g_strv_length (routes) % 2) != 0) {
		nm_log_warn (LOGD_DHCP4, "  classless static routes provided, but invalid");
		goto out;
	}

	for (r = routes; *r; r += 2) {
		char *slash;
		NMIP4Route *route;
		int rt_cidr = 32;
		struct in_addr rt_addr;
		struct in_addr rt_route;

		slash = strchr(*r, '/');
		if (slash) {
			*slash = '\0';
			errno = 0;
			rt_cidr = strtol (slash + 1, NULL, 10);
			if ((errno == EINVAL) || (errno == ERANGE)) {
				nm_log_warn (LOGD_DHCP4, "DHCP provided invalid classless static route cidr: '%s'", slash + 1);
				continue;
			}
		}
		if (inet_pton (AF_INET, *r, &rt_addr) <= 0) {
			nm_log_warn (LOGD_DHCP4, "DHCP provided invalid classless static route address: '%s'", *r);
			continue;
		}
		if (inet_pton (AF_INET, *(r + 1), &rt_route) <= 0) {
			nm_log_warn (LOGD_DHCP4, "DHCP provided invalid classless static route gateway: '%s'", *(r + 1));
			continue;
		}

		have_routes = TRUE;
		if (rt_cidr == 0 && rt_addr.s_addr == 0) {
			/* FIXME: how to handle multiple routers? */
			*gwaddr = rt_route.s_addr;
		} else {
			route = nm_ip4_route_new ();
			nm_ip4_route_set_dest (route, (guint32) rt_addr.s_addr);
			nm_ip4_route_set_prefix (route, rt_cidr);
			nm_ip4_route_set_next_hop (route, (guint32) rt_route.s_addr);

			nm_ip4_config_take_route (ip4_config, route);
			nm_log_info (LOGD_DHCP4, "  classless static route %s/%d gw %s", *r, rt_cidr, *(r + 1));
		}
	}

out:
	g_strfreev (routes);
	return have_routes;
}
예제 #2
0
static void
end_element (GMarkupParseContext  *context,
	     const gchar          *element_name,
	     gpointer              user_data,
	     GError              **error)
{
  ParseState *state = user_data;
  GError *my_error = NULL;

  if (strcmp (element_name, "gresource") == 0)
    {
      g_free (state->prefix);
      state->prefix = NULL;
    }

  else if (strcmp (element_name, "file") == 0)
    {
      gchar *file, *real_file;
      gchar *key;
      FileData *data;
      char *tmp_file = NULL;
      char *tmp_file2 = NULL;

      file = state->string->str;
      key = file;
      if (state->alias)
	key = state->alias;

      if (state->prefix)
	key = g_build_path ("/", "/", state->prefix, key, NULL);
      else
	key = g_build_path ("/", "/", key, NULL);

      if (g_hash_table_lookup (state->table, key) != NULL)
	{
	  g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
		       _("File %s appears multiple times in the resource"),
		       key);
	  return;
	}

      data = g_new0 (FileData, 1);

      if (sourcedirs != NULL)
        {
	  real_file = find_file (file);
	  if (real_file == NULL)
	    {
		g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
			     _("Failed to locate '%s' in any source directory"), file);
		return;
	    }
	}
      else
        {
	  gboolean exists;
	  exists = g_file_test (file, G_FILE_TEST_EXISTS);
	  if (!exists)
	    {
	      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
			   _("Failed to locate '%s' in current directory"), file);
	      return;
	    }
	  real_file = g_strdup (file);
	}

      data->filename = g_strdup (real_file);
      if (!state->collect_data)
        goto done;

      if (state->preproc_options)
        {
          gchar **options;
          guint i;
          gboolean xml_stripblanks = FALSE;
          gboolean to_pixdata = FALSE;

          options = g_strsplit (state->preproc_options, ",", -1);

          for (i = 0; options[i]; i++)
            {
              if (!strcmp (options[i], "xml-stripblanks"))
                xml_stripblanks = TRUE;
              else if (!strcmp (options[i], "to-pixdata"))
                to_pixdata = TRUE;
              else
                {
                  g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
                               _("Unknown processing option \"%s\""), options[i]);
                  g_strfreev (options);
                  goto cleanup;
                }
            }
          g_strfreev (options);

          if (xml_stripblanks && xmllint != NULL)
            {
              int fd;
	      GSubprocess *proc;

              tmp_file = g_strdup ("resource-XXXXXXXX");
              if ((fd = g_mkstemp (tmp_file)) == -1)
                {
                  int errsv = errno;

                  g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
                               _("Failed to create temp file: %s"),
                              g_strerror (errsv));
                  g_free (tmp_file);
                  tmp_file = NULL;
                  goto cleanup;
                }
              close (fd);

              proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
                                       xmllint, "--nonet", "--noblanks", "--output", tmp_file, real_file, NULL);
              g_free (real_file);
	      real_file = NULL;

	      if (!proc)
		goto cleanup;

	      if (!g_subprocess_wait_check (proc, NULL, error))
		{
		  g_object_unref (proc);
                  goto cleanup;
                }

	      g_object_unref (proc);

              real_file = g_strdup (tmp_file);
            }

          if (to_pixdata)
            {
              int fd;
	      GSubprocess *proc;

              if (gdk_pixbuf_pixdata == NULL)
                {
                  g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                                       "to-pixbuf preprocessing requested but GDK_PIXBUF_PIXDATA "
                                       "not set and gdk-pixbuf-pixdata not found in path");
                  goto cleanup;
                }

              tmp_file2 = g_strdup ("resource-XXXXXXXX");
              if ((fd = g_mkstemp (tmp_file2)) == -1)
                {
                  int errsv = errno;

                  g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
                               _("Failed to create temp file: %s"),
			       g_strerror (errsv));
                  g_free (tmp_file2);
                  tmp_file2 = NULL;
                  goto cleanup;
                }
              close (fd);

              proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
                                       gdk_pixbuf_pixdata, real_file, tmp_file2, NULL);
              g_free (real_file);
              real_file = NULL;

	      if (!g_subprocess_wait_check (proc, NULL, error))
		{
		  g_object_unref (proc);
                  goto cleanup;
		}

	      g_object_unref (proc);

              real_file = g_strdup (tmp_file2);
            }
	}

      if (!g_file_get_contents (real_file, &data->content, &data->size, &my_error))
	{
	  g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
		       _("Error reading file %s: %s"),
		       real_file, my_error->message);
	  g_clear_error (&my_error);
	  goto cleanup;
	}
      /* Include zero termination in content_size for uncompressed files (but not in size) */
      data->content_size = data->size + 1;

      if (state->compressed)
	{
	  GOutputStream *out = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
	  GZlibCompressor *compressor =
	    g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB, 9);
	  GOutputStream *out2 = g_converter_output_stream_new (out, G_CONVERTER (compressor));

	  if (!g_output_stream_write_all (out2, data->content, data->size,
					  NULL, NULL, NULL) ||
	      !g_output_stream_close (out2, NULL, NULL))
	    {
	      g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
			   _("Error compressing file %s"),
			   real_file);
	      goto cleanup;
	    }

	  g_free (data->content);
	  data->content_size = g_memory_output_stream_get_size (G_MEMORY_OUTPUT_STREAM (out));
	  data->content = g_memory_output_stream_steal_data (G_MEMORY_OUTPUT_STREAM (out));

	  g_object_unref (compressor);
	  g_object_unref (out);
	  g_object_unref (out2);

	  data->flags |= G_RESOURCE_FLAGS_COMPRESSED;
	}

    done:

      g_hash_table_insert (state->table, key, data);

    cleanup:
      /* Cleanup */

      g_free (state->alias);
      state->alias = NULL;
      g_string_free (state->string, TRUE);
      state->string = NULL;
      g_free (state->preproc_options);
      state->preproc_options = NULL;

      g_free (real_file);

      if (tmp_file)
        {
          unlink (tmp_file);
          g_free (tmp_file);
        }

      if (tmp_file2)
        {
          unlink (tmp_file2);
          g_free (tmp_file2);
        }
    }
}
예제 #3
0
void daemon_helpers_typehelper_ParseHostAndPort (const gchar* input, gchar** host, guint16** port, GError** error) {
	gchar* _host = NULL;
	guint16* _port = NULL;
	gchar** _tmp0_;
	gchar** _tmp1_ = NULL;
	gchar** parts;
	gint parts_length1;
	gint _parts_size_;
	gchar* _tmp3_ = NULL;
	gint _tmp4_;
	GError * _inner_error_ = NULL;
	g_return_if_fail (input != NULL);
	_tmp1_ = _tmp0_ = g_strsplit (input, ":", 0);
	parts = _tmp1_;
	parts_length1 = _vala_array_length (_tmp0_);
	_parts_size_ = _vala_array_length (_tmp0_);
	if (parts_length1 > 2) {
		GError* _tmp2_ = NULL;
		_tmp2_ = g_error_new_literal (DAEMON_HELPERS_DAEMON_ERROR, DAEMON_HELPERS_DAEMON_ERROR_ParseFailed, "Invalid host");
		_inner_error_ = _tmp2_;
		if (_inner_error_->domain == DAEMON_HELPERS_DAEMON_ERROR) {
			g_propagate_error (error, _inner_error_);
			parts = (_vala_array_free (parts, parts_length1, (GDestroyNotify) g_free), NULL);
			return;
		} else {
			parts = (_vala_array_free (parts, parts_length1, (GDestroyNotify) g_free), NULL);
			g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
			g_clear_error (&_inner_error_);
			return;
		}
	}
	_tmp3_ = string_strip (parts[0]);
	_g_free0 (_host);
	_host = _tmp3_;
	_tmp4_ = strlen (_host);
	if (_tmp4_ == 0) {
		GError* _tmp5_ = NULL;
		_tmp5_ = g_error_new_literal (DAEMON_HELPERS_DAEMON_ERROR, DAEMON_HELPERS_DAEMON_ERROR_ParseFailed, "Invalid host");
		_inner_error_ = _tmp5_;
		if (_inner_error_->domain == DAEMON_HELPERS_DAEMON_ERROR) {
			g_propagate_error (error, _inner_error_);
			parts = (_vala_array_free (parts, parts_length1, (GDestroyNotify) g_free), NULL);
			return;
		} else {
			parts = (_vala_array_free (parts, parts_length1, (GDestroyNotify) g_free), NULL);
			g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
			g_clear_error (&_inner_error_);
			return;
		}
	}
	if (parts_length1 == 2) {
		guint16* _tmp6_ = NULL;
		_tmp6_ = daemon_helpers_typehelper_ParsePort (parts[1]);
		_g_free0 (_port);
		_port = _tmp6_;
		if (_port == NULL) {
			GError* _tmp7_ = NULL;
			_tmp7_ = g_error_new_literal (DAEMON_HELPERS_DAEMON_ERROR, DAEMON_HELPERS_DAEMON_ERROR_ParseFailed, "Could not parse port");
			_inner_error_ = _tmp7_;
			if (_inner_error_->domain == DAEMON_HELPERS_DAEMON_ERROR) {
				g_propagate_error (error, _inner_error_);
				parts = (_vala_array_free (parts, parts_length1, (GDestroyNotify) g_free), NULL);
				return;
			} else {
				parts = (_vala_array_free (parts, parts_length1, (GDestroyNotify) g_free), NULL);
				g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
				g_clear_error (&_inner_error_);
				return;
			}
		}
	}
	parts = (_vala_array_free (parts, parts_length1, (GDestroyNotify) g_free), NULL);
	if (host) {
		*host = _host;
	} else {
		_g_free0 (_host);
	}
	if (port) {
		*port = _port;
	} else {
		_g_free0 (_port);
	}
}
예제 #4
0
파일: fluke.c 프로젝트: aurelj/libsigrok
static void handle_line(const struct sr_dev_inst *sdi)
{
	struct dev_context *devc;
	struct sr_serial_dev_inst *serial;
	struct sr_datafeed_packet packet;
	struct sr_datafeed_analog_old *analog;
	int num_tokens, n, i;
	char cmd[16], **tokens;

	devc = sdi->priv;
	serial = sdi->conn;
	sr_spew("Received line '%s' (%d).", devc->buf, devc->buflen);

	if (devc->buflen == 1) {
		if (devc->buf[0] != '0') {
			/* Not just a CMD_ACK from the query command. */
			sr_dbg("Got CMD_ACK '%c'.", devc->buf[0]);
			devc->expect_response = FALSE;
		}
		devc->buflen = 0;
		return;
	}

	analog = NULL;
	tokens = g_strsplit(devc->buf, ",", 0);
	if (tokens[0]) {
		if (devc->profile->model == FLUKE_187 || devc->profile->model == FLUKE_189) {
			devc->expect_response = FALSE;
			analog = handle_qm_18x(sdi, tokens);
		} else if (devc->profile->model == FLUKE_287) {
			devc->expect_response = FALSE;
			analog = handle_qm_28x(sdi, tokens);
		} else if (devc->profile->model == FLUKE_190) {
			devc->expect_response = FALSE;
			for (num_tokens = 0; tokens[num_tokens]; num_tokens++);
			if (num_tokens >= 7) {
				/* Response to QM: this is a comma-separated list of
				 * fields with metadata about the measurement. This
				 * format can return multiple sets of metadata,
				 * split into sets of 7 tokens each. */
				devc->meas_type = 0;
				for (i = 0; i < num_tokens; i += 7)
					handle_qm_19x_meta(sdi, tokens + i);
				if (devc->meas_type) {
					/* Slip the request in now, before the main
					 * timer loop asks for metadata again. */
					n = sprintf(cmd, "QM %d\r", devc->meas_type);
					if (serial_write_blocking(serial, cmd, n, SERIAL_WRITE_TIMEOUT_MS) < 0)
						sr_err("Unable to send QM (measurement).");
				}
			} else {
				/* Response to QM <n> measurement request. */
				handle_qm_19x_data(sdi, tokens);
			}
		}
	}
	g_strfreev(tokens);
	devc->buflen = 0;

	if (analog) {
		/* Got a measurement. */
		packet.type = SR_DF_ANALOG_OLD;
		packet.payload = analog;
		sr_session_send(devc->cb_data, &packet);
		devc->num_samples++;
		g_free(analog->data);
		g_free(analog);
	}

}
/**
 * gs_plugin_add_updates_historical:
 */
gboolean
gs_plugin_add_updates_historical (GsPlugin *plugin,
				  GList **list,
				  GCancellable *cancellable,
				  GError **error)
{
	gboolean ret;
	guint i;
	_cleanup_strv_free_ gchar **package_ids = NULL;
	_cleanup_free_ gchar *error_details = NULL;
	_cleanup_free_ gchar *packages = NULL;
	_cleanup_keyfile_unref_ GKeyFile *key_file = NULL;

	/* was any offline update attempted */
	if (!g_file_test (PK_OFFLINE_UPDATE_RESULTS_FILENAME, G_FILE_TEST_EXISTS))
		return TRUE;

	/* open the file */
	key_file = g_key_file_new ();
	ret = g_key_file_load_from_file (key_file,
					 PK_OFFLINE_UPDATE_RESULTS_FILENAME,
					 G_KEY_FILE_NONE,
					 error);
	if (!ret)
		return FALSE;

	/* only return results if successful */
	ret = g_key_file_get_boolean (key_file,
				      PK_OFFLINE_UPDATE_RESULTS_GROUP,
				      "Success",
				      NULL);
	if (!ret) {
		error_details = g_key_file_get_string (key_file,
						       PK_OFFLINE_UPDATE_RESULTS_GROUP,
						       "ErrorDetails",
						       error);
		if (error_details == NULL)
			return FALSE;
		g_set_error_literal (error,
				     GS_PLUGIN_ERROR,
				     GS_PLUGIN_ERROR_FAILED,
				     error_details);
		return FALSE;
	}

	/* get list of package-ids */
	packages = g_key_file_get_string (key_file,
					  PK_OFFLINE_UPDATE_RESULTS_GROUP,
					  "Packages",
					  NULL);
	if (packages == NULL) {
		g_set_error (error,
			     GS_PLUGIN_ERROR,
			     GS_PLUGIN_ERROR_NOT_SUPPORTED,
			     "No 'Packages' in %s",
			     PK_OFFLINE_UPDATE_RESULTS_FILENAME);
		return FALSE;
	}
	package_ids = g_strsplit (packages, ",", -1);
	for (i = 0; package_ids[i] != NULL; i++) {
		_cleanup_object_unref_ GsApp *app = NULL;
		_cleanup_strv_free_ gchar **split = NULL;
		app = gs_app_new (NULL);
		split = g_strsplit (package_ids[i], ";", 4);
		gs_app_add_source (app, split[0]);
		gs_app_set_update_version (app, split[1]);
		gs_app_set_management_plugin (app, "PackageKit");
		gs_app_add_source_id (app, package_ids[i]);
		gs_app_set_state (app, AS_APP_STATE_UPDATABLE);
		gs_app_set_kind (app, GS_APP_KIND_PACKAGE);
		gs_plugin_add_app (list, app);
	}
	return TRUE;
}
예제 #6
0
static void _tgentransfer_readCommand(TGenTransfer* transfer) {
    TGEN_ASSERT(transfer);

    if(_tgentransfer_getLine(transfer)) {
        /* we have read the entire command from the other end */
        gboolean hasError = FALSE;
        transfer->time.command = g_get_monotonic_time();

        gchar* line = g_string_free(transfer->readBuffer, FALSE);
        transfer->readBuffer = NULL;

        gchar** parts = g_strsplit(line, " ", 0);
        if(parts[0] == NULL || parts[1] == NULL || parts[2] == NULL || parts[3] == NULL) {
            tgen_critical("error parsing command '%s'", transfer->readBuffer->str);
            hasError = TRUE;
        } else {
            g_assert(!transfer->remoteName);
            transfer->remoteName = g_strdup(parts[0]);

            transfer->remoteID = (gsize)g_ascii_strtoull(parts[1], NULL, 10);
            if(transfer->remoteID == 0) {
                tgen_critical("error parsing command ID '%s'", parts[1]);
                hasError = TRUE;
            }

            if(!g_ascii_strncasecmp(parts[2], "GET", 3)) {
                /* they are trying to GET, then we need to PUT to them */
                transfer->type = TGEN_TYPE_PUT;
                /* we read command, but now need to write payload */
                transfer->events |= TGEN_EVENT_WRITE;
            } else if(!g_ascii_strncasecmp(parts[2], "PUT", 3)) {
                /* they want to PUT, so we will GET from them */
                transfer->type = TGEN_TYPE_GET;
            } else {
                tgen_critical("error parsing command type '%s'", parts[2]);
                hasError = TRUE;
            }

            transfer->size = (gsize)g_ascii_strtoull(parts[3], NULL, 10);
            if(transfer->size == 0) {
                tgen_critical("error parsing command size '%s'", parts[3]);
                hasError = TRUE;
            }
        }

        g_strfreev(parts);
        g_free(line);

        /* payload phase is next unless there was an error parsing */
        if(hasError) {
            _tgentransfer_changeState(transfer, TGEN_XFER_ERROR);
            _tgentransfer_changeError(transfer, TGEN_XFER_ERR_READ);
        } else {
            /* we need to update our string with the new command info */
            _tgentransfer_resetString(transfer);
            _tgentransfer_changeState(transfer, TGEN_XFER_RESPONSE);
            transfer->events |= TGEN_EVENT_WRITE;
        }
    } else {
        /* unable to receive entire command, wait for next chance to read */
    }
}
예제 #7
0
파일: main.c 프로젝트: korween/oio-sds
int
main(int argc, char ** argv)
{
	HC_PROC_INIT(argv,GRID_LOGLVL_INFO);

	int rc = 1;
	service_info_t *service = NULL;
	setenv("GS_DEBUG_ENABLE", "0", TRUE);

	supervisor_children_init();

	do {
		GError *err = NULL;
		regex_tag = g_regex_new("((stat|tag)\\.([^.=\\s]+))\\s*=\\s*(.*)",
				G_REGEX_CASELESS|G_REGEX_EXTENDED, 0, &err);
		if (!regex_tag) {
			FATAL("Cannot compile tag regex: %s", err->message);
			g_clear_error(&err);
			exit(-1);
		}
		regex_svc = g_regex_new("([^|]*)\\|([^|]*)\\|(.*)",
				G_REGEX_CASELESS, 0, &err);
		if (!regex_svc) {
			FATAL("Cannot compile svc regex: %s", err->message);
			g_clear_error(&err);
			exit(-1);
		}
	} while (0);

	static struct option long_options[] = {
		{"svc-id", 1, 0, 'i'},
		{"monitor", 1, 0, 'm'},
		{"svc-cmd", 1, 0, 'c'},
		{"syslog-id", 1, 0, 's'},
		{"auto-restart-children", 0, 0, 'a'},
		{"monitor-period", 1, 0, 'p'},
		{"no-tcp-check", 0, 0, 'n'},
		{"tag", 1, 0, 't'},
		{0, 0, 0, 0}
	};

	int c;
	int option_index = 0;
	gchar *optarg2 = NULL;
	gchar **kv = NULL;
	while (-1 != (c = getopt_long(argc, argv, "ac:i:m:np:s:t:",
			long_options, &option_index))) {
		switch (c) {
		case 'i':
			g_strlcpy(svc_id, optarg, sizeof(svc_id)-1);
			break;
		case 'm':
			g_strlcpy(svc_mon, optarg, sizeof(svc_mon)-1);
			break;
		case 'c':
			g_strlcpy(svc_cmd, optarg, sizeof(svc_cmd)-1);
			break;
		case 'n':
			kv = g_malloc0(3 * sizeof(gchar*));
			kv[0] = g_strdup("tag.agent_check");
			kv[1] = g_strdup("false");
			custom_tags = g_slist_prepend(custom_tags, kv);
			break;
		case 'a':
			auto_restart_children = TRUE;
			break;
		case 'p':
			monitor_period = strtoll(optarg, NULL, 10);
			break;
		case 's':
			g_strlcpy(syslog_id, optarg, sizeof(syslog_id)-1);
			break;
		case 't':
			if (!g_str_has_prefix(optarg, "tag."))
				optarg2 = g_strdup_printf("tag.%s", optarg);
			else
				optarg2 = g_strdup(optarg);
			kv = g_strsplit(optarg2, "=", 2);
			if (kv && g_strv_length(kv) == 2) {
				custom_tags = g_slist_prepend(custom_tags, kv);
			} else {
				g_printerr("Invalid tag, must contain '=': %s", optarg);
				g_strfreev(kv);
				kv = NULL;
			}
			g_free(optarg2);
			optarg2 = NULL;
			break;
		default:
			g_printerr("Unexpected option: %c\n", c);
			break;
		}
		option_index = 0;
	}

	if (argc <= 1 || strlen(svc_id) == 0 || strlen(svc_cmd) == 0) {
		g_printerr("Usage: %s\n", argv[0]);
		g_printerr("Mandatory options:\n");
		g_printerr("\t-i\t--svc-id <NS|type|ip:port>\n"
				"\t-c\t--svc-cmd </service/cmd/to/launch>\n\n"
				"Other options:\n"
				"\t-m\t--monitor </script/to/monitor>\n"
				"\t-p\t--monitor-period <seconds>\n"
				"\t-s\t--syslog-id <syslog-id>\n"
				"\t-t\t--tag <key=val>\n"
				"\t-a\t--auto-restart-children\n"
				"\t-n\t--no-tcp-check\n");
		return 1;
	}

	if (*syslog_id)
		logger_syslog_open();

	GError *error = NULL;
	if (!supervisor_children_register(CHILD_KEY, svc_cmd, &error)) {
		g_printerr("Child registration failure:\n\t%s\n", gerror_get_message(error));
		goto label_error;
	}

	if (0 != supervisor_children_set_limit(CHILD_KEY, SUPERV_LIMIT_THREAD_STACK, 8192 * 1024))
		GRID_WARN("Limit on thread stack size cannot be set: %s", strerror(errno));
	if (0 != supervisor_children_set_limit(CHILD_KEY, SUPERV_LIMIT_MAX_FILES, 32 * 1024))
		GRID_WARN("Limit on max opened files cannot be set: %s", strerror(errno));
	if (0 != supervisor_children_set_limit(CHILD_KEY, SUPERV_LIMIT_CORE_SIZE, -1))
		GRID_WARN("Limit on core file size cannot be set: %s", strerror(errno));

	supervisor_children_set_respawn(CHILD_KEY, FALSE);
	supervisor_children_set_working_directory(CHILD_KEY, "/tmp");
	supervisor_children_inherit_env(CHILD_KEY);

	service = g_malloc0(sizeof(service_info_t));
	if (0 != init_srvinfo(svc_id, service)) {
		g_printerr("Internal error: failed to init srvinfo\n");
		goto label_error;
	}

	stdin = freopen("/dev/null", "r", stdin);

	GRID_NOTICE("%s restarted, pid=%d", argv[0], getpid());

	signal(SIGQUIT, sighandler_supervisor);
	signal(SIGTERM, sighandler_supervisor);
	signal(SIGINT,  sighandler_supervisor);
	signal(SIGPIPE, sighandler_supervisor);
	signal(SIGUSR1, sighandler_supervisor);
	signal(SIGUSR2, sighandler_supervisor);
	signal(SIGCHLD, sighandler_supervisor);

	monitoring_loop(service);

	rc = 0;

label_error:
	g_slist_free_full(custom_tags, (GDestroyNotify) g_strfreev);
	service_info_clean(service);
	supervisor_children_cleanall();
	return rc;
}
예제 #8
0
static gchar * system_stat ()
{
        gchar *std_out, *p, **pp1, **pp2, model_name[128], *result;
        gint count;
        GError *err = NULL;

        /* cpu mode */
        result = g_strdup ("{\n");
        if (!g_file_get_contents ("/proc/cpuinfo", &p, NULL, &err)) {
                GST_ERROR ("read /proc/cpuinfo failure: %s", err->message);
                g_free (result);
                result = g_strdup_printf ("{\n    \"result\": \"failure\",\n    \"reason\": \"%s\"\n}", err->message);
                g_error_free (err);
                return result;
        }

        pp1 = pp2 = g_strsplit (p, "\n", 0);
        g_free (p);
        while (*pp1 != NULL) {
                if (!g_str_has_prefix (*pp1, "model name")) {
                        pp1++;
                        continue;
                }
                sscanf (*pp1, "%*[^:]: %[^\n]$", model_name);
                break;
        }
        g_strfreev (pp2);
        p = result;
        result = g_strdup_printf ("%s    \"CPU_Model\": \"%s\"", p, model_name);
        g_free (p);

        if (!g_spawn_command_line_sync ("lscpu", &std_out, NULL, NULL, &err)) {
                GST_ERROR ("invoke lscpu failure: %s", err->message);
                g_free (result);
                result = g_strdup_printf ("{\n    \"result\": \"failure\",\n    \"reason\": \"%s\"\n}", err->message);
                g_error_free (err);
                return result;
        }
        pp1 = pp2 = g_strsplit (std_out, "\n", 0);
        while (*pp1 != NULL) {
                if (g_str_has_prefix (*pp1, "CPU(s)")) {
                        sscanf (*pp1, "CPU(s):%*[ ]%d", &count);
                        p = result;
                        result = g_strdup_printf ("%s,\n    \"CPU_Count\": %d", p, count);
                        g_free (p);

                } else if (g_str_has_prefix (*pp1, "Thread(s) per core")) {
                        sscanf (*pp1, "Thread(s) per core:%*[ ]%d", &count);
                        p = result;
                        result = g_strdup_printf ("%s,\n    \"Threads_per_Core\": %d", p, count);
                        g_free (p);

                } else if (g_str_has_prefix (*pp1, "Core(s) per socket")) {
                        sscanf (*pp1, "Core(s) per socket:%*[ ]%d", &count);
                        p = result;
                        result = g_strdup_printf ("%s,\n    \"Core_per_Socket\": %d", p, count);
                        g_free (p);

                } else if (g_str_has_prefix (*pp1, "Socket(s)")) {
                        sscanf (*pp1, "Socket(s):%*[ ]%d", &count);
                        p = result;
                        result = g_strdup_printf ("%s,\n    \"Sockets_Count\": %d", p, count);
                        g_free (p);

                } else if (g_str_has_prefix (*pp1, "CPU MHz")){
                        sscanf (*pp1, "CPU MHz:%*[ ]%d", &count);
                        p = result;
                        result = g_strdup_printf ("%s,\n    \"CPU_MHz\": %d", p, count);
                        g_free (p);
                }
                pp1++;
        }
        g_strfreev (pp2);
        g_free (std_out);

        p = result;
        result = g_strdup_printf ("%s\n}", p);
        g_free (p);

        return result;
}
예제 #9
0
파일: plugin.c 프로젝트: algernon/syslog-ng
static GModule *
plugin_dlopen_module(const gchar *module_name, const gchar *module_path)
{
  gchar *plugin_module_name = NULL;
  gchar **module_path_dirs, *p, *dot;
  GModule *mod;
  gint i;

  module_path_dirs = g_strsplit(module_path, G_SEARCHPATH_SEPARATOR_S, 0);
  i = 0;
  while (module_path_dirs && module_path_dirs[i])
    {
      plugin_module_name = g_module_build_path(module_path_dirs[i], module_name);
      if (is_file_regular(plugin_module_name))
        break;

      /* also check if a libtool archive exists (for example in the build directory) */
#ifndef _AIX
      dot = strrchr(plugin_module_name, '.');
      if (dot)
        {
          *dot = 0;
          p = g_strdup_printf("%s.la", plugin_module_name);
          g_free(plugin_module_name);
          plugin_module_name = p;
        }
      if (is_file_regular(plugin_module_name))
        break;

      /* On AIX the modules in .a files */
#else
      dot = strrchr(plugin_module_name, '.');
      if (dot)
        {
          *dot = 0;
          p = g_strdup_printf("%s.a", plugin_module_name);
          g_free(plugin_module_name);
          plugin_module_name = p;
        }
      if (is_file_regular(plugin_module_name))
        break;
#endif

      g_free(plugin_module_name);
      plugin_module_name = NULL;
      i++;
    }
  g_strfreev(module_path_dirs);
  if (!plugin_module_name)
    {
      msg_error("Plugin module not found in 'module-path'",
                evt_tag_str("module-path", module_path),
                evt_tag_str("module", module_name),
                NULL);
      return NULL;
    }
  msg_trace("Trying to open module",
            evt_tag_str("module", module_name),
            evt_tag_str("filename", plugin_module_name),
            NULL);

  mod = g_module_open(plugin_module_name, G_MODULE_BIND_LAZY);
  g_free(plugin_module_name);
  if (!mod)
    {
      msg_error("Error opening plugin module",
                evt_tag_str("module", module_name),
                evt_tag_str("error", g_module_error()),
                NULL);
      return NULL;
    }
  return mod;
}
예제 #10
0
/**
 * @brief Inits or loads the knowledge base for a single host.
 *
 * Fills the knowledge base with host-specific login information for local
 * checks if defined.
 *
 * @param globals     Global preference arglist.
 * @param hostname    Name of the host.
 * @param new_kb[out] TRUE if the kb is new and shall be saved.
 *
 * @return A knowledge base.
 *
 * @see fill_host_kb_ssh_credentials
 */
static kb_t
init_host_kb (struct arglist *globals, char *hostname,
              struct arglist *hostinfos, gboolean * new_kb)
{
  kb_t kb, network_kb;
  (*new_kb) = FALSE;
  gchar *vhosts;
  struct kb_item *host_network_results = NULL;
  struct kb_item *result_iter;

  gchar *network_scan_status = (gchar *) arg_get_value (globals, "network_scan_status");
  if (network_scan_status != NULL)
    {
      if (g_ascii_strcasecmp (network_scan_status, "done") == 0)
        {
          gchar *hostname_pattern = g_strdup_printf ("%s/*", hostname);
          network_kb = save_kb_load_kb (globals, "network");
          host_network_results = kb_item_get_pattern (network_kb, hostname_pattern);
        }
      if (g_ascii_strcasecmp (network_scan_status, "busy") == 0)
        {
          arg_add_value (globals, "CURRENTLY_TESTED_HOST", ARG_STRING,
                         strlen ("network"), "network");
          save_kb_new (globals, "network");
          kb = kb_new ();
          (*new_kb) = TRUE;
          return kb;
        }
    }

  // Check if kb should be saved.
  if (save_kb (globals))
    {
      // Check if a saved kb exists and we shall restore it.
      if (save_kb_exists (hostname) != 0)
        {
          save_kb_backup (hostname);
          kb = save_kb_load_kb (globals, hostname);
        }
      else
        {
          // We shall not or cannot restore.
          save_kb_new (globals, hostname);
          kb = kb_new ();
          (*new_kb) = TRUE;
        }
 
      arg_add_value (globals, "CURRENTLY_TESTED_HOST", ARG_STRING,
                     strlen (hostname), hostname);
    }
  else                          /* save_kb(globals) */
    {
      kb = kb_new ();
    }

  /* Add local check (SSH)- related knowledge base items. */
  fill_host_kb_ssh_credentials (kb, globals, hostname);

  /* If vhosts is set, split it and put it in the KB. */
  vhosts = (gchar *)arg_get_value (hostinfos, "VHOSTS");
  if (vhosts)
    {
      gchar **vhosts_array = g_strsplit (vhosts, ",", 0);
      guint i = 0;
      while (vhosts_array[i] != NULL)
        {
          kb_item_add_str (kb, "hostinfos/vhosts", vhosts_array[i]);
          save_kb_write_str (globals, hostname, "hostinfos/vhosts", vhosts_array[i]);
          i++;
        }
      g_strfreev (vhosts_array);
    }

  result_iter = host_network_results;
  while (result_iter != NULL)
    {
      char *newname = strstr (result_iter->name, "/") + 1;
      if (result_iter->type == KB_TYPE_STR)
        {
          kb_item_add_str (kb, newname, result_iter->v.v_str);
          save_kb_write_str (globals, hostname, newname, result_iter->v.v_str);
        }
      else if (result_iter->type == KB_TYPE_INT)
        {
          kb_item_add_int (kb, newname, result_iter->v.v_int);
          save_kb_write_int (globals, hostname, newname, result_iter->v.v_int);
        }
      result_iter = result_iter->next;
    }

  return kb;
}
예제 #11
0
gboolean
_g_dbus_address_parse_entry (const gchar  *address_entry,
                             gchar       **out_transport_name,
                             GHashTable  **out_key_value_pairs,
                             GError      **error)
{
  gboolean ret;
  GHashTable *key_value_pairs;
  gchar *transport_name;
  gchar **kv_pairs;
  const gchar *s;
  guint n;

  ret = FALSE;
  kv_pairs = NULL;
  transport_name = NULL;
  key_value_pairs = NULL;

  s = strchr (address_entry, ':');
  if (s == NULL)
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_ARGUMENT,
                   _("Address element `%s', does not contain a colon (:)"),
                   address_entry);
      goto out;
    }

  transport_name = g_strndup (address_entry, s - address_entry);
  key_value_pairs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);

  kv_pairs = g_strsplit (s + 1, ",", 0);
  for (n = 0; kv_pairs != NULL && kv_pairs[n] != NULL; n++)
    {
      const gchar *kv_pair = kv_pairs[n];
      gchar *key;
      gchar *value;

      s = strchr (kv_pair, '=');
      if (s == NULL)
        {
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_ARGUMENT,
                       _("Key/Value pair %d, `%s', in address element `%s', does not contain an equal sign"),
                       n,
                       kv_pair,
                       address_entry);
          goto out;
        }

      /* TODO: actually validate that no illegal characters are present before and after then '=' sign */
      key = g_uri_unescape_segment (kv_pair, s, NULL);
      value = g_uri_unescape_segment (s + 1, kv_pair + strlen (kv_pair), NULL);
      g_hash_table_insert (key_value_pairs, key, value);
    }

  ret = TRUE;

out:
  g_strfreev (kv_pairs);
  if (ret)
    {
      if (out_transport_name != NULL)
        *out_transport_name = transport_name;
      else
        g_free (transport_name);
      if (out_key_value_pairs != NULL)
        *out_key_value_pairs = key_value_pairs;
      else if (key_value_pairs != NULL)
        g_hash_table_unref (key_value_pairs);
    }
  else
    {
      g_free (transport_name);
      if (key_value_pairs != NULL)
        g_hash_table_unref (key_value_pairs);
    }
  return ret;
}
예제 #12
0
파일: plugin.c 프로젝트: rosedu/anjuta
static void
on_glade_drop (IAnjutaEditor* editor,
               IAnjutaIterable* iterator,
               const gchar* signal_data,
               PythonPlugin* lang_plugin)
{
	GSignalQuery query;
	GType type;
	guint id;
	
	const gchar* widget;
	const gchar* signal;
	const gchar* handler;
	const gchar* user_data;
	gboolean swapped;
	GList* names = NULL;
	GString* str = g_string_new (NULL);
	int i;
	IAnjutaIterable* start, * end;
	
	GStrv data = g_strsplit(signal_data, ":", 5);
	
	widget = data[0];
	signal = data[1];
	handler = data[2];
	user_data = data[3];
	swapped = g_str_equal (data[4], "1");
	
	type = g_type_from_name (widget);
	id = g_signal_lookup (signal, type);

	g_signal_query (id, &query);

	g_string_append_printf (str, "\ndef %s (self", handler);
	for (i = 0; i < query.n_params; i++)
	{
		const gchar* type_name = g_type_name (query.param_types[i]);
		const gchar* param_name = language_support_get_signal_parameter (type_name,
		                                                                 &names);

		g_string_append_printf (str, ", %s", param_name);
	}
	g_string_append (str, "):\n");

	ianjuta_editor_insert (editor, iterator,
	                       str->str, -1, NULL);

	/* Indent code correctly */
	start = iterator;
	end = ianjuta_iterable_clone (iterator, NULL);
	ianjuta_iterable_set_position (end, 
	                               ianjuta_iterable_get_position (iterator, NULL)
	                           		+ g_utf8_strlen (str->str, -1),
	                               NULL);
	ianjuta_indenter_indent (IANJUTA_INDENTER (lang_plugin),
	                         start, end, NULL);
	g_object_unref (end);

	g_string_free (str, TRUE);
	anjuta_util_glist_strings_free (names);
	
	g_strfreev (data);
}
예제 #13
0
파일: sigrok-cli.c 프로젝트: jeras/sigrok
/* Register the given PDs for this session.
 * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
 * That will instantiate two SPI decoders on the clock but different data
 * lines.
 */
static int register_pds(struct sr_dev *dev, const char *pdstring)
{
	GHashTable *pd_opthash;
	struct srd_decoder_inst *di;
	int ret;
	char **pdtokens, **pdtok, *pd_name;

	/* Avoid compiler warnings. */
	(void)dev;

	ret = 0;
	pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
			g_free, NULL);
	pd_name = NULL;
	pd_opthash = NULL;
	pdtokens = g_strsplit(pdstring, ",", 0);
	for (pdtok = pdtokens; *pdtok; pdtok++) {
		if (!(pd_opthash = parse_generic_arg(*pdtok))) {
			g_critical("Invalid protocol decoder option '%s'.", *pdtok);
			goto err_out;
		}

		pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
		g_hash_table_remove(pd_opthash, "sigrok_key");
		if (srd_decoder_load(pd_name) != SRD_OK) {
			g_critical("Failed to load protocol decoder %s.", pd_name);
			ret = 1;
			goto err_out;
		}
		if (!(di = srd_inst_new(pd_name, pd_opthash))) {
			g_critical("Failed to instantiate protocol decoder %s.", pd_name);
			ret = 1;
			goto err_out;
		}

		/* If no annotation list was specified, add them all in now.
		 * This will be pared down later to leave only the last PD
		 * in the stack.
		 */
		if (!opt_pd_annotations)
			g_hash_table_insert(pd_ann_visible,
					    g_strdup(di->inst_id), NULL);

		/* Any keys left in the options hash are probes, where the key
		 * is the probe name as specified in the decoder class, and the
		 * value is the probe number i.e. the order in which the PD's
		 * incoming samples are arranged. */
		if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
			ret = 1;
			goto err_out;
		}
		g_hash_table_destroy(pd_opthash);
		pd_opthash = NULL;
	}

err_out:
	g_strfreev(pdtokens);
	if (pd_opthash)
		g_hash_table_destroy(pd_opthash);
	if (pd_name)
		g_free(pd_name);

	return ret;
}
예제 #14
0
/* Given a table of DHCP options from the client, convert into an IP4Config */
static NMIP4Config *
ip4_options_to_config (NMDHCPClient *self)
{
	NMDHCPClientPrivate *priv;
	NMIP4Config *ip4_config = NULL;
	struct in_addr tmp_addr;
	NMIP4Address *addr = NULL;
	char *str = NULL;
	guint32 gwaddr = 0, prefix = 0;

	g_return_val_if_fail (self != NULL, NULL);
	g_return_val_if_fail (NM_IS_DHCP_CLIENT (self), NULL);

	priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
	g_return_val_if_fail (priv->options != NULL, NULL);

	ip4_config = nm_ip4_config_new ();
	if (!ip4_config) {
		nm_log_warn (LOGD_DHCP4, "(%s): couldn't allocate memory for an IP4Config!", priv->iface);
		return NULL;
	}

	addr = nm_ip4_address_new ();
	if (!addr) {
		nm_log_warn (LOGD_DHCP4, "(%s): couldn't allocate memory for an IP4 Address!", priv->iface);
		goto error;
	}

	str = g_hash_table_lookup (priv->options, "new_ip_address");
	if (str && (inet_pton (AF_INET, str, &tmp_addr) > 0)) {
		nm_ip4_address_set_address (addr, tmp_addr.s_addr);
		nm_log_info (LOGD_DHCP4, "  address %s", str);
	} else
		goto error;

	str = g_hash_table_lookup (priv->options, "new_subnet_mask");
	if (str && (inet_pton (AF_INET, str, &tmp_addr) > 0)) {
		prefix = nm_utils_ip4_netmask_to_prefix (tmp_addr.s_addr);
		nm_log_info (LOGD_DHCP4, "  prefix %d (%s)", prefix, str);
	} else {
		/* Get default netmask for the IP according to appropriate class. */
		prefix = nm_utils_ip4_get_default_prefix (nm_ip4_address_get_address (addr));
		nm_log_info (LOGD_DHCP4, "  prefix %d (default)", prefix);
	}
	nm_ip4_address_set_prefix (addr, prefix);

	/* Routes: if the server returns classless static routes, we MUST ignore
	 * the 'static_routes' option.
	 */
	if (!ip4_process_classless_routes (priv->options, ip4_config, &gwaddr))
		process_classful_routes (priv->options, ip4_config);

	if (gwaddr) {
		char buf[INET_ADDRSTRLEN + 1];

		inet_ntop (AF_INET, &gwaddr, buf, sizeof (buf));
		nm_log_info (LOGD_DHCP4, "  gateway %s", buf);
		nm_ip4_address_set_gateway (addr, gwaddr);
	} else {
		/* If the gateway wasn't provided as a classless static route with a
		 * subnet length of 0, try to find it using the old-style 'routers' option.
		 */
		str = g_hash_table_lookup (priv->options, "new_routers");
		if (str) {
			char **routers = g_strsplit (str, " ", 0);
			char **s;

			for (s = routers; *s; s++) {
				/* FIXME: how to handle multiple routers? */
				if (inet_pton (AF_INET, *s, &tmp_addr) > 0) {
					nm_ip4_address_set_gateway (addr, tmp_addr.s_addr);
					nm_log_info (LOGD_DHCP4, "  gateway %s", *s);
					break;
				} else
					nm_log_warn (LOGD_DHCP4, "ignoring invalid gateway '%s'", *s);
			}
			g_strfreev (routers);
		}
	}

	nm_ip4_config_take_address (ip4_config, addr);
	addr = NULL;

	str = g_hash_table_lookup (priv->options, "new_host_name");
	if (str)
		nm_log_info (LOGD_DHCP4, "  hostname '%s'", str);

	str = g_hash_table_lookup (priv->options, "new_domain_name_servers");
	if (str) {
		char **searches = g_strsplit (str, " ", 0);
		char **s;

		for (s = searches; *s; s++) {
			if (inet_pton (AF_INET, *s, &tmp_addr) > 0) {
				nm_ip4_config_add_nameserver (ip4_config, tmp_addr.s_addr);
				nm_log_info (LOGD_DHCP4, "  nameserver '%s'", *s);
			} else
				nm_log_warn (LOGD_DHCP4, "ignoring invalid nameserver '%s'", *s);
		}
		g_strfreev (searches);
	}

	str = g_hash_table_lookup (priv->options, "new_domain_name");
	if (str) {
		char **domains = g_strsplit (str, " ", 0);
		char **s;

		for (s = domains; *s; s++) {
			nm_log_info (LOGD_DHCP4, "  domain name '%s'", *s);
			nm_ip4_config_add_domain (ip4_config, *s);
		}
		g_strfreev (domains);
	}

	str = g_hash_table_lookup (priv->options, "new_domain_search");
	if (str)
		process_domain_search (str, ip4_add_domain_search, ip4_config);

	str = g_hash_table_lookup (priv->options, "new_netbios_name_servers");
	if (str) {
		char **searches = g_strsplit (str, " ", 0);
		char **s;

		for (s = searches; *s; s++) {
			if (inet_pton (AF_INET, *s, &tmp_addr) > 0) {
				nm_ip4_config_add_wins (ip4_config, tmp_addr.s_addr);
				nm_log_info (LOGD_DHCP4, "  wins '%s'", *s);
			} else
				nm_log_warn (LOGD_DHCP4, "ignoring invalid WINS server '%s'", *s);
		}
		g_strfreev (searches);
	}

	str = g_hash_table_lookup (priv->options, "new_interface_mtu");
	if (str) {
		int int_mtu;

		errno = 0;
		int_mtu = strtol (str, NULL, 10);
		if ((errno == EINVAL) || (errno == ERANGE))
			goto error;

		if (int_mtu > 576)
			nm_ip4_config_set_mtu (ip4_config, int_mtu);
	}

	str = g_hash_table_lookup (priv->options, "new_nis_domain");
	if (str) {
		nm_log_info (LOGD_DHCP4, "  NIS domain '%s'", str);
		nm_ip4_config_set_nis_domain (ip4_config, str);
	}

	str = g_hash_table_lookup (priv->options, "new_nis_servers");
	if (str) {
		char **searches = g_strsplit (str, " ", 0);
		char **s;

		for (s = searches; *s; s++) {
			if (inet_pton (AF_INET, *s, &tmp_addr) > 0) {
				nm_ip4_config_add_nis_server (ip4_config, tmp_addr.s_addr);
				nm_log_info (LOGD_DHCP4, "  nis '%s'", *s);
			} else
				nm_log_warn (LOGD_DHCP4, "ignoring invalid NIS server '%s'", *s);
		}
		g_strfreev (searches);
	}

	return ip4_config;

error:
	if (addr)
		nm_ip4_address_unref (addr);
	g_object_unref (ip4_config);
	return NULL;
}
예제 #15
0
static void
ltable_insert(LTable* lt, const gchar* where, Listener* l)
{
  gchar** dirnames;
  guint i;
  GNode* cur;
  GNode* found = NULL;
  LTableEntry* lte;
  const gchar* noroot_where = where + 1;

  g_return_if_fail(mateconf_valid_key(where, NULL));
  
  if (lt->tree == NULL)
    {
      lte = ltable_entry_new(NULL, 0);
      
      lt->tree = g_node_new(lte);

      lte = NULL; /* paranoia */
    }
  
  /* Add to the tree */
  dirnames = g_strsplit(noroot_where, "/", -1);
  
  cur = lt->tree;
  i = 0;
  while (dirnames[i])
    {
      LTableEntry* ne;
      GNode* across;

      /* Find this dirname on this level, or add it. */
      g_assert (cur != NULL);        

      found = NULL;

      across = cur->children;

      while (across != NULL)
        {
          int cmp;

          lte = across->data;

          cmp = strcmp(lte->name, dirnames[i]);

          if (cmp == 0)
            {
              found = across;
              break;
            }
          else if (cmp > 0)
            {
              /* Past it */
              break;
            }
          else 
            {
              across = g_node_next_sibling(across);
            }
        }

      if (found == NULL)
        {
          ne = ltable_entry_new(dirnames, i);
              
          if (across != NULL) /* Across is at the one past */
            found = g_node_insert_data_before(cur, across, ne);
          else                /* Never went past, append - could speed this up by saving last visited */
            found = g_node_append_data(cur, ne);
        }

      g_assert(found != NULL);

      cur = found;

      ++i;
    }

  /* cur is still the root node ("/") if where was "/" since nothing
     was returned from g_strsplit */
  lte = cur->data;

  lte->listeners = g_list_prepend(lte->listeners, l);

  g_strfreev(dirnames);

  /* Add tree node to the flat table */
  g_ptr_array_set_size(lt->listeners, MAX(CNXN_ID_INDEX(lt->next_cnxn), CNXN_ID_INDEX(l->cnxn)));
  g_ptr_array_index(lt->listeners, CNXN_ID_INDEX(l->cnxn)) = cur;

  lt->active_listeners += 1;

#ifdef DEBUG_LISTENERS
  g_print ("Added %u at %s, spewing:\n",
	   l->cnxn, where);
  ltable_spew(lt);
#endif
}
예제 #16
0
/**
 * Easy command interface
 */
static void output_set(gpointer data, const char *param)
{
	gchar *str_param = g_strstrip(g_strdup(param));
	gchar **split = g_strsplit(str_param, " ", 2);
	if (split)
	{
		int output = -1;
		if (split[0])
		{
			output = (int)strtol(split[0], NULL, 10);
		}
		if (output >= 0)
		{
			/* Default to 'select' if no specific action given */
			if (!split[1] || g_utf8_collate(split[1], _("select")) == 0)
			{
				MpdData *devices = mpd_server_get_output_devices(connection);
				MpdData *d = devices;
				gboolean found = FALSE;

				while (d != NULL && d->output_dev->id != -10)
				{
					if (d->output_dev->id == output)
					{
						found = TRUE;
						break;
					}
					d = mpd_data_get_next(d);
				}

				if (found)
				{
					g_debug("select output %i\n", output);
					d = devices;
					while (d != NULL && d->output_dev->id != -10)
					{
						mpd_server_set_output_device(connection, d->output_dev->id,
													 d->output_dev->id == output ? 1 : 0);
						d = mpd_data_get_next(d);
					}
				} else
				{
					/* Let user know their request failed, otherwise they will likely be mystified */
					gchar *str = g_strdup_printf("Can't select output %i because it does not exist", output);
					g_debug("%s\n", str);
					playlist3_message_show(pl3_messages, str, ERROR_WARNING);
					g_free(str);
				}
			} else if (g_utf8_collate(split[1], _("enable")) == 0)
			{
				g_debug("enable output %i\n", output);
				mpd_server_set_output_device(connection, output, 1);
			} else if (g_utf8_collate(split[1], _("disable")) == 0)
			{
				mpd_server_set_output_device(connection, output, 0);
				g_debug("disable output %i\n", output);
			}
		}
		g_free(split);
	}
	g_free(str_param);
}
예제 #17
0
static void    
ltable_notify(LTable* lt, const gchar* key,
              MateConfListenersCallback callback, gpointer user_data)
{
  gchar** dirs;
  guint i;
  const gchar* noroot_key;
  GNode* cur;
  GList *to_notify;
  
  noroot_key = key + 1;

  g_return_if_fail(*key == '/');
  g_return_if_fail(mateconf_valid_key(key, NULL));

  if (lt->tree == NULL)
    return; /* no one to notify */

  /* we build a list "to_notify" to be safe against tree
   * modifications during the notification.
   */
  
  /* Notify "/" listeners */
  to_notify = g_list_copy (((LTableEntry*)lt->tree->data)->listeners);  

  dirs = g_strsplit (noroot_key, "/", -1);

  cur = lt->tree;
  i = 0;
  while (dirs[i] && cur)
    {
      GNode* child = cur->children;

      while (child != NULL)
        {
          LTableEntry* lte = child->data;

          if (strcmp(lte->name, dirs[i]) == 0)
            {
              GList *copy = g_list_copy (lte->listeners);
              to_notify = g_list_concat (to_notify, copy);

              break;
            }

          child = g_node_next_sibling(child);
        }

      if (child != NULL) /* we found a child, scan below it */
        cur = child;
      else               /* end of the line */
        cur = NULL;

      ++i;
    }
  
  g_strfreev(dirs);

  g_list_foreach (to_notify, (GFunc) listener_ref, NULL);
  
  notify_listener_list ((MateConfListeners*)lt,
                        to_notify, key,
                        callback, user_data);

  g_list_foreach (to_notify, (GFunc) listener_unref, NULL);

  g_list_free (to_notify);
}
예제 #18
0
파일: http_request.c 프로젝트: nakal/resow
static GSList * request_parse_accepts_properties(const gchar *qstr,
	const gchar *def_property) {

	GSList *list = NULL;
	gchar **v, **p;

	v = g_strsplit_set(qstr, ",\n", 0);
	if (v==NULL) {
		DEBUG_PRINT("g_strsplit returned NULL");
		return NULL;
	}

	for (p=v; *p; p++) {

		gchar **vv=NULL;
		gchar *prop, *qual;
		request_property_quality_t *e;

		e=g_malloc(sizeof(request_property_quality_t));
		if (e==NULL) {
			request_free_accepts_properties(list);
			g_strfreev(v);
			return NULL;
		}

		vv=g_strsplit(*p, ";", 2);
		if (vv==NULL) {
			DEBUG_PRINT("g_strsplit returned NULL");
			g_free(e);
			continue;
		}

		prop=g_strdup(*vv);
		if (prop==NULL) {
			DEBUG_PRINT("g_strdup returned NULL");
			g_strfreev(vv);
			g_free(e);
			continue;
		}

		qual=g_strdup(*(vv+1)!=NULL ? *(vv+1): "1.0");
		if (prop==NULL) {
			DEBUG_PRINT("g_strdup returned NULL");
			g_free(prop);
			g_strfreev(vv);
			g_free(e);
			continue;
		}

		g_strfreev(vv);

		g_strchug(qual); if (strlen(qual)>5) qual[5]=0;
		e->property = prop;
		if (strncmp(qual, "q=0.", 2)==0) {
			unsigned int mul=100, d=3;

			e->quality_per_mil=0;
			while (g_ascii_isdigit(qual[++d])) {
				e->quality_per_mil+=
					(unsigned int)(qual[d]-'0')*mul;
				mul/=10;
			}
		} else {
			/* XXX else we assume 1.xxx for everything invalid */
			e->quality_per_mil = 1000;
		}

		list=g_slist_insert_sorted(list, e, request_quality_compare);

		g_free(qual);
	}

	g_strfreev(v);

	/* we append default with quality 1000, if nothing requested */
	if (list==NULL && def_property!=NULL) {
		request_property_quality_t *e;

		e=g_malloc(sizeof(request_property_quality_t));
		if (e==NULL) return NULL;

		e->property=g_strdup(def_property);
		e->quality_per_mil=RESOW_CGI_QUALITY_MAX;

		list=g_slist_append(list, e);
	}

	return list;
}
예제 #19
0
/**
 * r_new_pnode:
 *
 * Create a new parsing node.
 **/
static RParserNode *
r_new_pnode(guint8 *key)
{
  RParserNode *parser_node = g_new0(RParserNode, 1);
  gchar **params = g_strsplit(key, ":", 3);
  guint params_len = g_strv_length(params);

  parser_node->first = 0;
  parser_node->last = 255;

  if (strcmp(params[0], "IPv4") == 0)
    {
      parser_node->parse = r_parser_ipv4;
      parser_node->type = RPT_IPV4;
      parser_node->first = '0';
      parser_node->last = '9';
    }
  else if (strcmp(params[0], "IPv6") == 0)
    {
      parser_node->parse = r_parser_ipv6;
      parser_node->type = RPT_IPV6;
    }
  else if (strcmp(params[0], "IPvANY") == 0)
    {
      parser_node->parse = r_parser_ip;
      parser_node->type = RPT_IP;
    }
  else if (strcmp(params[0], "MACADDR") == 0)
    {
      parser_node->parse = r_parser_macaddr;
      parser_node->type = RPT_MACADDR;
    }
  else if (strcmp(params[0], "NUMBER") == 0)
    {
      parser_node->parse = r_parser_number;
      parser_node->type = RPT_NUMBER;
      parser_node->first = '-';
      parser_node->last = '9';
    }
  else if (strcmp(params[0], "FLOAT") == 0 || strcmp(params[0], "DOUBLE") == 0)
    {
      /* DOUBLE is a deprecated alias for FLOAT */
      parser_node->parse = r_parser_float;
      parser_node->type = RPT_FLOAT;
      parser_node->first = '-';
      parser_node->last = '9';
    }
  else if (strcmp(params[0], "STRING") == 0)
    {
      parser_node->parse = r_parser_string;
      parser_node->type = RPT_STRING;
    }
  else if (strcmp(params[0], "ESTRING") == 0)
    {
      if (params_len == 3)
        {
          parser_node->parse = r_parser_estring_c;
          parser_node->type = RPT_ESTRING;

          if (params[2] && (strlen(params[2]) > 1))
            {
              gint len = strlen(params[2]);
              parser_node->state = GINT_TO_POINTER(len);
              parser_node->parse = r_parser_estring;
            }
        }
      else
        {
          g_free(parser_node);
          msg_error("Missing ESTRING parser parameters",
                     evt_tag_str("type", params[0]), NULL);
          parser_node = NULL;
        }

    }
#if ENABLE_PCRE
  else if (strcmp(params[0], "PCRE") == 0)
    {
      parser_node->parse = r_parser_pcre;
      parser_node->type = RPT_PCRE;

      if (params[2])
        {
          parser_node->free_state = r_parser_pcre_free_state;
          parser_node->state = r_parser_pcre_compile_state(params[2]);
        }
      else
        {
          g_free(parser_node);
          msg_error("Missing regular expression as 3rd argument",
                     evt_tag_str("type", params[0]), NULL);
          parser_node = NULL;
        }
    }
#endif
  else if (strcmp(params[0], "ANYSTRING") == 0)
    {
      parser_node->parse = r_parser_anystring;
      parser_node->type = RPT_ANYSTRING;
    }
  else if (strcmp(params[0], "SET") == 0)
    {
      if (params_len == 3)
        {
          parser_node->parse = r_parser_set;
          parser_node->type = RPT_SET;
        }
      else
        {
          g_free(parser_node);
          msg_error("Missing SET parser parameters",
                     evt_tag_str("type", params[0]), NULL);
          parser_node = NULL;
        }
    }
  else if (strcmp(params[0], "EMAIL") == 0)
    {
      parser_node->parse = r_parser_email;
      parser_node->type = RPT_EMAIL;
    }
  else if (strcmp(params[0], "HOSTNAME") == 0)
    {
      parser_node->parse = r_parser_hostname;
      parser_node->type = RPT_HOSTNAME;
    }
  else if (strcmp(params[0], "LLADDR") == 0)
    {
      parser_node->parse = r_parser_lladdr;
      parser_node->type = RPT_LLADDR;
    }
  else if (g_str_has_prefix(params[0], "QSTRING"))
    {
      if (params_len == 3)
        {
          gchar *state = (gchar *) &(parser_node->state);

          parser_node->parse = r_parser_qstring;
          parser_node->type = RPT_QSTRING;
          parser_node->first = params[2][0];
          parser_node->last = params[2][0];

          if (params_len >= 2 && params[2] && strlen(params[2]) == 2)
            state[0] = params[2][1];
          else
            state[0] = params[2][0];
        }
      else
        {
          g_free(parser_node);
          msg_error("Missing QSTRING parser parameters",
                     evt_tag_str("type", params[0]), NULL);
          parser_node = NULL;
        }
    }
  else
    {
      g_free(parser_node);
      msg_error("Unknown parser type specified",
                 evt_tag_str("type", params[0]), NULL);
      parser_node = NULL;
    }

  if (parser_node && params[1])
    {
      if (params[1][0])
        parser_node->handle = log_msg_get_value_handle(params[1]);

      if (params[2])
        parser_node->param = g_strdup(params[2]);
    }


  g_strfreev(params);

  return parser_node;
}
예제 #20
0
파일: api.c 프로젝트: anatol/libsigrok
static GSList *fluke_scan(struct sr_dev_driver *di, const char *conn,
		const char *serialcomm)
{
	struct sr_dev_inst *sdi;
	struct drv_context *drvc;
	struct dev_context *devc;
	struct sr_serial_dev_inst *serial;
	GSList *devices;
	int retry, len, i, s;
	char buf[128], *b, **tokens;

	serial = sr_serial_dev_inst_new(conn, serialcomm);

	if (serial_open(serial, SERIAL_RDWR) != SR_OK)
		return NULL;

	drvc = di->priv;
	b = buf;
	retry = 0;
	devices = NULL;
	/* We'll try the discovery sequence three times in case the device
	 * is not in an idle state when we send ID. */
	while (!devices && retry < 3) {
		retry++;
		serial_flush(serial);
		if (serial_write_blocking(serial, "ID\r", 3, SERIAL_WRITE_TIMEOUT_MS) < 0) {
			sr_err("Unable to send ID string");
			continue;
		}

		/* Response is first a CMD_ACK byte (ASCII '0' for OK,
		 * or '1' to signify an error. */
		len = 128;
		serial_readline(serial, &b, &len, 150);
		if (len != 1)
			continue;
		if (buf[0] != '0')
			continue;

		/* If CMD_ACK was OK, ID string follows. */
		len = 128;
		serial_readline(serial, &b, &len, 850);
		if (len < 10)
			continue;
		if (strcspn(buf, ",") < 15)
			/* Looks like it's comma-separated. */
			tokens = g_strsplit(buf, ",", 3);
		else
			/* Fluke 199B, at least, uses semicolon. */
			tokens = g_strsplit(buf, ";", 3);
		if (!strncmp("FLUKE", tokens[0], 5)
				&& tokens[1] && tokens[2]) {
			for (i = 0; supported_flukedmm[i].model; i++) {
				if (strcmp(supported_flukedmm[i].modelname, tokens[0] + 6))
					continue;
				/* Skip leading spaces in version number. */
				for (s = 0; tokens[1][s] == ' '; s++);
				sdi = g_malloc0(sizeof(struct sr_dev_inst));
				sdi->status = SR_ST_INACTIVE;
				sdi->vendor = g_strdup("Fluke");
				sdi->model = g_strdup(tokens[0] + 6);
				sdi->version = g_strdup(tokens[1] + s);
				devc = g_malloc0(sizeof(struct dev_context));
				devc->profile = &supported_flukedmm[i];
				sdi->inst_type = SR_INST_SERIAL;
				sdi->conn = serial;
				sdi->priv = devc;
				sdi->driver = di;
				sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "P1");
				drvc->instances = g_slist_append(drvc->instances, sdi);
				devices = g_slist_append(devices, sdi);
				break;
			}
		}
		g_strfreev(tokens);
		if (devices)
			/* Found one. */
			break;
	}
	serial_close(serial);
	if (!devices)
		sr_serial_dev_inst_free(serial);

	return devices;
}
예제 #21
0
struct netdev *get_configs() {
	int ncfgs = 0;
	struct netdev *ret, *tmpdev;
	struct dirent **cfgs;
	int x;
	
	ret = NULL;
	
	if ((ncfgs = scandir("/etc/sysconfig/network-scripts",&cfgs,
			     isCfg, alphasort)) == -1) {
		return ret;
	}
	for (x = 0; x < ncfgs; x++ ) {
		char *path;
		char *devname, *hwaddr;
		int vlan;
		gchar *contents, **lines;
		int i;
		
		devname = hwaddr = contents = NULL;
		lines = NULL;
		vlan = 0;
		if (asprintf(&path,"/etc/sysconfig/network-scripts/%s",
			     cfgs[x]->d_name) == -1)
			continue;
		g_file_get_contents(path, &contents, NULL, NULL);
		if (!contents)
			continue;
		lines = g_strsplit(contents,"\n", 0);
		for (i = 0; lines[i]; i++) {
			if (g_str_has_prefix(lines[i],"DEVICE=")) {
				devname = dequote(lines[i] + 7, NULL);
				/* ignore alias devices */
				if (strchr(devname,':'))
					devname = NULL;
			}
#if defined(__s390__) || defined(__s390x__)
			if (g_str_has_prefix(lines[i],"SUBCHANNELS=")) {
				hwaddr = dequote(lines[i] + 12, NULL);
			} else if (g_str_has_prefix(lines[i],"HWADDR=")) {
				hwaddr = dequote(lines[i] + 7, NULL);
			}
#else
			if (g_str_has_prefix(lines[i],"HWADDR=")) {
				hwaddr = dequote(lines[i] + 7, NULL);
			}
#endif
			if (g_str_has_prefix(lines[i],"VLAN=yes")) {
				vlan=1;
			}
		}
		if (!devname || !hwaddr || vlan) {
			g_free(contents);
			g_strfreev(lines);
			continue;
		}
		tmpdev = calloc(1, sizeof(struct netdev));
		tmpdev->dev = g_strstrip(g_strdup(devname));
		tmpdev->hwaddr = g_strstrip(g_strdup(hwaddr));
		if (ret)
			tmpdev->next = ret;
		ret = tmpdev;
		g_free(contents);
		g_strfreev(lines);
	}
	free(cfgs);
	return ret;
}
예제 #22
0
파일: gsk-wget.c 프로젝트: davebenson/gsk
/* --- Main --- */
int main(int argc, char **argv)
{
  int i;
  GError *error = NULL;
  GskUrl *url = NULL;
  GskUrlTransfer *transfer;
  add_http_headers = g_ptr_array_new ();

  gsk_init_without_threads (&argc, &argv);

  /* parse arguments */
  for (i = 1; i < argc; i++)
    {
      const char *arg = argv[i];
      if (strcmp (arg, "--ssl") == 0)
        use_ssl = TRUE;
      else if (g_str_has_prefix (arg, "--ssl="))
        {
          char **pieces;
          use_ssl = TRUE;
          pieces = g_strsplit (strchr(arg,'=') + 1, ":", 3);
          if (pieces[0] && pieces[0][0])
            ssl_cert = pieces[0];
          if (pieces[0] && pieces[1] && pieces[1][0])
            ssl_key = pieces[1];
          if (pieces[0] && pieces[1] && pieces[2] && pieces[2][0])
            ssl_password = pieces[2];
          g_free (pieces);
        }
      else if (g_str_has_prefix (arg, "--upload-data="))
        upload_string = strchr (arg, '=') + 1;
      else if (g_str_has_prefix (arg, "--upload-file="))
        upload_filename = strchr (arg, '=') + 1;
      else if (g_str_has_prefix (arg, "--add-http-header="))
        g_ptr_array_add (add_http_headers, strchr (arg, '=') + 1);
      else if (g_str_has_prefix (arg, "--user-agent="))
	user_agent = strchr (arg, '=') + 1;
      else if (g_str_has_prefix (arg, "--timeout="))
        timeout = atoi (strchr (arg, '=') + 1);
      else if (strcmp (arg, "--dont-quit-when-done") == 0)
        quit_when_done = FALSE;
      else if (arg[0] == '-')
        usage ();
      else if (url == NULL)
        {
          url = gsk_url_new (arg, &error);
          if (url == NULL)
            g_error ("error parsing url %s: %s", arg, error->message);
        }
      else
        g_error ("too many arguments (at %s)", arg);
    }

  if (url == NULL)
    usage ();

  transfer = gsk_url_transfer_new (url);
  if (transfer == NULL)
    g_error ("cannot make transfer for %s", gsk_url_to_string (url));
  if (upload_string != NULL)
    gsk_url_transfer_set_upload (transfer, make_upload_from_string, NULL, NULL);
  else if (upload_filename != NULL)
    gsk_url_transfer_set_upload (transfer, make_upload_from_filename, NULL, NULL);

  if (timeout >= 0)
    gsk_url_transfer_set_timeout (transfer, timeout);

  if (GSK_IS_URL_TRANSFER_HTTP (transfer))
    {
      gsk_g_ptr_array_foreach (add_http_headers,
                               add_http_header_line_to_transfer,
                               transfer);
      if (user_agent)
	gsk_url_transfer_http_set_user_agent (GSK_URL_TRANSFER_HTTP (transfer),
					      user_agent);
    }
  else
    {
      if (add_http_headers->len > 0)
        g_error ("--add-http-header= specified for non-HTTP url");
    }

  gsk_url_transfer_set_handler (transfer,
                                handle_transfer_done,
                                NULL,
                                handle_transfer_destroyed);

  if (!gsk_url_transfer_start (transfer, &error))
    g_error ("error starting URL transfer: %s", error->message);
  g_object_unref (transfer);
  g_object_unref (url);

  return gsk_main_run();
}
예제 #23
0
파일: api.c 프로젝트: russdill/libsigrok
static GSList *scan(GSList *options)
{
	struct sr_dev_inst *sdi;
	struct drv_context *drvc;
	struct dev_context *devc;
	struct sr_config *src;
	struct sr_probe *probe;
	struct sr_serial_dev_inst *serial;
	GSList *l, *devices;
	int len, i;
	const char *conn, *serialcomm;
	char *buf, **tokens;

	drvc = di->priv;
	drvc->instances = NULL;

	devices = NULL;
	conn = serialcomm = NULL;
	for (l = options; l; l = l->next) {
		src = l->data;
		switch (src->key) {
		case SR_CONF_CONN:
			conn = g_variant_get_string(src->data, NULL);
			break;
		case SR_CONF_SERIALCOMM:
			serialcomm = g_variant_get_string(src->data, NULL);
			break;
		}
	}
	if (!conn)
		return NULL;
	if (!serialcomm)
		serialcomm = SERIALCOMM;

	if (!(serial = sr_serial_dev_inst_new(conn, serialcomm)))
		return NULL;

	if (serial_open(serial, SERIAL_RDWR | SERIAL_NONBLOCK) != SR_OK)
		return NULL;

	serial_flush(serial);
	if (serial_write(serial, "*IDN?\r\n", 7) == -1) {
		sr_err("Unable to send identification string: %s.",
		       strerror(errno));
		return NULL;
	}

	len = 128;
	if (!(buf = g_try_malloc(len))) {
		sr_err("Serial buffer malloc failed.");
		return NULL;
	}
	serial_readline(serial, &buf, &len, 150);
	if (!len)
		return NULL;

	tokens = g_strsplit(buf, ",", 4);
	if (!strcmp("Agilent Technologies", tokens[0])
			&& tokens[1] && tokens[2] && tokens[3]) {
		for (i = 0; supported_agdmm[i].model; i++) {
			if (strcmp(supported_agdmm[i].modelname, tokens[1]))
				continue;
			if (!(sdi = sr_dev_inst_new(0, SR_ST_INACTIVE, tokens[0],
					tokens[1], tokens[3])))
				return NULL;
			if (!(devc = g_try_malloc0(sizeof(struct dev_context)))) {
				sr_err("Device context malloc failed.");
				return NULL;
			}
			devc->profile = &supported_agdmm[i];
			devc->cur_mq = -1;
			sdi->inst_type = SR_INST_SERIAL;
			sdi->conn = serial;
			sdi->priv = devc;
			sdi->driver = di;
			if (!(probe = sr_probe_new(0, SR_PROBE_ANALOG, TRUE, "P1")))
				return NULL;
			sdi->probes = g_slist_append(sdi->probes, probe);
			drvc->instances = g_slist_append(drvc->instances, sdi);
			devices = g_slist_append(devices, sdi);
			break;
		}
	}
	g_strfreev(tokens);
	g_free(buf);

	serial_close(serial);
	if (!devices)
		sr_serial_dev_inst_free(serial);

	return devices;
}
예제 #24
0
파일: httpconn.c 프로젝트: bf4/pidgin-mac
static gboolean
msn_httpconn_parse_data(MsnHttpConn *httpconn, const char *buf,
						size_t size, char **ret_buf, size_t *ret_size,
						gboolean *error)
{
	const char *s, *c;
	char *header, *body;
	const char *body_start;
	char *tmp;
	size_t body_len = 0;
	gboolean wasted = FALSE;

	g_return_val_if_fail(httpconn != NULL, FALSE);
	g_return_val_if_fail(buf      != NULL, FALSE);
	g_return_val_if_fail(size      > 0,    FALSE);
	g_return_val_if_fail(ret_buf  != NULL, FALSE);
	g_return_val_if_fail(ret_size != NULL, FALSE);
	g_return_val_if_fail(error    != NULL, FALSE);

#if 0
	purple_debug_info("msn", "HTTP: parsing data {%s}\n", buf);
#endif

	/* Healthy defaults. */
	body = NULL;

	*ret_buf  = NULL;
	*ret_size = 0;
	*error    = FALSE;

	/* First, some tests to see if we have a full block of stuff. */
	if (((strncmp(buf, "HTTP/1.1 200 OK\r\n", 17) != 0) &&
		 (strncmp(buf, "HTTP/1.1 100 Continue\r\n", 23) != 0)) &&
		((strncmp(buf, "HTTP/1.0 200 OK\r\n", 17) != 0) &&
		 (strncmp(buf, "HTTP/1.0 100 Continue\r\n", 23) != 0)))
	{
		*error = TRUE;

		return FALSE;
	}

	if (strncmp(buf, "HTTP/1.1 100 Continue\r\n", 23) == 0)
	{
		if ((s = strstr(buf, "\r\n\r\n")) == NULL)
			return FALSE;

		s += 4;

		if (*s == '\0')
		{
			*ret_buf = g_strdup("");
			*ret_size = 0;

			msn_httpconn_process_queue(httpconn);

			return TRUE;
		}

		buf = s;
		size -= (s - buf);
	}

	if ((s = strstr(buf, "\r\n\r\n")) == NULL)
		/* Need to wait for the full HTTP header to arrive */
		return FALSE;

	s += 4; /* Skip \r\n */
	header = g_strndup(buf, s - buf);
	body_start = s;
	body_len = size - (body_start - buf);

	if ((s = purple_strcasestr(header, "Content-Length: ")) != NULL)
	{
		int tmp_len;

		s += strlen("Content-Length: ");

		if ((c = strchr(s, '\r')) == NULL)
		{
			g_free(header);

			return FALSE;
		}

		tmp = g_strndup(s, c - s);
		tmp_len = atoi(tmp);
		g_free(tmp);

		if (body_len != tmp_len)
		{
			/* Need to wait for the full packet to arrive */

			g_free(header);

#if 0
			purple_debug_warning("msn",
							   "body length (%d) != content length (%d)\n",
							   body_len, tmp_len);
#endif

			return FALSE;
		}
	}

	body = g_malloc0(body_len + 1);
	memcpy(body, body_start, body_len);

#ifdef MSN_DEBUG_HTTP
	purple_debug_misc("msn", "Incoming HTTP buffer (header): {%s\r\n}\n",
					header);
#endif

	/* Now we should be able to process the data. */
	if ((s = purple_strcasestr(header, "X-MSN-Messenger: ")) != NULL)
	{
		char *full_session_id, *gw_ip, *session_action;
		char *t, *session_id;
		char **elems, **cur, **tokens;

		full_session_id = gw_ip = session_action = NULL;

		s += strlen("X-MSN-Messenger: ");

		if ((c = strchr(s, '\r')) == NULL)
		{
			msn_session_set_error(httpconn->session,
								  MSN_ERROR_HTTP_MALFORMED, NULL);
			purple_debug_error("msn", "Malformed X-MSN-Messenger field.\n{%s}\n",
							 buf);

			g_free(body);
			return FALSE;
		}

		tmp = g_strndup(s, c - s);

		elems = g_strsplit(tmp, "; ", 0);

		for (cur = elems; *cur != NULL; cur++)
		{
			tokens = g_strsplit(*cur, "=", 2);

			if (strcmp(tokens[0], "SessionID") == 0)
				full_session_id = tokens[1];
			else if (strcmp(tokens[0], "GW-IP") == 0)
				gw_ip = tokens[1];
			else if (strcmp(tokens[0], "Session") == 0)
				session_action = tokens[1];
			else
				g_free(tokens[1]);

			g_free(tokens[0]);
			/* Don't free each of the tokens, only the array. */
			g_free(tokens);
		}

		g_strfreev(elems);

		g_free(tmp);

		if ((session_action != NULL) && (strcmp(session_action, "close") == 0))
			wasted = TRUE;

		g_free(session_action);

		t = strchr(full_session_id, '.');
		session_id = g_strndup(full_session_id, t - full_session_id);

		if (!wasted)
		{
			g_free(httpconn->full_session_id);
			httpconn->full_session_id = full_session_id;

			g_free(httpconn->session_id);
			httpconn->session_id = session_id;

			g_free(httpconn->host);
			httpconn->host = gw_ip;
		}
		else
		{
			MsnServConn *servconn;

			/* It's going to die. */
			/* poor thing */

			servconn = httpconn->servconn;

			/* I'll be honest, I don't fully understand all this, but this
			 * causes crashes, Stu. */
			/* if (servconn != NULL)
				servconn->wasted = TRUE; */

			g_free(full_session_id);
			g_free(session_id);
			g_free(gw_ip);
		}
	}

	g_free(header);

	*ret_buf  = body;
	*ret_size = body_len;

	msn_httpconn_process_queue(httpconn);

	return TRUE;
}
예제 #25
0
static int
display_file_selector(int the_mode,
		      GcomprisBoard *gcomprisBoard,
		      gchar *rootdir,
		      gchar *file_exts,
		      FileSelectorCallBack iscb,
		      void *user_context)
{
  gchar            *full_rootdir;

  mode = the_mode;

  /* Get the coordinate x y of the control area from the skin */
  control_area_x1   = gc_skin_get_number_default("gcompris/fileselectx", 85);
  control_area_y1   = gc_skin_get_number_default("gcompris/fileselecty", 80);
  directory_label_y = gc_skin_get_number_default("gcompris/fileselectdiry", 180);

  if(rootitem)
    return 0;

  gc_bar_hide(TRUE);

  gc_board_pause(TRUE);

  fileSelectorCallBack=iscb;

  rootitem = goo_canvas_group_new (goo_canvas_get_root_item(gc_get_canvas()),
				   NULL);

  goo_canvas_svg_new (rootitem,
			     gc_skin_rsvg_get(),
			     "svg-id", "#FILE_SELECTOR",
			     "pointer-events", GOO_CANVAS_EVENTS_NONE,
			     NULL);

  /* Entry area */
  widget_entry = gtk_entry_new ();

  if(mode==MODE_SAVE)
    gtk_entry_set_max_length(GTK_ENTRY(widget_entry), 30);

  goo_canvas_widget_new (rootitem,
				GTK_WIDGET(widget_entry),
				control_area_x1,
				control_area_y1,
				230.0,
				30.0,
				NULL);

  g_signal_connect(GTK_OBJECT(widget_entry), "activate",
		   G_CALLBACK(entry_enter_callback),
		   widget_entry);

  gtk_widget_show(widget_entry);

  /*
   * Create the combo with the file types
   * ------------------------------------
   */
  if(mode==MODE_SAVE && file_exts && *file_exts != '\0')
  {
    gchar **all_type = g_strsplit(file_exts, " ", 0);
    guint i = 0;

    gtk_combo_filetypes = GTK_WIDGET(gtk_combo_box_new_text());

    /* Extract first string */
    while (all_type[i])
      gtk_combo_box_append_text(GTK_COMBO_BOX(gtk_combo_filetypes),
				g_strdup(all_type[i++]) );

    g_strfreev(all_type);

    goo_canvas_widget_new (rootitem,
			   gtk_combo_filetypes,
			   control_area_x1 + 400,
			   control_area_y1,
			   250.0,
			   35.0,
			   NULL);

    gtk_widget_show(gtk_combo_filetypes);
    gtk_combo_box_set_active(GTK_COMBO_BOX(gtk_combo_filetypes), 0);
  }

  /*
   * Buttons
   * -------
   */

  // CANCEL
  gc_util_button_text_svg(rootitem,
			  BOARDWIDTH * 1/3,
			  BOARDHEIGHT - 32,
			  "#BUTTON_TEXT",
			  _("CANCEL"),
			  (GCallback) item_event_file_selector,
			  "/cancel/");
  // OK
  gc_util_button_text_svg(rootitem,
			  BOARDWIDTH * 2/3,
			  BOARDHEIGHT - 32,
			  "#BUTTON_TEXT",
			  (mode==MODE_LOAD ? _("LOAD") : _("SAVE")),
			  (GCallback) item_event_file_selector,
			  "/ok/");

  file_selector_displayed = TRUE;

  full_rootdir = g_strconcat(gc_prop_get()->user_dir, "/", rootdir, NULL);
  gc_util_create_rootdir(full_rootdir);

  current_rootdir = full_rootdir;
  current_user_context = user_context;

  display_files(rootitem, full_rootdir);

  return 0;

}
예제 #26
0
/**
 * gst_rtsp_transport_parse:
 * @str: a transport string
 * @transport: a #GstRTSPTransport
 *
 * Parse the RTSP transport string @str into @transport.
 *
 * Returns: a #GstRTSPResult.
 */
GstRTSPResult
gst_rtsp_transport_parse (const gchar * str, GstRTSPTransport * transport)
{
  gchar **split, *down, **transp = NULL;
  guint transport_params = 0;
  gint i, count;

  g_return_val_if_fail (transport != NULL, GST_RTSP_EINVAL);
  g_return_val_if_fail (str != NULL, GST_RTSP_EINVAL);

  gst_rtsp_transport_init (transport);

  /* case insensitive */
  down = g_ascii_strdown (str, -1);

  split = g_strsplit (down, ";", 0);
  g_free (down);

  /* First field contains the transport/profile/lower_transport */
  if (split[0] == NULL)
    goto invalid_transport;

  transp = g_strsplit (split[0], "/", 0);

  if (transp[0] == NULL || transp[1] == NULL)
    goto invalid_transport;

  for (i = 0; transports[i].name; i++)
    if (strcmp (transp[0], transports[i].name) == 0)
      break;
  transport->trans = transports[i].mode;

  if (transport->trans != GST_RTSP_TRANS_RDT) {
    for (i = 0; profiles[i].name; i++)
      if (strcmp (transp[1], profiles[i].name) == 0)
        break;
    transport->profile = profiles[i].profile;
    count = 2;
  } else {
    /* RDT has transport/lower_transport */
    transport->profile = GST_RTSP_PROFILE_AVP;
    count = 1;
  }

  if (transp[count] != NULL) {
    for (i = 0; ltrans[i].name; i++)
      if (strcmp (transp[count], ltrans[i].name) == 0)
        break;
    transport->lower_transport = ltrans[i].ltrans;
  } else {
    /* specifying the lower transport is optional */
    if (transport->trans == GST_RTSP_TRANS_RTP &&
        transport->profile == GST_RTSP_PROFILE_AVP)
      transport->lower_transport = GST_RTSP_LOWER_TRANS_UDP_MCAST;
    else
      transport->lower_transport = GST_RTSP_LOWER_TRANS_UNKNOWN;
  }

  g_strfreev (transp);
  transp = NULL;

  if (transport->trans == GST_RTSP_TRANS_UNKNOWN ||
      transport->profile == GST_RTSP_PROFILE_UNKNOWN ||
      transport->lower_transport == GST_RTSP_LOWER_TRANS_UNKNOWN)
    goto unsupported_transport;

  i = 1;
  while (split[i]) {
    if (strcmp (split[i], "multicast") == 0) {
      RTSP_TRANSPORT_PARAMETER_IS_UNIQUE (RTSP_TRANSPORT_DELIVERY);
      if (transport->lower_transport == GST_RTSP_LOWER_TRANS_TCP)
        goto invalid_transport;
      transport->lower_transport = GST_RTSP_LOWER_TRANS_UDP_MCAST;
    } else if (strcmp (split[i], "unicast") == 0) {
      RTSP_TRANSPORT_PARAMETER_IS_UNIQUE (RTSP_TRANSPORT_DELIVERY);
      if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST)
        transport->lower_transport = GST_RTSP_LOWER_TRANS_UDP;
    } else if (g_str_has_prefix (split[i], "destination=")) {
      RTSP_TRANSPORT_PARAMETER_IS_UNIQUE (RTSP_TRANSPORT_DESTINATION);
      transport->destination = g_strdup (split[i] + 12);
    } else if (g_str_has_prefix (split[i], "source=")) {
      RTSP_TRANSPORT_PARAMETER_IS_UNIQUE (RTSP_TRANSPORT_SOURCE);
      transport->source = g_strdup (split[i] + 7);
    } else if (g_str_has_prefix (split[i], "layers=")) {
      RTSP_TRANSPORT_PARAMETER_IS_UNIQUE (RTSP_TRANSPORT_LAYERS);
      transport->layers = strtoul (split[i] + 7, NULL, 10);
    } else if (g_str_has_prefix (split[i], "mode=")) {
      RTSP_TRANSPORT_PARAMETER_IS_UNIQUE (RTSP_TRANSPORT_MODE);
      parse_mode (transport, split[i] + 5);
      if (!transport->mode_play && !transport->mode_record)
        goto invalid_transport;
    } else if (strcmp (split[i], "append") == 0) {
      RTSP_TRANSPORT_PARAMETER_IS_UNIQUE (RTSP_TRANSPORT_APPEND);
      transport->append = TRUE;
    } else if (g_str_has_prefix (split[i], "interleaved=")) {
      RTSP_TRANSPORT_PARAMETER_IS_UNIQUE (RTSP_TRANSPORT_INTERLEAVED);
      parse_range (split[i] + 12, &transport->interleaved);
      if (!IS_VALID_INTERLEAVE_RANGE (transport->interleaved))
        goto invalid_transport;
    } else if (g_str_has_prefix (split[i], "ttl=")) {
      RTSP_TRANSPORT_PARAMETER_IS_UNIQUE (RTSP_TRANSPORT_TTL);
      transport->ttl = strtoul (split[i] + 4, NULL, 10);
      if (transport->ttl >= 256)
        goto invalid_transport;
    } else if (g_str_has_prefix (split[i], "port=")) {
      RTSP_TRANSPORT_PARAMETER_IS_UNIQUE (RTSP_TRANSPORT_PORT);
      if (parse_range (split[i] + 5, &transport->port)) {
        if (!IS_VALID_PORT_RANGE (transport->port))
          goto invalid_transport;
      }
    } else if (g_str_has_prefix (split[i], "client_port=")) {
      RTSP_TRANSPORT_PARAMETER_IS_UNIQUE (RTSP_TRANSPORT_CLIENT_PORT);
      if (parse_range (split[i] + 12, &transport->client_port)) {
        if (!IS_VALID_PORT_RANGE (transport->client_port))
          goto invalid_transport;
      }
    } else if (g_str_has_prefix (split[i], "server_port=")) {
      RTSP_TRANSPORT_PARAMETER_IS_UNIQUE (RTSP_TRANSPORT_SERVER_PORT);
      if (parse_range (split[i] + 12, &transport->server_port)) {
        if (!IS_VALID_PORT_RANGE (transport->server_port))
          goto invalid_transport;
      }
    } else if (g_str_has_prefix (split[i], "ssrc=")) {
      RTSP_TRANSPORT_PARAMETER_IS_UNIQUE (RTSP_TRANSPORT_SSRC);
      transport->ssrc = strtoul (split[i] + 5, NULL, 16);
    } else {
      /* unknown field... */
      g_warning ("unknown transport field \"%s\"", split[i]);
    }
    i++;
  }
  g_strfreev (split);

  return GST_RTSP_OK;

unsupported_transport:
  {
    g_strfreev (split);
    return GST_RTSP_ERROR;
  }
invalid_transport:
  {
    g_strfreev (transp);
    g_strfreev (split);
    return GST_RTSP_EINVAL;
  }
}
예제 #27
0
gboolean gebr_comm_protocol_receive_data(struct gebr_comm_protocol *protocol, GString * data)
{
	gchar **splits;
	gboolean reached_end = FALSE;

	while (!reached_end && data->len) {
		gsize missing;

		/* if so, this is a new message; otherwise, another part
		 * of the argument of protocol->message
		 */
		if (!protocol->message->hash) {
			gint erase_len;
			gchar *strtol_endptr;

			splits = g_strsplit(data->str, " ", 3);
			gint n_tokens = g_strv_length(splits);
			if (n_tokens < 2)
				goto err;

			/* code */
			if (g_hash_table_lookup(gebr_comm_protocol_defs.hash_table, splits[0]) == NULL) {
				g_string_assign(data, "");
				goto err;
			}
			protocol->message->hash = g_str_hash(splits[0]);
			/* argument size */
			strtol_endptr = NULL;
			protocol->message->argument_size = strtol(splits[1], &strtol_endptr, 10);
			if (errno == ERANGE)
				goto err;

			/* the missing bytes to complete the read of argument */
			missing = protocol->message->argument_size;
			/* erase code and size from data */
			erase_len = strlen(splits[0]) + 1 + strlen(splits[1]) + ((n_tokens == 2) ? 0 : 1);
			g_string_erase(data, 0, erase_len);

			g_strfreev(splits);
		} else {
			missing = protocol->message->argument_size - protocol->message->argument->len;
		}

		/* if so, protocol->message has now received its
		 * argument entirely using > because there must be a line feed.
		 */
		reached_end = data->len > missing; 
		if (reached_end) {
			struct gebr_comm_message *queued;

			g_string_append_len(protocol->message->argument, data->str, missing);
			g_string_erase(data, 0, missing + 1);

			/* add to the list of messages */
			queued = protocol->message;
			protocol->messages = g_list_prepend(protocol->messages, queued);
			protocol->message = gebr_comm_message_new();
		} else {
			g_string_append(protocol->message->argument, data->str);
			g_string_erase(data, 0, -1);
		}
	}

	return TRUE;

 err:	g_strfreev(splits);
	return FALSE;
}
예제 #28
0
bool PluginPackage::fetchInfo()
{
#if defined(XP_UNIX)
    if (!load())
        return false;

    NP_GetMIMEDescriptionFuncPtr NP_GetMIMEDescription = 0;
    NPP_GetValueProcPtr NPP_GetValue = 0;

    g_module_symbol(m_module, "NP_GetMIMEDescription", (void**)&NP_GetMIMEDescription);
    g_module_symbol(m_module, "NP_GetValue", (void**)&NPP_GetValue);

    if (!NP_GetMIMEDescription || !NPP_GetValue)
        return false;

    char* buffer = 0;
    NPError err = NPP_GetValue(0, NPPVpluginNameString, &buffer);
    if (err == NPERR_NO_ERROR)
        m_name = buffer;

    buffer = 0;
    err = NPP_GetValue(0, NPPVpluginDescriptionString, &buffer);
    if (err == NPERR_NO_ERROR) {
        m_description = buffer;
        determineModuleVersionFromDescription();
    }

    const gchar* types = NP_GetMIMEDescription();
    if (!types)
        return true;

    gchar** mimeDescs = g_strsplit(types, ";", -1);
    for (int i = 0; mimeDescs[i] && mimeDescs[i][0]; i++) {
        GOwnPtr<char> mime(g_utf8_strdown(mimeDescs[i], -1));
        gchar** mimeData = g_strsplit(mime.get(), ":", 3);
        if (g_strv_length(mimeData) < 3) {
            g_strfreev(mimeData);
            continue;
        }

        String description = String::fromUTF8(mimeData[2]);
        gchar** extensions = g_strsplit(mimeData[1], ",", -1);

        Vector<String> extVector;
        for (int j = 0; extensions[j]; j++)
            extVector.append(String::fromUTF8(extensions[j]));

        determineQuirks(mimeData[0]);
        m_mimeToExtensions.add(mimeData[0], extVector);
        m_mimeToDescriptions.add(mimeData[0], description);

        g_strfreev(extensions);
        g_strfreev(mimeData);
    }
    g_strfreev(mimeDescs);

    return true;
#else
    notImplemented();
    return false;
#endif
}
예제 #29
0
janus_turnrest_response *janus_turnrest_request(void) {
    janus_mutex_lock(&api_mutex);
    if(api_server == NULL) {
        janus_mutex_unlock(&api_mutex);
        return NULL;
    }
    /* Prepare the request URI */
    char query_string[512];
    g_snprintf(query_string, 512, "service=turn");
    if(api_key != NULL) {
        char buffer[256];
        g_snprintf(buffer, 256, "&api=%s", api_key);
        g_strlcat(query_string, buffer, 512);
    }
    char request_uri[1024];
    g_snprintf(request_uri, 1024, "%s?%s", api_server, query_string);
    JANUS_LOG(LOG_VERB, "Sending request: %s\n", request_uri);
    janus_mutex_unlock(&api_mutex);
    /* Prepare the libcurl context */
    CURLcode res;
    CURL *curl = curl_easy_init();
    if(curl == NULL) {
        JANUS_LOG(LOG_ERR, "libcurl error\n");
        return NULL;
    }
    curl_easy_setopt(curl, CURLOPT_URL, request_uri);
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    /* FIXME Some servers don't like a POST with no data */
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, query_string);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);	/* FIXME Max 10 seconds */
    /* For getting data, we use an helper struct and the libcurl callback */
    janus_turnrest_buffer data;
    data.buffer = malloc(1);
    data.size = 0;
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, janus_turnrest_callback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&data);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "Janus/1.0");
    /* Send the request */
    res = curl_easy_perform(curl);
    if(res != CURLE_OK) {
        JANUS_LOG(LOG_ERR, "Couldn't send the request: %s\n", curl_easy_strerror(res));
        free(data.buffer);
        curl_easy_cleanup(curl);
        return NULL;
    }
    /* Cleanup the libcurl context */
    curl_easy_cleanup(curl);
    /* Process the response */
    JANUS_LOG(LOG_VERB, "Got %zu bytes from the TURN REST API server\n", data.size);
    JANUS_LOG(LOG_VERB, "%s\n", data.buffer);
    json_error_t error;
    json_t *root = json_loads(data.buffer, 0, &error);
    if(!root) {
        JANUS_LOG(LOG_ERR, "Couldn't parse response: error on line %d: %s", error.line, error.text);
        free(data.buffer);
        return NULL;
    }
    free(data.buffer);
    json_t *username = json_object_get(root, "username");
    if(!username) {
        JANUS_LOG(LOG_ERR, "Invalid response: missing username\n");
        return NULL;
    }
    if(!json_is_string(username)) {
        JANUS_LOG(LOG_ERR, "Invalid response: username should be a string\n");
        return NULL;
    }
    json_t *password = json_object_get(root, "password");
    if(!password) {
        JANUS_LOG(LOG_ERR, "Invalid response: missing password\n");
        return NULL;
    }
    if(!json_is_string(password)) {
        JANUS_LOG(LOG_ERR, "Invalid response: password should be a string\n");
        return NULL;
    }
    json_t *ttl = json_object_get(root, "ttl");
    if(ttl && (!json_is_integer(ttl) || json_integer_value(ttl) < 0)) {
        JANUS_LOG(LOG_ERR, "Invalid response: ttl should be a positive integer\n");
        return NULL;
    }
    json_t *uris = json_object_get(root, "uris");
    if(!uris) {
        JANUS_LOG(LOG_ERR, "Invalid response: missing uris\n");
        return NULL;
    }
    if(!json_is_array(uris) || json_array_size(uris) == 0) {
        JANUS_LOG(LOG_ERR, "Invalid response: uris should be a non-empty array\n");
        return NULL;
    }
    /* Turn the response into a janus_turnrest_response object we can use */
    janus_turnrest_response *response = calloc(1, sizeof(janus_turnrest_response));
    response->username = g_strdup(json_string_value(username));
    response->password = g_strdup(json_string_value(password));
    response->ttl = ttl ? json_integer_value(ttl) : 0;
    response->servers = NULL;
    size_t i = 0;
    for(i=0; i<json_array_size(uris); i++) {
        json_t *uri = json_array_get(uris, i);
        if(uri == NULL || !json_is_string(uri)) {
            JANUS_LOG(LOG_WARN, "Skipping invalid TURN URI (not a string)...\n");
            continue;
        }
        const char *turn_uri = json_string_value(uri);
        if(strstr(turn_uri, "turn:") != turn_uri && strstr(turn_uri, "turns:") != turn_uri) {
            JANUS_LOG(LOG_WARN, "Skipping invalid TURN URI '%s' (not a TURN URI)...\n", turn_uri);
            continue;
        }
        janus_turnrest_instance *instance = calloc(1, sizeof(janus_turnrest_instance));
        instance->transport = NICE_RELAY_TYPE_TURN_UDP;
        if(strstr(turn_uri, "turns:") == turn_uri)
            instance->transport = NICE_RELAY_TYPE_TURN_TLS;
        else if(strstr(turn_uri, "transport=tcp") == turn_uri)
            instance->transport = NICE_RELAY_TYPE_TURN_TCP;
        gchar **parts = NULL;
        if(strstr(turn_uri, "?") != NULL) {
            parts = g_strsplit(turn_uri, "?", -1);
            turn_uri = parts[0];
        }
        gchar **uri_parts = g_strsplit(turn_uri, ":", -1);
        /* Resolve the TURN URI address */
        struct hostent *he = gethostbyname(uri_parts[1]);
        if(he == NULL) {
            JANUS_LOG(LOG_WARN, "Skipping invalid TURN URI '%s' (could not resolve the address)...\n", uri_parts[1]);
            g_strfreev(uri_parts);
            continue;
        }
        struct in_addr **addr_list = (struct in_addr **)he->h_addr_list;
        if(addr_list[0] == NULL) {
            JANUS_LOG(LOG_WARN, "Skipping invalid TURN URI '%s' (could not resolve the address)...\n", uri_parts[1]);
            g_strfreev(uri_parts);
            continue;
        }
        instance->server = g_strdup(inet_ntoa(*addr_list[0]));
        if(uri_parts[2] == NULL) {
            /* No port? USe 3478 by default */
            instance->port = 3478;
        } else {
            instance->port = atoi(uri_parts[2]);
        }
        g_strfreev(uri_parts);
        g_strfreev(parts);
        /* Add the server to the list */
        response->servers = g_list_append(response->servers, instance);
    }
    if(response->servers == NULL) {
        JANUS_LOG(LOG_ERR, "Couldn't find any valid TURN URI in the response...\n");
        janus_turnrest_response_destroy(response);
        return NULL;
    }
    /* Done */
    return response;
}
예제 #30
0
/* Given a table of DHCP options from the client, convert into an IP6Config */
static NMIP6Config *
ip6_options_to_config (NMDHCPClient *self)
{
	NMDHCPClientPrivate *priv;
	NMIP6Config *ip6_config = NULL;
	struct in6_addr tmp_addr;
	NMIP6Address *addr = NULL;
	char *str = NULL;
	GHashTableIter iter;
	gpointer key, value;

	g_return_val_if_fail (self != NULL, NULL);
	g_return_val_if_fail (NM_IS_DHCP_CLIENT (self), NULL);

	priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
	g_return_val_if_fail (priv->options != NULL, NULL);

	g_hash_table_iter_init (&iter, priv->options);
	while (g_hash_table_iter_next (&iter, &key, &value)) {
		nm_log_dbg (LOGD_DHCP6, "(%s): option '%s'=>'%s'",
		            priv->iface, (const char *) key, (const char *) value);
	}

	ip6_config = nm_ip6_config_new ();
	if (!ip6_config) {
		nm_log_warn (LOGD_DHCP6, "(%s): couldn't allocate memory for an IP6Config!", priv->iface);
		return NULL;
	}

	addr = nm_ip6_address_new ();
	if (!addr) {
		nm_log_warn (LOGD_DHCP6, "(%s): couldn't allocate memory for an IP6 Address!", priv->iface);
		goto error;
	}

	str = g_hash_table_lookup (priv->options, "new_ip6_address");
	if (str) {
		if (!inet_pton (AF_INET6, str, &tmp_addr)) {
			nm_log_warn (LOGD_DHCP6, "(%s): DHCP returned invalid address '%s'",
			             priv->iface);
			goto error;
		}

		nm_ip6_address_set_address (addr, &tmp_addr);
		nm_log_info (LOGD_DHCP6, "  address %s", str);
	} else {
		/* No address in managed mode is a hard error */
		if (priv->info_only == FALSE)
			goto error;

		/* But "info-only" setups don't necessarily need an address */
		nm_ip6_address_unref (addr);
		addr = NULL;
	}

	/* Only care about prefix if we got an address */
	if (addr) {
		str = g_hash_table_lookup (priv->options, "new_ip6_prefixlen");
		if (str) {
			long unsigned int prefix;

			errno = 0;
			prefix = strtoul (str, NULL, 10);
			if (errno != 0 || prefix > 128)
				goto error;

			nm_ip6_address_set_prefix (addr, (guint32) prefix);
			nm_log_info (LOGD_DHCP6, "  prefix %lu", prefix);
		}

		nm_ip6_config_take_address (ip6_config, addr);
		addr = NULL;
	}

	str = g_hash_table_lookup (priv->options, "new_host_name");
	if (str)
		nm_log_info (LOGD_DHCP6, "  hostname '%s'", str);

	str = g_hash_table_lookup (priv->options, "new_dhcp6_name_servers");
	if (str) {
		char **searches = g_strsplit (str, " ", 0);
		char **s;

		for (s = searches; *s; s++) {
			if (inet_pton (AF_INET6, *s, &tmp_addr) > 0) {
				nm_ip6_config_add_nameserver (ip6_config, &tmp_addr);
				nm_log_info (LOGD_DHCP6, "  nameserver '%s'", *s);
			} else
				nm_log_warn (LOGD_DHCP6, "ignoring invalid nameserver '%s'", *s);
		}
		g_strfreev (searches);
	}

	str = g_hash_table_lookup (priv->options, "new_dhcp6_domain_search");
	if (str)
		process_domain_search (str, ip6_add_domain_search, ip6_config);

	return ip6_config;

error:
	if (addr)
		nm_ip6_address_unref (addr);
	g_object_unref (ip6_config);
	return NULL;
}