/**
 * couchdb_document_contact_im_new:
 * @uuid: A unique ID
 * @address: IM address
 * @description: Description for this IM address
 * @protocol: Protocol used for this IM address
 *
 * Returns a #CouchdbStructField representing the given IM address.
 *
 * Returns: (transfer full): A newly-created #CouchdbStructField representing
 * the given IM address information.
 */
CouchdbStructField *
couchdb_document_contact_im_new (const char *uuid,
				 const char *address,
				 const char *description,
				 const char *protocol)
{
	CouchdbStructField *sf;

	sf = couchdb_struct_field_new_from_json_object (json_object_new ());
	if (uuid != NULL)
		couchdb_struct_field_set_uuid (sf, uuid);
	else {
		char *new_uuid = generate_uuid ();
		couchdb_struct_field_set_uuid (sf, new_uuid);
		g_free (new_uuid);
	}

	if (address != NULL)
		couchdb_document_contact_im_set_address (sf, address);
	if (description != NULL)
		couchdb_document_contact_im_set_description (sf, description);
	if (protocol != NULL)
		couchdb_document_contact_im_set_protocol (sf, protocol);

	return sf;
}
Esempio n. 2
0
zmq::zmq_init_t::zmq_init_t (io_thread_t *io_thread_,
      socket_base_t *socket_, session_t *session_, fd_t fd_,
      const options_t &options_) :
    own_t (io_thread_, options_),
    ephemeral_engine (NULL),
    received (false),
    socket (socket_),
    session (session_),
    io_thread (io_thread_)
{
    //  Create the engine object for this connection.
    engine = new (std::nothrow) zmq_engine_t (fd_, options);
    alloc_assert (engine);

    //  Generate an unique identity.
    peer_identity.resize (17);
    peer_identity [0] = 0;
    generate_uuid (&peer_identity [1]);

    //  Create a list of messages to send on connection initialisation.
    if (!options.identity.empty ()) {
        msg_t msg;
        int rc = msg.init_size (options.identity.size ());
        errno_assert (rc == 0);
        memcpy (msg.data () , options.identity.data (), msg.size ());
        to_send.push_back (msg);
    }
    else {
        msg_t msg;
        int rc = msg.init ();
        errno_assert (rc == 0);
        to_send.push_back (msg);
    }
}
Esempio n. 3
0
static int
glusterfs_ctx_defaults_init (glusterfs_ctx_t *ctx)
{
        cmd_args_t    *cmd_args = NULL;
        struct rlimit  lim = {0, };
        call_pool_t   *pool = NULL;

        xlator_mem_acct_init (THIS, cli_mt_end);

        ctx->process_uuid = generate_uuid ();
        if (!ctx->process_uuid)
                return -1;

        ctx->page_size  = 128 * GF_UNIT_KB;

        ctx->iobuf_pool = iobuf_pool_new (8 * GF_UNIT_MB, ctx->page_size);
        if (!ctx->iobuf_pool)
                return -1;

        ctx->event_pool = event_pool_new (DEFAULT_EVENT_POOL_SIZE);
        if (!ctx->event_pool)
                return -1;

        pool = GF_CALLOC (1, sizeof (call_pool_t),
                          cli_mt_call_pool_t);
        if (!pool)
                return -1;

        /* frame_mem_pool size 112 * 16k */
        pool->frame_mem_pool = mem_pool_new (call_frame_t, 16384);

        if (!pool->frame_mem_pool)
                return -1;

        /* stack_mem_pool size 256 * 8k */
        pool->stack_mem_pool = mem_pool_new (call_stack_t, 8192); 

        if (!pool->stack_mem_pool)
                return -1;

        ctx->stub_mem_pool = mem_pool_new (call_stub_t, 1024);
        if (!ctx->stub_mem_pool)
                return -1;

        INIT_LIST_HEAD (&pool->all_frames);
        LOCK_INIT (&pool->lock);
        ctx->pool = pool;

        pthread_mutex_init (&(ctx->lock), NULL);

        cmd_args = &ctx->cmd_args;

        INIT_LIST_HEAD (&cmd_args->xlator_options);

        lim.rlim_cur = RLIM_INFINITY;
        lim.rlim_max = RLIM_INFINITY;
        setrlimit (RLIMIT_CORE, &lim);

        return 0;
}
Esempio n. 4
0
/**
 * Assign a new message id for a client.  Make sure it isn't already being used and does
 * not exceed the maximum.
 * @param client a client structure
 * @return the next message id to use, or 0 if none available
 */
uint64_t MQTTProtocol_assignMsgId(Clients* client)
{
	uint64_t msgid;
	FUNC_ENTRY;
	msgid = generate_uuid();
	client->msgID = msgid;
	FUNC_EXIT_RC(msgid);
	return msgid;
#if 0
	int start_msgid = client->msgID;
	uint64_t msgid = start_msgid;

	FUNC_ENTRY;
	msgid = (msgid == MAX_MSG_ID) ? 1 : msgid + 1;
	while (ListFindItem(client->outboundMsgs, &msgid, messageIDCompare) != NULL)
	{
		msgid = (msgid == MAX_MSG_ID) ? 1 : msgid + 1;
		if (msgid == start_msgid) 
		{ /* we've tried them all - none free */
			msgid = 0;
			break;
		}
	}
	if (msgid != 0)
		client->msgID = msgid;
	FUNC_EXIT_RC(msgid);
	return msgid;
#endif
}
Esempio n. 5
0
void zmq::socket_base_t::attach_pipe (pipe_t *pipe_,
    const blob_t &peer_identity_)
{
    //  First, register the pipe so that we can terminate it later on.
    pipe_->set_event_sink (this);
    pipes.push_back (pipe_);

    //  Then, pass the pipe to the specific socket type.
    //  If the peer haven't specified it's identity, let's generate one.
    if (peer_identity_.size ()) {
        xattach_pipe (pipe_, peer_identity_);
    }
    else {
        blob_t identity (17, 0);
        generate_uuid ((unsigned char*) identity.data () + 1);
        xattach_pipe (pipe_, identity);
    }

    //  If the socket is already being closed, ask any new pipes to terminate
    //  straight away.
    if (is_terminating ()) {
        register_term_acks (1);
        pipe_->terminate (false);
    }
}
Esempio n. 6
0
int
outbound_addressing_filter(SoapOpH opHandle, void *data, void *opaqueData)
{
	WsXmlDocH in_doc = soap_get_op_doc(opHandle, 1);
	WsXmlDocH out_doc = soap_get_op_doc(opHandle, 0);

	WsXmlNodeH outHeaders = wsman_get_soap_header_element(out_doc, NULL, NULL);

	if (!outHeaders) {
		return 0;
	}
	if (ws_xml_get_child(outHeaders, 0, XML_NS_ADDRESSING,  WSA_MESSAGE_ID) == NULL &&
	    !wsman_is_identify_request(in_doc)) {
		char uuidBuf[100];
		generate_uuid(uuidBuf, sizeof(uuidBuf), 0);
		ws_xml_add_child(outHeaders, XML_NS_ADDRESSING,	 WSA_MESSAGE_ID, uuidBuf);
		debug("Adding message id: %s", uuidBuf);
	}
	if (in_doc != NULL) {
		WsXmlNodeH inMsgIdNode;
		inMsgIdNode = wsman_get_soap_header_element(in_doc,XML_NS_ADDRESSING,
							    WSA_MESSAGE_ID);
		if (inMsgIdNode != NULL &&
		    !ws_xml_get_child(outHeaders, 0, XML_NS_ADDRESSING, WSA_RELATES_TO)) {
			ws_xml_add_child(outHeaders, XML_NS_ADDRESSING, WSA_RELATES_TO,
					 ws_xml_get_node_text(inMsgIdNode));
		}
	}

	return 0;
}
Esempio n. 7
0
/*
 * Pre-save hook for saving a message in a blog room.
 * (Do we want to only do this for top-level messages?)
 */
int blog_upload_beforesave(struct CtdlMessage *msg, recptypes *recp) {

	/* Only run this hook for blog rooms */
	if (CC->room.QRdefaultview != VIEW_BLOG) {
		return(0);
	}

	/* 
	 * If the message doesn't have an EUID, give it one.
	 */
	if (CM_IsEmpty(msg, eExclusiveID))
	{
		char uuid[SIZ];
		generate_uuid(uuid);
		CM_SetField(msg, eExclusiveID, uuid, strlen(uuid));
	}

	/*
	 * We also want to define a maximum length, whether we generated it or not.
	 */
	CM_CutFieldAt(msg, eExclusiveID, BLOG_EUIDBUF_SIZE - 1);
	
	/* Now allow the save to complete. */
	return(0);
}
static gboolean
glib_main (gpointer data)
{
	xmlDoc *doc = NULL;
	xmlNode *root_element = NULL;
	struct connection conn;
	static struct start_network_data start_network_data;


	if (!(start_network_data.client = nm_client_new()))
	{
		network_status (NULL, "Unable to connect to NetworkManager");
		g_main_loop_quit (loop);
	        return FALSE;
	}

	g_timeout_add_seconds (2, do_timeout, &start_network_data);
	start_network_data.should_quit = TRUE;

	/*parse the file and get the DOM */
	if( NULL == (doc = xmlReadFile(NETWORK_CONFIG, NULL, 0))) {
		network_status (start_network_data.client, "error: Could not parse " NETWORK_CONFIG "\n");
		g_main_loop_quit (loop);
		return FALSE;
	}

	/*Get the root element node */
	root_element = xmlDocGetRootElement(doc);
	if (root_element->type == XML_ELEMENT_NODE && !strcmp((char *)root_element->name, "configuration")) {
		gchar *err = read_connection(&conn, root_element);
		if (err) {
			gchar err2[1024];
			g_snprintf(err2, sizeof(err2), "Unable to parse configuration data: %s", err);
			network_status (start_network_data.client, err2);
			g_main_loop_quit (loop);
			return FALSE;
		}
	}
	else {
		network_status (start_network_data.client, "error: Invalid " NETWORK_CONFIG " file: No <configuration/> root node\n");
		g_main_loop_quit (loop);
		return FALSE;
	}

	xmlFreeDoc(doc);
	xmlCleanupParser();

	/* Generate the UUID from the connection information */
	generate_uuid(&conn, start_network_data.uuid, sizeof(start_network_data.uuid));


	/* Hand control over to do_connection.  Execution will continue in callbacks. */
	do_connection(&start_network_data);


	return FALSE;
}
Esempio n. 9
0
 /* 
  * Constructs a new bot with the specified username.
  */
 player_bot::player_bot (server& srv, const std::string& username)
   : username (username),
     living_entity (srv)
 {
   this->uuid = generate_uuid ();
   this->bbox = bounding_box {
     vector3 (-(this->get_width () / 2.0), -(this->get_height () / 2.0), -(this->get_depth () / 2.0)),
     vector3 (this->get_width () / 2.0, this->get_height () / 2.0, this->get_depth () / 2.0) };
   
   this->ticks = 0;
 }
Esempio n. 10
0
/**
 * Generates a pair record plist with required certificates for a specific
 * device. If a pairing exists, it is loaded from the computer instead of being
 * generated.
 *
 * @param pair_record_plist Holds the pair record.
 *
 * @return LOCKDOWN_E_SUCCESS on success
 */
static lockdownd_error_t pair_record_generate(lockdownd_client_t client, plist_t *pair_record)
{
	lockdownd_error_t ret = LOCKDOWN_E_UNKNOWN_ERROR;

	key_data_t public_key = { NULL, 0 };
	char* host_id = NULL;
	char* system_buid = NULL;

	/* retrieve device public key */
	ret = lockdownd_get_device_public_key_as_key_data(client, &public_key);
	if (ret != LOCKDOWN_E_SUCCESS) {
		debug_info("device refused to send public key.");
		goto leave;
	}
	debug_info("device public key follows:\n%.*s", public_key.size, public_key.data);

	*pair_record = plist_new_dict();

	/* generate keys and certificates into pair record */
	userpref_error_t uret = USERPREF_E_SUCCESS;
	uret = pair_record_generate_keys_and_certs(*pair_record, public_key);
	switch(uret) {
		case USERPREF_E_INVALID_ARG:
			ret = LOCKDOWN_E_INVALID_ARG;
			break;
		case USERPREF_E_INVALID_CONF:
			ret = LOCKDOWN_E_INVALID_CONF;
			break;
		case USERPREF_E_SSL_ERROR:
			ret = LOCKDOWN_E_SSL_ERROR;
		default:
			break;
	}

	/* set SystemBUID */
	userpref_read_system_buid(&system_buid);
	if (system_buid) {
		plist_dict_set_item(*pair_record, USERPREF_SYSTEM_BUID_KEY, plist_new_string(system_buid));
	}

	/* set HostID */
	host_id = generate_uuid();
	pair_record_set_host_id(*pair_record, host_id);

leave:
	if (host_id)
		free(host_id);
	if (system_buid)
		free(system_buid);
	if (public_key.data)
		free(public_key.data);

	return ret;
}
Esempio n. 11
0
Object* Object::instantiate(Class *c) {
    if (c == NULL) {
        throw std::string("object.cpp: Cannot instantiate null class.");
    }
    
    Object* o = new Object();
    o->isa = c;
    o->id = generate_uuid(10);
    
    return o;
}
Esempio n. 12
0
//-----------------------------------------------------------------------------
bool worker_c::create_experiment( Reveal::Core::authorization_ptr auth, Reveal::Core::scenario_ptr scenario, Reveal::Core::experiment_ptr& experiment ) {
  Reveal::DB::database_c::error_e db_error;

  //experiment = Reveal::Core::experiment_ptr( new Reveal::Core::experiment_c() );
  experiment->experiment_id = generate_uuid();
  experiment->session_id = auth->get_session();
  //TODO: validate that experiment values within bounds of scenario

  db_error = _db->insert( experiment );
  if( db_error == Reveal::DB::database_c::ERROR_NONE )
    return true;

  return false;
}
static void
test_change_databases (void)
{
    char *dbname;
    gint i;
    GError *error = NULL;

    dbname = generate_uuid ();
    g_assert (dbname != NULL);

    /* Database name can not start with a digit
     * we will overwrite the first character with 'a' */
    dbname[0] = 'a';

    /* Create database */
    couchdb_session_create_database (couchdb, dbname, &error);
    if (error) {
        g_critical ("Error creating database '%s': %s", dbname, error->message);
        g_error_free (error);
    }

    couchdb_session_listen_for_changes (couchdb, dbname);

    /* Create some documents */
    for (i = 0; i < 10; i++) {
        CouchdbDocument *document;
        char *str;

        document = couchdb_document_new (couchdb);
        g_assert (document != NULL);

        couchdb_document_set_boolean_field (document, "boolean", TRUE);
        couchdb_document_set_int_field (document, "int", i);
        couchdb_document_set_double_field (document, "double", (gdouble) i);

        str = g_strdup_printf ("value%d", i);
        couchdb_document_set_string_field (document, "string", str);
        g_free (str);

        g_assert (couchdb_document_put (document, dbname, &error));
        g_assert (error == NULL);
    }

    /* Delete database */
    g_assert (couchdb_session_delete_database (couchdb, dbname, &error));
    g_assert (error == NULL);

    /* Free memory */
    g_free (dbname);
}
Esempio n. 14
0
/*
 * Create a new note
 */
void add_new_note(void) {
	struct vnote *v;

	v = vnote_new();
	if (v) {
		v->uid = malloc(128);
		generate_uuid(v->uid);
		v->color_red = pastel_palette[3][0];
		v->color_green = pastel_palette[3][1];
		v->color_blue = pastel_palette[3][2];
		v->body = strdup(_("Click on any note to edit it."));
		write_vnote_to_server(v);
		vnote_free(v);
	}
	
	readloop(readfwd, eUseDefault);
}
Esempio n. 15
0
/**
 * Initialize super sector.
 *
 * @super_sect super sector image to initialize.
 * @lbs logical block size.
 * @pbs physical block size.
 * @ddev_lb device size [logical block].
 * @ldev_lb log device size [logical block]
 * @name name of the walb device, or NULL.
 *
 * RETURN:
 *   true in success.
 */
bool init_super_sector_raw(
	struct walb_super_sector* super_sect,
	unsigned int lbs, unsigned int pbs,
	u64 ddev_lb, u64 ldev_lb,
	const char *name)
{
	u32 salt;
	char *rname;
	bool ret;

	ASSERT(super_sect);
	ASSERT(0 < lbs);
	ASSERT(0 < pbs);
	ASSERT(0 < ddev_lb);
	ASSERT(0 < ldev_lb);

	ASSERT(sizeof(struct walb_super_sector) <= (size_t)pbs);

	/* Prepare super sector */
	memset(super_sect, 0, sizeof(*super_sect));
	/* Set sector type. */
	super_sect->sector_type = SECTOR_TYPE_SUPER;
	/* Fill parameters. */
	super_sect->version = WALB_LOG_VERSION;
	super_sect->logical_bs = lbs;
	super_sect->physical_bs = pbs;
	super_sect->metadata_size = 0; /* currently fixed */
	ret = generate_uuid(super_sect->uuid);
	if (!ret) { return false; }
	memset_random((u8 *)&salt, sizeof(salt));
	LOGn("salt: %"PRIu32"\n", salt);
	super_sect->log_checksum_salt = salt;
	super_sect->ring_buffer_size =
		ldev_lb / (pbs / lbs)
		- get_ring_buffer_offset(pbs);
	super_sect->oldest_lsid = 0;
	super_sect->written_lsid = 0;
	super_sect->device_size = ddev_lb;
	rname = set_super_sector_name(super_sect, name);
	if (name && strlen(name) != strlen(rname)) {
		printf("name %s is pruned to %s.\n", name, rname);
	}

	ASSERT(is_valid_super_sector_raw(super_sect, pbs));
	return true;
}
Esempio n. 16
0
int main(int argc, char **argv)
{
    alexjlz_log(1, "client started:%s\n", uuid);
    generate_uuid();
    alexjlz_log(1, "uuid generated:%s\n", uuid);
    getOurIP();
    srand(time(NULL) ^ getpid());
    init_rand(time(NULL) ^ getpid());
    set_proc_title(argc, argv, PROC_TITLE);
    alexjlz_log(1, "set proc title success\n");

    while (1)
    {
        if ( daemonize() == 0 )
            break;
        alexjlz_log(3, "daemonize failed\n");
        sleep(3);
    }
    alexjlz_log(3, "daemonize success\n");
    while ( 1 )
    {
        if( (mainCommSock=connect_tcp_server(server, port)) == -1)
        {
            alexjlz_log(3, "connect to server failed\n");
            sleep(5);
            continue;
        }
        alexjlz_log(3, "connect to server success\n");
        if ( ask_for_service( mainCommSock ) == -1 )  // return from this function means connection between client
            // and server are unexpectedly closed
        {
            //fprintf(stdout, "error in client\n");
        }

        if ( check_fd(mainCommSock) )
        {
            close(mainCommSock);
        }
        sleep(3);
    }

    return 0;
}
Esempio n. 17
0
    /* This constructor registers with the given registrant. It may block for a short
    time. */
    registrant_t(
            mailbox_manager_t *mm,
            const registrar_business_card_t<business_card_t> &rmd,
            business_card_t initial_value) :
        mailbox_manager(mm),
        registrar_md(rmd),
        registration_id(generate_uuid())
    {
        /* This will make it so that we get deregistered in our destructor. */
        deregisterer.fun = std::bind(&registrant_t::send_deregister_message,
            mailbox_manager,
            registrar_md.delete_mailbox,
            registration_id);

        /* Send a message to register us */
        send(mailbox_manager, registrar_md.create_mailbox,
            registration_id,
            mailbox_manager->get_connectivity_cluster()->get_me(),
            initial_value);
    }
/**
 * couchdb_document_contact_address_new:
 * @uuid: A unique ID
 * @street: Street
 * @ext_street: Extra information for the street
 * @city: City
 * @state: State or region
 * @country: Country
 * @postalcode: Postal code
 * @pobox: Post Office box
 * @description: Description for thos address
 *
 * Returns a #CouchdbStructField representing the given address.
 *
 * Returns: (transfer full): A newly-created #CouchdbStructField representing
 * the given address information.
 */
CouchdbStructField *
couchdb_document_contact_address_new (const char *uuid,
				      const char *street,
				      const char *ext_street,
				      const char *city,
				      const char *state,
				      const char *country,
				      const char *postalcode,
				      const char *pobox,
				      const char *description)
{
	CouchdbStructField *sf;

	sf = couchdb_struct_field_new_from_json_object (json_object_new ());
	if (uuid != NULL)
		couchdb_struct_field_set_uuid (sf, uuid);
	else {
		char *new_uuid = generate_uuid ();
		couchdb_struct_field_set_uuid (sf, new_uuid);
		g_free (new_uuid);
	}

	if (street)
		couchdb_document_contact_address_set_street (sf, street);
	if (ext_street)
		couchdb_document_contact_address_set_ext_street (sf, ext_street);
	if (city)
		couchdb_document_contact_address_set_city (sf, city);
	if (state)
		couchdb_document_contact_address_set_state (sf, state);
	if (country)
		couchdb_document_contact_address_set_country (sf, country);
	if (postalcode)
		couchdb_document_contact_address_set_postalcode (sf, postalcode);
	if (pobox)
		couchdb_document_contact_address_set_pobox (sf, pobox);
	if (description)
		couchdb_document_contact_address_set_description (sf, description);

	return sf;
}
Esempio n. 19
0
int pubnub_publishStatus(char *p_data){
	enum pubnub_res res;
    char const *chan = "sensorStatus-resp";
    pubnub_t *pbp = pubnub_alloc();

    if (NULL == pbp) {
        printf("Failed to allocate Pubnub context!\n");
        return -1;
    }
    pubnub_init(pbp, g_pub_key,g_sub_key);
    pubnub_set_transaction_timeout(pbp, PUBNUB_DEFAULT_NON_SUBSCRIBE_TIMEOUT);
    /* Leave this commented out to use the default - which is
       blocking I/O on most platforms. Uncomment to use non-
       blocking I/O.
    */
	//    pubnub_set_non_blocking_io(pbp);
    generate_uuid(pbp);
    pubnub_set_auth(pbp, "danaske");
    res = pubnub_publish(pbp, chan, p_data);
    if (res != PNR_STARTED) {
        printf("pubnub_publish() returned unexpected: %d\n", res);
        pubnub_free(pbp);
        return -1;
    }
    res = pubnub_await(pbp);
    if (res == PNR_STARTED) {
        printf("pubnub_await() returned unexpected: PNR_STARTED(%d)\n", res);
        pubnub_free(pbp);
        return -1;
    }
    if (PNR_OK == res) {
        //printf("Published! Response from Pubnub: %s\n", pubnub_last_publish_result(pbp));
    }
    else if (PNR_PUBLISH_FAILED == res) {
        printf("Published failed on Pubnub, description: %s\n", pubnub_last_publish_result(pbp));
    }
    else {
        printf("Publishing failed with code: %d\n", res);
    }
    return 0;
}
CouchdbStructField *
desktopcouch_document_contact_email_new (const char *uuid, const char *address, const char *description)
{
	CouchdbStructField *sf;

	sf = couchdb_struct_field_new_from_json_object (json_object_new ());
	if (uuid != NULL)
		couchdb_struct_field_set_uuid (sf, uuid);
	else {
		char *new_uuid = generate_uuid ();
		couchdb_struct_field_set_uuid (sf, new_uuid);
		g_free (new_uuid);
	}

	if (address)
		desktopcouch_document_contact_email_set_address (sf, address);
	if (description)
		desktopcouch_document_contact_email_set_description (sf, description);

	return sf;
}
Esempio n. 21
0
//-----------------------------------------------------------------------------
bool worker_c::create_session( Reveal::Core::authorization_ptr auth, Reveal::Core::session_ptr& session ) {
  Reveal::DB::database_c::error_e db_error;

  session = Reveal::Core::session_ptr( new Reveal::Core::session_c() );
  session->session_id = generate_uuid();

  Reveal::Core::authorization_c::type_e type = auth->get_type();
  if( type == Reveal::Core::authorization_c::TYPE_IDENTIFIED ) {
    session->user_type = Reveal::Core::session_c::IDENTIFIED;
    session->user_id = auth->get_user();
  } else if( type == Reveal::Core::authorization_c::TYPE_ANONYMOUS ) {
    session->user_type = Reveal::Core::session_c::ANONYMOUS;
    session->user_id = "";
  }

  db_error = _db->insert( session );
  if( db_error == Reveal::DB::database_c::ERROR_NONE )
    return true;

  return false;
}
/**
 * couchdb_document_contact_phone_new:
 * @uuid: A unique ID
 * @number: A phone number
 * @description: Description for this phone number
 * @priority: Priority of this phone number
 *
 * Returns a #CouchdbStructField representing the given phone number.
 *
 * Returns: (transfer full): A newly-created #CouchdbStructField representing
 * the given phone number information.
 */
CouchdbStructField *
couchdb_document_contact_phone_new (const char *uuid, const char *number, const char *description, gint priority)
{
	CouchdbStructField *sf;

	sf = couchdb_struct_field_new_from_json_object (json_object_new ());
	if (uuid != NULL)
		couchdb_struct_field_set_uuid (sf, uuid);
	else {
		char *new_uuid = generate_uuid ();
		couchdb_struct_field_set_uuid (sf, new_uuid);
		g_free (new_uuid);
	}

	if (number)
		couchdb_document_contact_phone_set_number (sf, number);
	if (description)
		couchdb_document_contact_phone_set_description (sf, description);
	couchdb_document_contact_phone_set_priority (sf, priority);

	return sf;
}
Esempio n. 23
0
int main()
{
    char const *msg;
    enum pubnub_res res;
    char const *chan = "hello_world";
    pubnub_t *pbp = pubnub_alloc();

    if (NULL == pbp) {
        printf("Failed to allocate Pubnub context!\n");
        return -1;
    }
    pubnub_init(pbp, "demo", "demo");

    pubnub_set_transaction_timeout(pbp, PUBNUB_DEFAULT_NON_SUBSCRIBE_TIMEOUT);
    
    /* Leave this commented out to use the default - which is
       blocking I/O on most platforms. Uncomment to use non-
       blocking I/O.
    */
//    pubnub_set_non_blocking_io(pbp);

    generate_uuid(pbp);

    pubnub_set_auth(pbp, "danaske");

    puts("Publishing...");
    res = pubnub_publish(pbp, chan, "\"Hello world from sync!\"");
    if (res != PNR_STARTED) {
        printf("pubnub_publish() returned unexpected: %d\n", res);
        pubnub_free(pbp);
        return -1;
    }
    res = pubnub_await(pbp);
    if (res == PNR_STARTED) {
        printf("pubnub_await() returned unexpected: PNR_STARTED(%d)\n", res);
        pubnub_free(pbp);
        return -1;
    }
    if (PNR_OK == res) {
        printf("Published! Response from Pubnub: %s\n", pubnub_last_publish_result(pbp));
    }
    else if (PNR_PUBLISH_FAILED == res) {
        printf("Published failed on Pubnub, description: %s\n", pubnub_last_publish_result(pbp));
    }
    else {
        printf("Publishing failed with code: %d\n", res);
    }

    puts("Subscribing...");
    res = pubnub_subscribe(pbp, chan, NULL);
    if (res != PNR_STARTED) {
        printf("pubnub_subscribe() returned unexpected: %d\n", res);
        pubnub_free(pbp);
        return -1;
    }
    res = pubnub_await(pbp);
    if (res == PNR_STARTED) {
        printf("pubnub_await() returned unexpected: PNR_STARTED(%d)\n", res);
        pubnub_free(pbp);
        return -1;
    }

    if (PNR_OK == res) {
        puts("Subscribed!");
    }
    else {
        printf("Subscribing failed with code: %d\n", res);
    }

    res = pubnub_subscribe(pbp, chan, NULL);
    if (res != PNR_STARTED) {
        printf("pubnub_subscribe() returned unexpected: %d\n", res);
        pubnub_free(pbp);
        return -1;
    }
    res = pubnub_await(pbp);
    if (res == PNR_STARTED) {
        printf("pubnub_await() returned unexpected: PNR_STARTED(%d)\n", res);
        pubnub_free(pbp);
        return -1;
    }

    if (PNR_OK == res) {
        puts("Subscribed! Got messages:");
        for (;;) {
            msg = pubnub_get(pbp);
            if (NULL == msg) {
                break;
            }
            puts(msg);
        }
    }
    else {
        printf("Subscribing failed with code: %d\n", res);
    }

    puts("Getting time...");
    res = pubnub_time(pbp);
    if (res != PNR_STARTED) {
        printf("pubnub_time() returned unexpected: %d\n", res);
        pubnub_free(pbp);
        return -1;
    }
    res = pubnub_await(pbp);
    if (res == PNR_STARTED) {
        printf("pubnub_await() returned unexpected: PNR_STARTED(%d)\n", res);
        pubnub_free(pbp);
        return -1;
    }

    if (PNR_OK == res) {
        printf("Gotten time: %s; last time token=%s\n", pubnub_get(pbp), pubnub_last_time_token(pbp));
    }
    else {
        printf("Getting time failed with code: %d\n", res);
    }

    puts("Getting history with include_token...");
    res = pubnub_history(pbp, chan, 10, true);
    if (res != PNR_STARTED) {
        printf("pubnub_history() returned unexpected: %d\n", res);
        pubnub_free(pbp);
        return -1;
    }
    res = pubnub_await(pbp);
    if (res == PNR_STARTED) {
        printf("pubnub_await() returned unexpected: PNR_STARTED(%d)\n", res);
        pubnub_free(pbp);
        return -1;
    }

    if (PNR_OK == res) {
        puts("Got history! Elements:");
        for (;;) {
            msg = pubnub_get(pbp);
            if (NULL == msg) {
                break;
            }
            puts(msg);
        }
    }
    else {
        printf("Getting history v2 with include_token failed with code: %d\n", res);
    }

    puts("Getting here_now presence...");
    res = pubnub_here_now(pbp, chan, NULL);
    if (res != PNR_STARTED) {
        printf("pubnub_here_now() returned unexpected: %d\n", res);
        pubnub_free(pbp);
        return -1;
    }
    res = pubnub_await(pbp);
    if (res == PNR_STARTED) {
        printf("pubnub_await() returned unexpected: PNR_STARTED(%d)\n", res);
        pubnub_free(pbp);
        return -1;
    }

    if (PNR_OK == res) {
        puts("Got here now presence!");
        for (;;) {
            msg = pubnub_get(pbp);
            if (NULL == msg) {
                break;
            }
            puts(msg);
        }
    }
    else {
        printf("Getting here-now presence failed with code: %d\n", res);
    }

    /** Global here_now presence for "demo" subscribe key is _very_
        long, but we have it here to show that we can handle very long
        response if the PUBNUB_DYNAMIC_REPLY_BUFFER is "on".
    */
    if (PUBNUB_DYNAMIC_REPLY_BUFFER) {
        puts("Getting global here_now presence...");
        res = pubnub_global_here_now(pbp);
        if (res != PNR_STARTED) {
            printf("pubnub_global_here_now() returned unexpected: %d\n", res);
            pubnub_free(pbp);
            return -1;
        }
        res = pubnub_await(pbp);
        if (res == PNR_STARTED) {
            printf("pubnub_await() returned unexpected: PNR_STARTED(%d)\n", res);
            pubnub_free(pbp);
            return -1;
        }
        
        if (PNR_OK == res) {
            puts("Got global here now presence!");
            for (;;) {
                msg = pubnub_get(pbp);
                if (NULL == msg) {
                    break;
                }
                puts(msg);
            }
        }
        else {
            printf("Getting global here-now presence failed with code: %d\n", res);
        }
    }

    puts("Getting where_now presence...");
    res = pubnub_where_now(pbp, pubnub_uuid_get(pbp));
    if (res != PNR_STARTED) {
        printf("pubnub_where_now() returned unexpected: %d\n", res);
        pubnub_free(pbp);
        return -1;
    }
    res = pubnub_await(pbp);
    if (res == PNR_STARTED) {
        printf("pubnub_await() returned unexpected: PNR_STARTED(%d)\n", res);
        pubnub_free(pbp);
        return -1;
    }

    if (PNR_OK == res) {
        puts("Got where now presence!");
        for (;;) {
            msg = pubnub_get(pbp);
            if (NULL == msg) {
                break;
            }
            puts(msg);
        }
    }
    else {
        printf("Getting where-now presence failed with code: %d\n", res);
    }

    puts("Setting state...");
    res = pubnub_set_state(pbp, chan, NULL, pubnub_uuid_get(pbp), "{\"x\":5}");
    if (res != PNR_STARTED) {
        printf("pubnub_set_state() returned unexpected: %d\n", res);
        pubnub_free(pbp);
        return -1;
    }
    res = pubnub_await(pbp);
    if (res == PNR_STARTED) {
        printf("pubnub_await() returned unexpected: PNR_STARTED(%d)\n", res);
        pubnub_free(pbp);
        return -1;
    }

    if (PNR_OK == res) {
        puts("Got set state response!");
        for (;;) {
            msg = pubnub_get(pbp);
            if (NULL == msg) {
                break;
            }
            puts(msg);
        }
    }
    else {
        printf("Setting state failed with code: %d\n", res);
    }

    puts("Getting state...");
    res = pubnub_state_get(pbp, chan, NULL, pubnub_uuid_get(pbp));
    if (res != PNR_STARTED) {
        printf("pubnub_state_get() returned unexpected: %d\n", res);
        pubnub_free(pbp);
        return -1;
    }
    res = pubnub_await(pbp);
    if (res == PNR_STARTED) {
        printf("pubnub_await() returned unexpected: PNR_STARTED(%d)\n", res);
        pubnub_free(pbp);
        return -1;
    }

    if (PNR_OK == res) {
        puts("Got state!");
        for (;;) {
            msg = pubnub_get(pbp);
            if (NULL == msg) {
                break;
            }
            puts(msg);
        }
    }
    else {
        printf("Getting state failed with code: %d\n", res);
    }

    puts("List channel group...");
    res = pubnub_list_channel_group(pbp, "channel-group");
    if (res != PNR_STARTED) {
        printf("pubnub_state_get() returned unexpected: %d\n", res);
        pubnub_free(pbp);
        return -1;
    }
    res = pubnub_await(pbp);
    if (res == PNR_STARTED) {
        printf("pubnub_await() returned unexpected: PNR_STARTED(%d)\n", res);
        pubnub_free(pbp);
        return -1;
    }

    if (PNR_OK == res) {
        puts("Got channel group list!");
        for (;;) {
            msg = pubnub_get_channel(pbp);
            if (NULL == msg) {
                break;
            }
            puts(msg);
        }
    }
    else {
        printf("Getting channel group list failed with code: %d ('%s')\n", res, pubnub_res_2_string(res));
    }
	
    /* We're done */
    if (pubnub_free(pbp) != 0) {
        printf("Failed to free the Pubnub context\n");
    }

    puts("Pubnub sync demo over.");

    return 0;
}
Esempio n. 24
0
static int
glusterfs_ctx_defaults_init (glusterfs_ctx_t *ctx)
{
    cmd_args_t    *cmd_args = NULL;
    struct rlimit  lim = {0, };
    call_pool_t   *pool = NULL;

    xlator_mem_acct_init (THIS, gfd_mt_end);

    ctx->process_uuid = generate_uuid ();
    if (!ctx->process_uuid)
        return -1;

    ctx->page_size  = 128 * GF_UNIT_KB;

    ctx->iobuf_pool = iobuf_pool_new (8 * GF_UNIT_MB, ctx->page_size);
    if (!ctx->iobuf_pool)
        return -1;

    ctx->event_pool = event_pool_new (DEFAULT_EVENT_POOL_SIZE);
    if (!ctx->event_pool)
        return -1;

    pool = GF_CALLOC (1, sizeof (call_pool_t),
                      gfd_mt_call_pool_t);
    if (!pool)
        return -1;

    /* frame_mem_pool size 112 * 16k */
    pool->frame_mem_pool = mem_pool_new (call_frame_t, 16384);

    if (!pool->frame_mem_pool)
        return -1;

    /* stack_mem_pool size 256 * 8k */
    pool->stack_mem_pool = mem_pool_new (call_stack_t, 8192);

    if (!pool->stack_mem_pool)
        return -1;

    ctx->stub_mem_pool = mem_pool_new (call_stub_t, 1024);
    if (!ctx->stub_mem_pool)
        return -1;

    INIT_LIST_HEAD (&pool->all_frames);
    LOCK_INIT (&pool->lock);
    ctx->pool = pool;

    pthread_mutex_init (&(ctx->lock), NULL);

    cmd_args = &ctx->cmd_args;

    /* parsing command line arguments */
    cmd_args->log_level = DEFAULT_LOG_LEVEL;
#ifdef GF_DARWIN_HOST_OS
    cmd_args->mac_compat = GF_OPTION_DEFERRED;
    /* On Darwin machines, O_APPEND is not handled,
     * which may corrupt the data
     */
    cmd_args->fuse_direct_io_mode = GF_OPTION_DISABLE;
#else
    cmd_args->mac_compat = GF_OPTION_DISABLE;
    cmd_args->fuse_direct_io_mode = GF_OPTION_DEFERRED;
#endif
    cmd_args->fuse_attribute_timeout = -1;
    cmd_args->fuse_entry_timeout = -1;

    INIT_LIST_HEAD (&cmd_args->xlator_options);

    lim.rlim_cur = RLIM_INFINITY;
    lim.rlim_max = RLIM_INFINITY;
    setrlimit (RLIMIT_CORE, &lim);

    return 0;
}
Esempio n. 25
0
char *process_uuid(struct Logs *logs,
                   const struct Rc *rc, const struct Options *opt,
                   struct Entry *entry)
{
	assert(logs);
	assert(logs->logfp);
	assert(rc);
	assert(opt);
	assert(entry);

	/*
	 * Generate the UUID or use an already generated UUID stored in 
	 * opt->uuid.
	 */

	if (opt->uuid) {
		if (!valid_uuid(opt->uuid, TRUE)) {
			fprintf(stderr, "process_uuid(): UUID \"%s\" is not "
			                "valid.\n", opt->uuid);
			return NULL;
		}
		entry->uuid = opt->uuid;
	} else
		entry->uuid = generate_uuid(rc, opt->random_mac);
	if (!entry->uuid) {
		fprintf(stderr, "%s: UUID generation failed\n", progname);
		return NULL;
	}

	/*
	 * Extract the time stamp from the UUID and store it in an allocated 
	 * buffer.
	 */

	if (!entry->date)
		entry->date = malloc(DATE_LENGTH + 1);
	if (!entry->date) {
		myerror("process_uuid(): Could not allocate %lu bytes for "
		        "date string", DATE_LENGTH + 1);
		return NULL;
	}
	if (!uuid_date_from_uuid(entry->date, entry->uuid))
		return NULL;

	if (add_to_logfile(logs->logfp, entry, opt->raw) == EXIT_FAILURE)
		return NULL;

	/*
	 * Write the UUID to stdout and/or stderr, or not, depending on the 
	 * -w/--whereto argument.
	 */

	if (!opt->whereto)
		puts(entry->uuid);
	else {
		if (strchr(opt->whereto, 'a') || strchr(opt->whereto, 'o'))
			fprintf(stdout, "%s\n", entry->uuid);
		if (strchr(opt->whereto, 'a') || strchr(opt->whereto, 'e'))
			fprintf(stderr, "%s\n", entry->uuid);
	}

	return entry->uuid;
}
Esempio n. 26
0
 static order_bucket_t create() { return order_bucket_t(generate_uuid()); }
Esempio n. 27
0
/* Fill in the superblock memory buffer based on the filesystem parameters */
void ext4_fill_in_sb()
{
	unsigned int i;
	struct ext4_super_block *sb = aux_info.sb;

	sb->s_inodes_count = info.inodes_per_group * aux_info.groups;
	sb->s_blocks_count_lo = aux_info.len_blocks;
	sb->s_r_blocks_count_lo = 0;
	sb->s_free_blocks_count_lo = 0;
	sb->s_free_inodes_count = 0;
	sb->s_first_data_block = aux_info.first_data_block;
	sb->s_log_block_size = log_2(info.block_size / 1024);
	sb->s_obso_log_frag_size = log_2(info.block_size / 1024);
	sb->s_blocks_per_group = info.blocks_per_group;
	sb->s_obso_frags_per_group = info.blocks_per_group;
	sb->s_inodes_per_group = info.inodes_per_group;
	sb->s_mtime = 0;
	sb->s_wtime = 0;
	sb->s_mnt_count = 0;
	sb->s_max_mnt_count = 0xFFFF;
	sb->s_magic = EXT4_SUPER_MAGIC;
	sb->s_state = EXT4_VALID_FS;
	sb->s_errors = EXT4_ERRORS_RO;
	sb->s_minor_rev_level = 0;
	sb->s_lastcheck = 0;
	sb->s_checkinterval = 0;
	sb->s_creator_os = EXT4_OS_LINUX;
	sb->s_rev_level = EXT4_DYNAMIC_REV;
	sb->s_def_resuid = EXT4_DEF_RESUID;
	sb->s_def_resgid = EXT4_DEF_RESGID;

	sb->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
	sb->s_inode_size = info.inode_size;
	sb->s_block_group_nr = 0;
	sb->s_feature_compat = info.feat_compat;
	sb->s_feature_incompat = info.feat_incompat;
	sb->s_feature_ro_compat = info.feat_ro_compat;
	generate_uuid("extandroid/make_ext4fs", info.label, sb->s_uuid);
	memset(sb->s_volume_name, 0, sizeof(sb->s_volume_name));
	strncpy(sb->s_volume_name, info.label, sizeof(sb->s_volume_name));
	memset(sb->s_last_mounted, 0, sizeof(sb->s_last_mounted));
	sb->s_algorithm_usage_bitmap = 0;

	sb->s_reserved_gdt_blocks = info.bg_desc_reserve_blocks;
	sb->s_prealloc_blocks = 0;
	sb->s_prealloc_dir_blocks = 0;

	//memcpy(sb->s_journal_uuid, sb->s_uuid, sizeof(sb->s_journal_uuid));
	if (info.feat_compat & EXT4_FEATURE_COMPAT_HAS_JOURNAL)
		sb->s_journal_inum = EXT4_JOURNAL_INO;
	sb->s_journal_dev = 0;
	sb->s_last_orphan = 0;
	sb->s_hash_seed[0] = 0; /* FIXME */
	sb->s_def_hash_version = DX_HASH_TEA;
	sb->s_reserved_char_pad = EXT4_JNL_BACKUP_BLOCKS;
	sb->s_desc_size = sizeof(struct ext2_group_desc);
	sb->s_default_mount_opts = 0; /* FIXME */
	sb->s_first_meta_bg = 0;
	sb->s_mkfs_time = 0;
	//sb->s_jnl_blocks[17]; /* FIXME */

	sb->s_blocks_count_hi = aux_info.len_blocks >> 32;
	sb->s_r_blocks_count_hi = 0;
	sb->s_free_blocks_count_hi = 0;
	sb->s_min_extra_isize = sizeof(struct ext4_inode) -
		EXT4_GOOD_OLD_INODE_SIZE;
	sb->s_want_extra_isize = sizeof(struct ext4_inode) -
		EXT4_GOOD_OLD_INODE_SIZE;
	sb->s_flags = 0;
	sb->s_raid_stride = 0;
	sb->s_mmp_interval = 0;
	sb->s_mmp_block = 0;
	sb->s_raid_stripe_width = 0;
	sb->s_log_groups_per_flex = 0;
	sb->s_kbytes_written = 0;

	for (i = 0; i < aux_info.groups; i++) {
		u64 group_start_block = aux_info.first_data_block + i *
			info.blocks_per_group;
		u32 header_size = 0;
		if (ext4_bg_has_super_block(i)) {
			if (i != 0) {
				aux_info.backup_sb[i] = calloc(info.block_size, 1);
				memcpy(aux_info.backup_sb[i], sb, info.block_size);
				/* Update the block group nr of this backup superblock */
				aux_info.backup_sb[i]->s_block_group_nr = i;
				queue_data_block((u8 *)aux_info.backup_sb[i],
                                                  info.block_size, group_start_block);
			}
			queue_data_block((u8 *)aux_info.bg_desc,
				aux_info.bg_desc_blocks * info.block_size,
				group_start_block + 1);
			header_size = 1 + aux_info.bg_desc_blocks + info.bg_desc_reserve_blocks;
		}

		aux_info.bg_desc[i].bg_block_bitmap = group_start_block + header_size;
		aux_info.bg_desc[i].bg_inode_bitmap = group_start_block + header_size + 1;
		aux_info.bg_desc[i].bg_inode_table = group_start_block + header_size + 2;

		aux_info.bg_desc[i].bg_free_blocks_count = sb->s_blocks_per_group;
		aux_info.bg_desc[i].bg_free_inodes_count = sb->s_inodes_per_group;
		aux_info.bg_desc[i].bg_used_dirs_count = 0;
	}
}
Esempio n. 28
0
LIBIMOBILEDEVICE_API lockdownd_error_t lockdownd_client_new(idevice_t device, lockdownd_client_t *client, const char *label)
{
	if (!client)
		return LOCKDOWN_E_INVALID_ARG;

	static struct lockdownd_service_descriptor service = {
		.port = 0xf27e,
		.ssl_enabled = 0
	};

	property_list_service_client_t plistclient = NULL;
	if (property_list_service_client_new(device, (lockdownd_service_descriptor_t)&service, &plistclient) != PROPERTY_LIST_SERVICE_E_SUCCESS) {
		debug_info("could not connect to lockdownd (device %s)", device->udid);
		return LOCKDOWN_E_MUX_ERROR;
	}

	lockdownd_client_t client_loc = (lockdownd_client_t) malloc(sizeof(struct lockdownd_client_private));
	client_loc->parent = plistclient;
	client_loc->ssl_enabled = 0;
	client_loc->session_id = NULL;

	if (idevice_get_udid(device, &client_loc->udid) != IDEVICE_E_SUCCESS) {
		debug_info("failed to get device udid.");
	}
	debug_info("device udid: %s", client_loc->udid);

	client_loc->label = label ? strdup(label) : NULL;

	*client = client_loc;

	return LOCKDOWN_E_SUCCESS;
}

LIBIMOBILEDEVICE_API lockdownd_error_t lockdownd_client_new_with_handshake(idevice_t device, lockdownd_client_t *client, const char *label)
{
	if (!client)
		return LOCKDOWN_E_INVALID_ARG;

	lockdownd_error_t ret = LOCKDOWN_E_SUCCESS;
	lockdownd_client_t client_loc = NULL;
	char *host_id = NULL;
	char *type = NULL;

	ret = lockdownd_client_new(device, &client_loc, label);
	if (LOCKDOWN_E_SUCCESS != ret) {
		debug_info("failed to create lockdownd client.");
		return ret;
	}

	/* perform handshake */
	if (LOCKDOWN_E_SUCCESS != lockdownd_query_type(client_loc, &type)) {
		debug_info("QueryType failed in the lockdownd client.");
		ret = LOCKDOWN_E_NOT_ENOUGH_DATA;
	} else {
		if (strcmp("com.apple.mobile.lockdown", type)) {
			debug_info("Warning QueryType request returned \"%s\".", type);
		}
	}
	if (type)
		free(type);

	plist_t pair_record = NULL;
	userpref_read_pair_record(client_loc->udid, &pair_record);
	if (pair_record) {
		pair_record_get_host_id(pair_record, &host_id);
	}
	if (LOCKDOWN_E_SUCCESS == ret && !host_id) {
		ret = LOCKDOWN_E_INVALID_CONF;
	}

	if (LOCKDOWN_E_SUCCESS == ret && !pair_record) {
		/* attempt pairing */
		ret = lockdownd_pair(client_loc, NULL);
	}

	plist_free(pair_record);
	pair_record = NULL;

	/* in any case, we need to validate pairing to receive trusted host status */
	ret = lockdownd_validate_pair(client_loc, NULL);

	/* if not paired yet, let's do it now */
	if (LOCKDOWN_E_INVALID_HOST_ID == ret) {
		ret = lockdownd_pair(client_loc, NULL);

		if (LOCKDOWN_E_SUCCESS == ret) {
			ret = lockdownd_validate_pair(client_loc, NULL);
		} else if (LOCKDOWN_E_PAIRING_DIALOG_PENDING == ret) {
			debug_info("Device shows the pairing dialog.");
		}
	}

	if (LOCKDOWN_E_SUCCESS == ret) {
		if (!host_id) {
			userpref_read_pair_record(client_loc->udid, &pair_record);
			if (pair_record) {
				pair_record_get_host_id(pair_record, &host_id);
				plist_free(pair_record);
			}
		}

		ret = lockdownd_start_session(client_loc, host_id, NULL, NULL);
		if (LOCKDOWN_E_SUCCESS != ret) {
			debug_info("Session opening failed.");
		}

		if (host_id) {
			free(host_id);
			host_id = NULL;
		}
	}
	
	if (LOCKDOWN_E_SUCCESS == ret) {
		*client = client_loc;
	} else {
		lockdownd_client_free(client_loc);
	}

	return ret;
}

/**
 * Returns a new plist from the supplied lockdownd pair record. The caller is
 * responsible for freeing the plist.
 *
 * @param pair_record The pair record to create a plist from.
 *
 * @return A pair record plist from the device, NULL if pair_record is not set
 */
static plist_t lockdownd_pair_record_to_plist(lockdownd_pair_record_t pair_record)
{
	if (!pair_record)
		return NULL;

	/* setup request plist */
	plist_t dict = plist_new_dict();
	plist_dict_set_item(dict, "DeviceCertificate", plist_new_data(pair_record->device_certificate, strlen(pair_record->device_certificate)));
	plist_dict_set_item(dict, "HostCertificate", plist_new_data(pair_record->host_certificate, strlen(pair_record->host_certificate)));
	plist_dict_set_item(dict, "HostID", plist_new_string(pair_record->host_id));
	plist_dict_set_item(dict, "RootCertificate", plist_new_data(pair_record->root_certificate, strlen(pair_record->root_certificate)));
	plist_dict_set_item(dict, "SystemBUID", plist_new_string(pair_record->system_buid));

	return dict;
}

/**
 * Generates a pair record plist with required certificates for a specific
 * device. If a pairing exists, it is loaded from the computer instead of being
 * generated.
 *
 * @param pair_record_plist Holds the pair record.
 *
 * @return LOCKDOWN_E_SUCCESS on success
 */
static lockdownd_error_t pair_record_generate(lockdownd_client_t client, plist_t *pair_record)
{
	lockdownd_error_t ret = LOCKDOWN_E_UNKNOWN_ERROR;

	key_data_t public_key = { NULL, 0 };
	char* host_id = NULL;
	char* system_buid = NULL;

	/* retrieve device public key */
	ret = lockdownd_get_device_public_key_as_key_data(client, &public_key);
	if (ret != LOCKDOWN_E_SUCCESS) {
		debug_info("device refused to send public key.");
		goto leave;
	}
	debug_info("device public key follows:\n%.*s", public_key.size, public_key.data);

	*pair_record = plist_new_dict();

	/* generate keys and certificates into pair record */
	userpref_error_t uret = USERPREF_E_SUCCESS;
	uret = pair_record_generate_keys_and_certs(*pair_record, public_key);
	switch(uret) {
		case USERPREF_E_INVALID_ARG:
			ret = LOCKDOWN_E_INVALID_ARG;
			break;
		case USERPREF_E_INVALID_CONF:
			ret = LOCKDOWN_E_INVALID_CONF;
			break;
		case USERPREF_E_SSL_ERROR:
			ret = LOCKDOWN_E_SSL_ERROR;
		default:
			break;
	}

	/* set SystemBUID */
	userpref_read_system_buid(&system_buid);
	if (system_buid) {
		plist_dict_set_item(*pair_record, USERPREF_SYSTEM_BUID_KEY, plist_new_string(system_buid));
	}

	/* set HostID */
	host_id = generate_uuid();
	pair_record_set_host_id(*pair_record, host_id);

leave:
	if (host_id)
		free(host_id);
	if (system_buid)
		free(system_buid);
	if (public_key.data)
		free(public_key.data);

	return ret;
}
Esempio n. 29
0
File: main.c Progetto: darcyg/u2pnpd
struct device_desc *device_desc_new(config_options_t *options)
{
	struct device_desc *d = calloc(1, sizeof(*d));
	char *s = NULL;

	if (!d)
		return NULL;

	if (options->uuid)
		quote_xml_special(&d->uuid, options->uuid);
	else
		generate_uuid(&d->uuid);

	if (options->serialNumber) {
		quote_xml_special(&d->serialNumber, options->serialNumber);
	} else {
		deviceinfo_from_cpuinfo(&s, "Serial");
		if (s) {
			quote_xml_special(&d->serialNumber, s);
			free(s);
			s = NULL;
		}
	}

	if (options->modelURL)
		quote_xml_special(&d->modelURL, options->modelURL);
	if (options->modelNumber)
		quote_xml_special(&d->modelNumber, options->modelNumber);
	if (options->modelDescription)
		quote_xml_special(&d->modelDescription, options->modelDescription);

	if (options->manufacturerURL) {
		quote_xml_special(&d->manufacturerURL, options->manufacturerURL);
	} else {
		deviceinfo_from_deviceinfo(&s, "DEVICE_MANUFACTURER_URL");
		if (s) {
			quote_xml_special(&d->manufacturerURL, s);
			free(s);
			s = NULL;
		}
	}

	if (options->manufacturer) {
		quote_xml_special(&d->manufacturer, options->manufacturer);
	} else {
		deviceinfo_from_deviceinfo(&s, "DEVICE_MANUFACTURER");
		if (s) {
			quote_xml_special(&d->manufacturer, s);
			free(s);
			s = NULL;
		}
	}

	if (options->modelName) {
		quote_xml_special(&d->modelName, options->modelName);
	} else {
		deviceinfo_from_deviceinfo(&s, "DEVICE_PRODUCT");
		if (s) {
			quote_xml_special(&d->modelName, s);
			free(s);
			s = NULL;
		}
	}

	if (options->friendlyName) {
		quote_xml_special(&d->friendlyName, options->friendlyName);
	} else {
		deviceinfo_from_deviceinfo(&s, "DEVICE_FRIENDLYNAME");
		if (s) {
			quote_xml_special(&d->friendlyName, s);
			free(s);
			s = NULL;
		} else {
			if (d->manufacturer && d->manufacturer[0] &&
			    d->modelName && d->modelName[0]) {

				asprintf(&s, "%s %s", d->manufacturer, d->modelName);
				if (s) {
					quote_xml_special(&d->friendlyName, s);
					free(s);
					s = NULL;
				}
			}
		}
	}

	if (options->presentationURL) {
		quote_xml_special(&d->presentationURL, options->presentationURL);
	} else {
		asprintf(&d->presentationURL, "http%s://%s/", options->use_https ? "s" : "",
		         UpnpGetServerIpAddress());
	}

	return d;
}
Esempio n. 30
0
/*
 * Before allowing a wiki page save to execute, we have to perform version control.
 * This involves fetching the old version of the page if it exists.
 */
int wiki_upload_beforesave(struct CtdlMessage *msg, recptypes *recp) {
	struct CitContext *CCC = CC;
	long old_msgnum = (-1L);
	struct CtdlMessage *old_msg = NULL;
	long history_msgnum = (-1L);
	struct CtdlMessage *history_msg = NULL;
	char diff_old_filename[PATH_MAX];
	char diff_new_filename[PATH_MAX];
	char diff_out_filename[PATH_MAX];
	char diff_cmd[PATH_MAX];
	FILE *fp;
	int rv;
	char history_page[1024];
	long history_page_len;
	char boundary[256];
	char prefixed_boundary[258];
	char buf[1024];
	char *diffbuf = NULL;
	size_t diffbuf_len = 0;
	char *ptr = NULL;
	long newmsgid;
	StrBuf *msgidbuf;

	if (!CCC->logged_in) return(0);	/* Only do this if logged in. */

	/* Is this a room with a Wiki in it, don't run this hook. */
	if ((CCC->room.QRdefaultview != VIEW_WIKI) &&
	    (CCC->room.QRdefaultview != VIEW_WIKIMD)) {
		return(0);
	}

	/* If this isn't a MIME message, don't bother. */
	if (msg->cm_format_type != 4) return(0);

	/* If there's no EUID we can't do this.  Reject the post. */
	if (CM_IsEmpty(msg, eExclusiveID)) return(1);

	newmsgid = get_new_message_number();
	msgidbuf = NewStrBuf();
	StrBufPrintf(msgidbuf, "%08lX-%08lX@%s/%s",
		     (long unsigned int) time(NULL),
		     (long unsigned int) newmsgid,
		     CtdlGetConfigStr("c_fqdn"),
		     msg->cm_fields[eExclusiveID]
		);

	CM_SetAsFieldSB(msg, emessageId, &msgidbuf);

	history_page_len = snprintf(history_page, sizeof history_page,
				    "%s_HISTORY_", msg->cm_fields[eExclusiveID]);

	/* Make sure we're saving a real wiki page rather than a wiki history page.
	 * This is important in order to avoid recursing infinitely into this hook.
	 */
	if (	(msg->cm_lengths[eExclusiveID] >= 9)
		&& (!strcasecmp(&msg->cm_fields[eExclusiveID][msg->cm_lengths[eExclusiveID]-9], "_HISTORY_"))
	) {
		syslog(LOG_DEBUG, "History page not being historied\n");
		return(0);
	}

	/* If there's no message text, obviously this is all b0rken and shouldn't happen at all */
	if (CM_IsEmpty(msg, eMesageText)) return(0);

	/* Set the message subject identical to the page name */
	CM_CopyField(msg, eMsgSubject, eExclusiveID);

	/* See if we can retrieve the previous version. */
	old_msgnum = CtdlLocateMessageByEuid(msg->cm_fields[eExclusiveID], &CCC->room);
	if (old_msgnum > 0L) {
		old_msg = CtdlFetchMessage(old_msgnum, 1, 1);
	}
	else {
		old_msg = NULL;
	}

	if ((old_msg != NULL) && (CM_IsEmpty(old_msg, eMesageText))) {	/* old version is corrupt? */
		CM_Free(old_msg);
		old_msg = NULL;
	}
	
	/* If no changes were made, don't bother saving it again */
	if ((old_msg != NULL) && (!strcmp(msg->cm_fields[eMesageText], old_msg->cm_fields[eMesageText]))) {
		CM_Free(old_msg);
		return(1);
	}

	/*
	 * Generate diffs
	 */
	CtdlMakeTempFileName(diff_old_filename, sizeof diff_old_filename);
	CtdlMakeTempFileName(diff_new_filename, sizeof diff_new_filename);
	CtdlMakeTempFileName(diff_out_filename, sizeof diff_out_filename);

	if (old_msg != NULL) {
		fp = fopen(diff_old_filename, "w");
		rv = fwrite(old_msg->cm_fields[eMesageText], old_msg->cm_lengths[eMesageText], 1, fp);
		fclose(fp);
		CM_Free(old_msg);
	}

	fp = fopen(diff_new_filename, "w");
	rv = fwrite(msg->cm_fields[eMesageText], msg->cm_lengths[eMesageText], 1, fp);
	fclose(fp);

	snprintf(diff_cmd, sizeof diff_cmd,
		DIFF " -u %s %s >%s",
		diff_new_filename,
		((old_msg != NULL) ? diff_old_filename : "/dev/null"),
		diff_out_filename
	);
	syslog(LOG_DEBUG, "diff cmd: %s", diff_cmd);
	rv = system(diff_cmd);
	syslog(LOG_DEBUG, "diff cmd returned %d", rv);

	diffbuf_len = 0;
	diffbuf = NULL;
	fp = fopen(diff_out_filename, "r");
	if (fp == NULL) {
		fp = fopen("/dev/null", "r");
	}
	if (fp != NULL) {
		fseek(fp, 0L, SEEK_END);
		diffbuf_len = ftell(fp);
		fseek(fp, 0L, SEEK_SET);
		diffbuf = malloc(diffbuf_len + 1);
		fread(diffbuf, diffbuf_len, 1, fp);
		diffbuf[diffbuf_len] = '\0';
		fclose(fp);
	}

	syslog(LOG_DEBUG, "diff length is "SIZE_T_FMT" bytes", diffbuf_len);

	unlink(diff_old_filename);
	unlink(diff_new_filename);
	unlink(diff_out_filename);

	/* Determine whether this was a bogus (empty) edit */
	if ((diffbuf_len = 0) && (diffbuf != NULL)) {
		free(diffbuf);
		diffbuf = NULL;
	}
	if (diffbuf == NULL) {
		return(1);		/* No changes at all?  Abandon the post entirely! */
	}

	/* Now look for the existing edit history */

	history_msgnum = CtdlLocateMessageByEuid(history_page, &CCC->room);
	history_msg = NULL;
	if (history_msgnum > 0L) {
		history_msg = CtdlFetchMessage(history_msgnum, 1, 1);
	}

	/* Create a new history message if necessary */
	if (history_msg == NULL) {
		char *buf;
		long len;

		history_msg = malloc(sizeof(struct CtdlMessage));
		memset(history_msg, 0, sizeof(struct CtdlMessage));
		history_msg->cm_magic = CTDLMESSAGE_MAGIC;
		history_msg->cm_anon_type = MES_NORMAL;
		history_msg->cm_format_type = FMT_RFC822;
		CM_SetField(history_msg, eAuthor, HKEY("Citadel"));
		if (!IsEmptyStr(CCC->room.QRname)){
			CM_SetField(history_msg, eRecipient, CCC->room.QRname, strlen(CCC->room.QRname));
		}
		CM_SetField(history_msg, eExclusiveID, history_page, history_page_len);
		CM_SetField(history_msg, eMsgSubject, history_page, history_page_len);
		CM_SetField(history_msg, eSuppressIdx, HKEY("1")); /* suppress full text indexing */
		snprintf(boundary, sizeof boundary, "Citadel--Multipart--%04x--%08lx", getpid(), time(NULL));
		buf = (char*) malloc(1024);
		len = snprintf(buf, 1024,
			       "Content-type: multipart/mixed; boundary=\"%s\"\n\n"
			       "This is a Citadel wiki history encoded as multipart MIME.\n"
			       "Each part is comprised of a diff script representing one change set.\n"
			       "\n"
			       "--%s--\n",
			       boundary, boundary
		);
		CM_SetAsField(history_msg, eMesageText, &buf, len);
	}

	/* Update the history message (regardless of whether it's new or existing) */

	/* Remove the Message-ID from the old version of the history message.  This will cause a brand
	 * new one to be generated, avoiding an uninitentional hit of the loop zapper when we replicate.
	 */
	CM_FlushField(history_msg, emessageId);

	/* Figure out the boundary string.  We do this even when we generated the
	 * boundary string in the above code, just to be safe and consistent.
	 */
	*boundary = '\0';

	ptr = history_msg->cm_fields[eMesageText];
	do {
		ptr = memreadline(ptr, buf, sizeof buf);
		if (*ptr != 0) {
			striplt(buf);
			if (!IsEmptyStr(buf) && (!strncasecmp(buf, "Content-type:", 13))) {
				if (
					(bmstrcasestr(buf, "multipart") != NULL)
					&& (bmstrcasestr(buf, "boundary=") != NULL)
				) {
					safestrncpy(boundary, bmstrcasestr(buf, "\""), sizeof boundary);
					char *qu;
					qu = strchr(boundary, '\"');
					if (qu) {
						strcpy(boundary, ++qu);
					}
					qu = strchr(boundary, '\"');
					if (qu) {
						*qu = 0;
					}
				}
			}
		}
	} while ( (IsEmptyStr(boundary)) && (*ptr != 0) );

	/*
	 * Now look for the first boundary.  That is where we need to insert our fun.
	 */
	if (!IsEmptyStr(boundary)) {
		char *MsgText;
		long MsgTextLen;
		time_t Now = time(NULL);

		snprintf(prefixed_boundary, sizeof(prefixed_boundary), "--%s", boundary);
		
		CM_GetAsField(history_msg, eMesageText, &MsgText, &MsgTextLen);

		ptr = bmstrcasestr(MsgText, prefixed_boundary);
		if (ptr != NULL) {
			StrBuf *NewMsgText;
			char uuid[64];
			char memo[512];
			long memolen;
			char encoded_memo[1024];
			
			NewMsgText = NewStrBufPlain(NULL, MsgTextLen + diffbuf_len + 1024);

			generate_uuid(uuid);
			memolen = snprintf(memo, sizeof(memo), "%s|%ld|%s|%s", 
					   uuid,
					   Now,
					   CCC->user.fullname,
					   CtdlGetConfigStr("c_nodename"));

			memolen = CtdlEncodeBase64(encoded_memo, memo, memolen, 0);

			StrBufAppendBufPlain(NewMsgText, HKEY("--"), 0);
			StrBufAppendBufPlain(NewMsgText, boundary, -1, 0);
			StrBufAppendBufPlain(
				NewMsgText, 
				HKEY("\n"
				     "Content-type: text/plain\n"
				     "Content-Disposition: inline; filename=\""), 0);

			StrBufAppendBufPlain(NewMsgText, encoded_memo, memolen, 0);

			StrBufAppendBufPlain(
				NewMsgText, 
				HKEY("\"\n"
				     "Content-Transfer-Encoding: 8bit\n"
				     "\n"), 0);

			StrBufAppendBufPlain(NewMsgText, diffbuf, diffbuf_len, 0);
			StrBufAppendBufPlain(NewMsgText, HKEY("\n"), 0);

			StrBufAppendBufPlain(NewMsgText, ptr, MsgTextLen - (ptr - MsgText), 0);
			free(MsgText);
			CM_SetAsFieldSB(history_msg, eMesageText, &NewMsgText); 
		}
		else
		{
			CM_SetAsField(history_msg, eMesageText, &MsgText, MsgTextLen); 
		}

		CM_SetFieldLONG(history_msg, eTimestamp, Now);
	
		CtdlSubmitMsg(history_msg, NULL, "", 0);
	}
	else {
		syslog(LOG_ALERT, "Empty boundary string in history message.  No history!\n");
	}

	free(diffbuf);
	CM_Free(history_msg);
	return(0);
}