示例#1
0
文件: base_to.c 项目: smokku/wpjabber
result base_to_config(instance id, xmlnode x, void *arg)
{
	if (id == NULL) {
		jid j = jid_new(xmlnode_pool(x), xmlnode_get_data(x));

		log_debug("base_to_config validating configuration\n");
		if (j == NULL) {
			xmlnode_put_attrib(x, "error",
					   "'to' tag must contain a jid to send log data to");
			log_debug("Invalid Configuration for base_to");
			return r_ERR;
		}
		return r_PASS;
	}

	log_debug("base_to configuring instance %s", id->id);

	if (id->type != p_LOG) {
		log_alert(NULL,
			  "ERROR in instance %s: <to>..</to> element only allowed in log sections",
			  id->id);
		return r_ERR;
	}

	register_phandler(id, o_DELIVER, base_to_deliver,
			  (void *) xmlnode_get_data(x));

	return r_DONE;
}
示例#2
0
void workloop(void *t) {
  Loop* me = (Loop*)t;
  log_info("%s starting.", me->name);

  LoopData loop;
  loop.count = 0;
  loop.period = start_period / n_worker;
  loop.deadline = abs_start + loop.period*me->id;

  // entering primary mode
  rt_task_set_mode(0, T_WARNSW, NULL);/* Ask Xenomai to warn us upon
					 switches to secondary mode. */

  RTIME now = rt_timer_read();
  while(loop.deadline < now) loop.deadline += loop.period;

  while(bTesting) {
    rt_task_sleep_until(loop.deadline);//blocks /////////////////////
    if(!bTesting) break;

    now = rt_timer_read();
    loop.jitter = now - loop.deadline;//measure jitter

    /* Begin "work" ****************************************/
    me->work(); //rt_task_sleep(100000000); //for debugging
    /* End "work" ******************************************/
    RTIME t0 = now;//use an easy to remember var
    now = rt_timer_read();

    // Post work book keeping ///////////////////////////////
    //to report how much the work took
    loop.t_work = now - t0;
    if(me->loopdata_q.push(loop)) {
    } else { /* Have to throw away data; need to alarm! */
      log_alert("Loop data full");
    }

    if(!me->late_q.isEmpty()// Manage the late q
       && me->late_q[0].count < (loop.count - 100)) {
      me->late_q.pop(); // if sufficiently old, forget about it
    }
    loop.deadline += loop.period;
    if(now > loop.deadline) { // Did I miss the deadline?
      // How badly did I miss the deadline?
      // Definition of "badness": just a simple count over the past N loop
      if(me->late_q.isFull()) { //FATAL
	log_fatal("Missed too many deadlines");
	break;
      }
    }

    /* decrement the period by a fraction */
    loop.period -= dec_ppm ? loop.period / (1000000 / dec_ppm) : 0;
    if(loop.period < 1000000) break; /* Limit at 1 ms for now */
    ++loop.count;
  }

  rt_task_set_mode(T_WARNSW, 0, NULL);// popping out of primary mode
  log_info("%s exiting.", me->name);
}
示例#3
0
文件: xdb.c 项目: smokku/wpjabber
/* match will find a child in the parent, and either replace (if it's an insert) or remove (if data is NULL) */
int xdb_act(xdbcache xc, jid owner, char *ns, char *act, char *match,
	    xmlnode data)
{
	xdbrequest_p cur;
	struct timeval tv;

	if (xc->shutdown)
		return 1;

	if (xc == NULL || owner == NULL || ns == NULL) {
		log_alert("xdb_set",
			  "Programming Error: xdb_set() called with NULL\n");
		return 1;
	}

	log_debug("XDB SET");


	cur = malloc(sizeof(xdbrequest_t));
	memset(cur, 0, sizeof(xdbrequest_t));

	cur->set = 1;
	cur->data = data;
	cur->ns = ns;
	cur->owner = owner;
	cur->act = act;
	cur->match = match;
	gettimeofday(&tv, NULL);
	cur->sent = tv.tv_sec;

	SEM_LOCK(xc->sem);
	cur->id = xc->id++;

	cur->next = xc->first;
	xc->first = cur;

	SEM_UNLOCK(xc->sem);

	/* send it on it's way */
	xdb_deliver(xc->i, cur, 0);
	cur->external = 1;

	/* if it hasn't already returned, we should block here until it returns */
	while (cur->preblock != 1)
		usleep(10);

	/* if it didn't actually get set, flag that */
	if (cur->data == NULL) {
		free(cur);
		return 1;
	}

	xmlnode_free(cur->data);

	free(cur);
	return 0;
}
示例#4
0
文件: init.c 项目: bigclouds/opendove
/*
 ******************************************************************************
 * dcs_read_version --                                                    *//**
 *
 * \brief This routine reads the version from the flash file
 *
 * \return dove_status
 *
 *****************************************************************************/
static void dcs_read_version()
{
	FILE *fp = NULL;
	int error = -1;

	do
	{
		memset(dsa_version_string, 0, DSA_VERSION_MAX_LENGTH);
		fp = fopen(DSA_VERSION_FILE, "r");
		if(fp == NULL)
		{
			log_alert(PythonDataHandlerLogLevel,
			          "Version file not found [%s]",
			           DSA_VERSION_FILE);
			break;
		}
		// read the file and populate the global
		if(fgets(dsa_version_string, 120, fp) == NULL)
		{
			log_alert(PythonDataHandlerLogLevel,
			          "Cannot read ROLE File %s, probably corrupted",
			          DSA_VERSION_FILE);
			break;
		}
		show_print("DSA Version: %s", dsa_version_string);
		log_notice(PythonDataHandlerLogLevel,
		           "DSA Version: %s", dsa_version_string);
		error = 0;
	}while(0);
	if (fp)
	{
		fclose(fp);
	}
	if (error)
	{
		//Put fake version in
		sprintf(dsa_version_string, "0.0.0 Thur Jan 1 0:0:0 UDT 1970");
		log_emergency(PythonDataHandlerLogLevel,
		              "Generating Fake DSA Version: %s", dsa_version_string);
	}
	return;
}
示例#5
0
void *fast_mtq_thread(void *arg)
{
	fast_mtq f_mtq = (fast_mtq) arg;
	register fast_mtq_elem e;
	void *cb_arg;

	cb_arg = f_mtq->arg;

	if (f_mtq->start_cb) {
		cb_arg = (f_mtq->start_cb) (cb_arg);
	}

	log_debug("fast mtq thread start");

	while (1) {

		/* check if something to resolv */
		SEM_LOCK(f_mtq->sem);

		e = NULL;

		if (f_mtq->shutdown != 2) {
			if ((!(f_mtq->first)) && (!(f_mtq->shutdown))) {
				COND_WAIT(f_mtq->cond, f_mtq->sem);
			}

			/* get element */
			e = f_mtq->first;
			if (e) {
				f_mtq->first = e->mtq_next;
				f_mtq->queue--;
				f_mtq->queue2--;
			}
		}

		SEM_UNLOCK(f_mtq->sem);

		if (e) {
			(f_mtq->cb) (cb_arg, (void *) e);
		} else {
			if (f_mtq->shutdown)
				break;
		}
	}

	log_alert("mtq", "fast mtq thread stop %d [%d][%d]",
		  f_mtq->shutdown, f_mtq->queue, f_mtq->queue2);

	if (f_mtq->stop_cb) {
		(f_mtq->stop_cb) (cb_arg);
	}

	return NULL;
}
示例#6
0
static void dps_heartbeat_main(void *pDummy)
{

    struct timespec   ts;
    struct timeval    tp;
    int               it;
    int               rc;

    Py_Initialize();
    while (TRUE) {
        pthread_mutex_lock(&dps_heartbeat_mp);
        it = dps_heartbeat_sample_interval;
        gettimeofday(&tp, NULL);
        /* Convert from timeval to timespec */
        ts.tv_sec  = tp.tv_sec;
        ts.tv_nsec = tp.tv_usec * 1000;
        ts.tv_sec += it;
        rc = pthread_cond_timedwait(&dps_heartbeat_cv, &dps_heartbeat_mp, &ts);
        if (rc == ETIMEDOUT)
        {
            pthread_mutex_unlock(&dps_heartbeat_mp);
            if(dps_heartbeat_send && controller_location_set)/* Whether to send heartbeat */
            {
                /* Send Heartbeat to DOVE Controller*/
                log_info(RESTHandlerLogLevel, "Send Heartbeat to Dove Controller");
                //Send the heartbeat is NOT success as the correct repsponse is not received yet
                //set it in response handler when received a HTTP_OK
                last_heartbeat_to_dmc_is_success = 0;
                dps_heartbeat_send_to_dove_controller();
                dps_heartbeat_to_dmc_send_count ++;
            }

            /* Check if we need registration to DMC again */
            if(get_dps_appliance_registration_needed())
            {
                log_info(RESTHandlerLogLevel, "Send DCS appliance registration to DMC!");
                dps_appliance_registration();
                if (dcs_role_assigned)
                {
                    log_alert(RESTHandlerLogLevel,
                              "DCS: Sending Query to DMC for list of Nodes");
                    dps_rest_client_query_dove_controller_cluster_info();
                }
            }
            continue;
        }
        pthread_mutex_unlock(&dps_heartbeat_mp);
    }
    Py_Finalize();

    return;
}
示例#7
0
void warn_upon_switch(int sig __attribute__((unused)))
{
#if BACKTRACE // couldn't compile this for some reason; TODO
  void *bt[32];
  int nentries;
  /* Dump a backtrace of the frame which caused the switch to
     secondary mode: */
  nentries = backtrace(bt,sizeof(bt) / sizeof(bt[0]));
  backtrace_symbols_fd(bt,nentries,fileno(stdout));
#else
  log_alert("Switched to 2ndary mode\n");
#endif
}
示例#8
0
文件: xdb.c 项目: Doap/transports
/** resend packets. heartbeat thread */
result xdb_thump(void *arg)
{
    xdbcache xc = (xdbcache)arg;
    xdbcache cur, next;
    int now = time(NULL);

    pthread_mutex_lock(&(xc->sem));
    /* spin through the cache looking for stale requests */
    cur = xc->next;
    while(cur != xc)
    {
        next = cur->next;

        /* really old ones get wacked */
        if((now - cur->sent) > 30)
        {
            /* remove from ring */
            cur->prev->next = cur->next;
            cur->next->prev = cur->prev;

            /* make sure it's null as a flag for xdb_set's */
            cur->data = NULL;

            /* free the thread! */
			cur->preblock = 1;

            cur = next;
            continue;
        }

        /* resend the waiting ones every so often */
        if((now - cur->sent) > 10) {
		  log_alert(ZONE,"Resend xdb packet");
	 	  xdb_deliver(xc->i, cur,1);
		}

        /* cur could have been free'd already on it's thread */
        cur = next;
    }


    pthread_mutex_unlock(&(xc->sem));
    return r_DONE;
}
示例#9
0
文件: xdb.c 项目: smokku/wpjabber
/** resend packets. heartbeat thread */
result xdb_thump(void *arg)
{
	xdbcache xc = (xdbcache) arg;
	xdbrequest_p cur, next, last;
	struct timeval tv;
	time_t now;

	if (xc->shutdown)
		return r_UNREG;

	gettimeofday(&tv, NULL);
	now = tv.tv_sec;

	SEM_LOCK(xc->sem);
	/* spin through the cache looking for stale requests */

	for (last = NULL, cur = xc->first; cur;) {
		next = cur->next;
		if ((cur->external) && ((now - cur->sent) > 30)) {

			if (!last)
				xc->first = next;
			else
				last->next = next;

			cur->data = NULL;
			cur->preblock = 1;
		} else {
			last = cur;

			if ((cur->external) && ((now - cur->sent) > 10)) {
				log_alert("xdb", "Resend xdb packet");
				xdb_deliver(xc->i, cur, 1);
			}
		}

		cur = next;
	}
	SEM_UNLOCK(xc->sem);

	return r_DONE;
}
示例#10
0
文件: init.c 项目: bigclouds/opendove
/*
 ******************************************************************************
 * dcs_write_role_to_file --                                              *//**
 *
 * \brief This routine write the role to the file
 *
 * \param role
 *
 * \return dove_status
 *
 *****************************************************************************/
static void dcs_write_role_to_file(int role)
{
	FILE *fp = NULL;
	char role_string[16];
	char path[100] = {'\0'};

	sprintf(path, "%s/%s", getenv("HOME"), DCS_ROLE_FILE);
	if((fp = fopen(path,"w")) == NULL) {
		log_alert(PythonClusterDataLogLevel,
		          "[ERROR] in opening(write) ROLE file [%s]",
		          path);
	}else{
		sprintf(role_string, "%d", role);
		fputs(role_string, fp);
		log_notice(PythonClusterDataLogLevel,
		           "Wrote Role %d to file %s",role, path);
		fclose(fp);
	}
	return;
}
示例#11
0
文件: deliver.c 项目: smokku/wpjabber
/* deliver threads, when offline user or server */
void js_deliver_thread_hander(void *arg, void *value)
{
	jsmi si = (jsmi) arg;
	packet_thread_p pt = (packet_thread_p) value;

	/* */
	if ((pt->jp) && (pt->p)) {
		log_debug("Get user Simple packet");
		js_outgoing_packet(si, pt->jp, pt->p);
		return;
	}

	if (!pt->p) {
		log_debug("SImple packet");
		js_deliver_local(si, pt->jp);
		return;
	}


	log_alert("fatal", "error - unknown state");
}
示例#12
0
result base_file_config(instance id, xmlnode x, void *arg)
{
    basefile bf;
        
    if(id == NULL)
    {
        log_debug(ZONE,"base_file_config validating configuration");

        if (xmlnode_get_data(x) == NULL)
        {
            log_debug(ZONE,"base_file_config error: no filename provided.");
            xmlnode_put_attrib(x,"error","'file' tag must contain a filename to write to");
            return r_ERR;
        }
        return r_PASS;
    }

    log_debug(ZONE,"base_file configuring instance %s",id->id);

    if(id->type != p_LOG)
    {
        log_alert(NULL,"ERROR in instance %s: <file>..</file> element only allowed in log sections", id->id);
        return r_ERR;
    }

    bf = pmalloco(id->p,sizeof(_basefile));
    bf->filename = pstrdup(id->p,xmlnode_get_data(x));
    bf->yesterday.tm_mday = -1;
    bf->last_time = 0;
    bf->f = NULL;
    pthread_mutex_init(&(bf->sem),NULL);

    /* Register a handler for this instance... */
    register_phandler(id, o_DELIVER, base_file_deliver, (void*)bf);

    pool_cleanup(id->p, _base_file_shutdown, (void*)bf);
    
    return r_DONE;
}
示例#13
0
/** Shut down transport, kill all sessions */
void it_shutdown(void *arg)
{
    iti ti = (iti) arg;

    log_alert(ZONE,"JIT Transport, shutting down");

    ti->shutdown = 1;

    /* wait */
    usleep(1000);

    if (ti->sessions_count) { 
	  SEM_LOCK(ti->sessions_sem);
      wpxhash_walk(ti->sessions,it_sessions_end,NULL);      
	  SEM_UNLOCK(ti->sessions_sem);
    }

    while (ti->sessions_count > 0)
      usleep(100);
    
    wpxhash_free(ti->sessions);
    ti->sessions = NULL;
}
示例#14
0
文件: xdb.c 项目: smokku/wpjabber
xdbcache xdb_cache(instance id)
{
	xdbcache xc;

	if (id == NULL) {
		log_alert("xdb",
			  "Programming Error: xdb_cache() called with NULL\n");
		return NULL;
	}

	xc = pmalloco(id->p, sizeof(_xdbcache));
	xc->i = id;		/* flags it as the top of the ring too */
	xc->first = NULL;	/* init ring */
	SEM_INIT(xc->sem);

	/* register the handler in the instance to filter out xdb results */
	register_phandler(id, o_PRECOND, xdb_results, (void *) xc);

	/* heartbeat to keep a watchful eye on xdb_cache */
	register_beat(10, xdb_thump, (void *) xc);

	register_shutdown_first(xdb_shutdown, (void *) xc);
	return xc;
}
示例#15
0
static void dps_heartbeat_send_to_dove_controller()
{
    json_t *js_res = NULL;
    char dps_heartbeat_uri[MAX_URI_LEN];

    sprintf (dps_heartbeat_uri, DPS_DOVE_CONTROLLER_DPS_HEARTBEAT_URI, dps_node_uuid);

    log_debug(RESTHandlerLogLevel, "Enter");
    do
    {
        js_res = dps_form_json_heartbeat();
        if(js_res == NULL)
        {
            log_alert(RESTHandlerLogLevel,
                      "Can not form json for heartbeat");
            break;
        }
        dps_rest_client_json_send_to_dove_controller(js_res,
                dps_heartbeat_uri,
                EVHTTP_REQ_PUT);
    } while(0);
    log_debug(RESTHandlerLogLevel, "Exit");
    return;
}
示例#16
0
文件: liao_server.c 项目: kyosold/sc
int main(int argc, char **argv)
{
	liao_log("liao_server", LOG_PID|LOG_NDELAY, LOG_MAIL);

	if (argc != 3) {
		usage(argv[0]);
		exit(0);
	}

	if (chdir(LIAO_HOME) == -1) {
		log_alert("cannot start: unable to switch to home directory");	
		exit(0);
	}

	snprintf(msg_id, sizeof(msg_id), "00000000");
	
	char cfg_file[MAX_LINE] = CFG_FILE;
	
	int c;
	const char *args = "c:h";
	while ((c = getopt(argc, argv, args)) != -1) {
		switch (c) {
			case 'c':
				snprintf(cfg_file, sizeof(cfg_file), "%s", optarg);
				break;
				
			case 'h':
			default:
				usage(argv[0]);
				exit(0);
		}
	}

	// 处理配置文件 
	if (conf_init(cfg_file)) {
		fprintf(stderr, "Unable to read control files:%s\n", cfg_file);
		log_error("Unable to read control files:%s", cfg_file);
		exit(1);
	}

	/*	
	// 检查队列目录
	if (strlen(config_st.queue_path) <= 0) {
		fprintf(stderr, "Unable to read queue path.\n");
		log_error("Unable to read queue path.");
		exit(1);
	}
	if ( access(config_st.queue_path, F_OK) ) {
		fprintf(stderr, "Queue path:%s not exists:%s, so create it.\n", config_st.queue_path, strerror(errno));	
		log_error("Queue path:%s not exists:%s, so create it.", config_st.queue_path, strerror(errno));	

		umask(0);
		mkdir(config_st.queue_path, 0777);
	}*/
	

	online_d = dictionary_new(atoi(config_st.max_works) + 1);
	

	child_st = (struct childs *)malloc((atoi(config_st.max_works) + 1) * sizeof(struct childs));
	if (!child_st) {
		log_error("malloc childs [%d] failed:[%d]%s", (atoi(config_st.max_works) + 1), errno, strerror(errno));
		exit(1);
	}
	
	int i = 0;
	for (i=0; i<(atoi(config_st.max_works) + 1); i++) {
		child_st[i].used = 0;
		child_st[i].pid = -1;
		child_st[i].client_fd = -1;
		child_st[i].pipe_r_in = -1;
		child_st[i].pipe_r_out = -1;
		child_st[i].pipe_w_in = -1;
		child_st[i].pipe_w_out = -1;
		memset(child_st[i].mid, 0, sizeof(child_st[i].mid));
		child_st[i].mfp_out = NULL;
	}

	// 开始服务
	int connfd, epfd, sockfd, n, nread;
	struct sockaddr_in local, remote;
	socklen_t addrlen;

	// 初始化buffer
	char buf[BUF_SIZE];

	size_t pbuf_len = 0;
	size_t pbuf_size = BUF_SIZE + 1;
	char *pbuf = (char *)calloc(1, pbuf_size);
	if (pbuf == NULL) {
		log_error("calloc fail: size[%d]", pbuf_size);
		exit(1);
	}

	// 创建listen socket
	int bind_port = atoi(config_st.bind_port);
	if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		log_error("socket failed:[%d]:%s", errno, strerror(errno));
		exit(1);
	}
	if (setnonblocking(listenfd) > 0) {
		exit(1);
	}

	bzero(&local, sizeof(local));
	local.sin_family = AF_INET;
	local.sin_addr.s_addr = htonl(INADDR_ANY);
	local.sin_port = htons(bind_port);
	if (bind(listenfd, (struct sockaddr *)&local, sizeof(local)) < 0) {
		log_error("bind local %d failed:[%d]%s", bind_port, errno, strerror(errno));
		exit(1);
	}
	log_info("bind local %d succ", bind_port);

	if (listen(listenfd, atoi(config_st.max_works)) != 0) {
		log_error("listen fd[%d] max_number[%d] failed:[%d]%s", listenfd, atoi(config_st.max_works), errno, strerror(errno));
		exit(1);
	}
	
	// 忽略pipe信号 
	sig_pipeignore();
	// 捕抓子进程退出信号
	sig_catch(SIGCHLD, sigchld);

	// epoll create fd
	epoll_event_num = atoi(config_st.max_works) + 1;
	epoll_evts = NULL;
	epoll_fd = -1;
	epoll_nfds = -1;

	int epoll_i = 0;

	epoll_evts = (struct epoll_event *)malloc(epoll_event_num * sizeof(struct epoll_event));
	if (epoll_evts == NULL) {
		log_error("alloc epoll event failed");
    	_exit(111);
    }

	epoll_fd = epoll_create(epoll_event_num);
	if (epoll_fd == -1) {
		log_error("epoll_create max_number[%d] failed:[%d]%s", epoll_event_num, errno, strerror(errno));
		exit(1);
	}

	struct epoll_event ev;
	ev.events = EPOLLIN;
	ev.data.fd = listenfd;
	if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, ev.data.fd, &ev) == -1) {
		log_error("epoll_ctl: listen_socket failed:[%d]%s", errno, strerror(errno));
		exit(1);
	}
	epoll_num_running = 1;

	for (;;) {

		epoll_nfds = epoll_wait(epoll_fd, epoll_evts, epoll_event_num, -1);
		
		if (epoll_nfds == -1) {
			if (errno == EINTR)	{
				// 收到中断信号
				log_info("epoll_wait recive EINTR signal, continue");
				continue;
			}

			_exit(111);
		}

		log_debug("epoll_num_running:%d nfds:%d", epoll_num_running, epoll_nfds);
		for (epoll_i = 0; epoll_i < epoll_nfds; epoll_i++) {
			sig_childblock();

			int evt_fd = epoll_evts[epoll_i].data.fd;
			if (evt_fd == listenfd) {
				if ((connfd = accept(listenfd, (struct sockaddr *) &remote, &addrlen)) > 0) {
					char *ipaddr = inet_ntoa(remote.sin_addr);
					log_info("accept client:%s", ipaddr);
					
					char greetting[512] = {0};
					char hostname[1024] = {0};
					if (gethostname(hostname, sizeof(hostname)) != 0) {
						snprintf(hostname, sizeof(hostname), "unknown");
					}

					// 取客户端IP,Port
					char client_ip[20] = {0};
					char client_port[20] = {0};
					struct sockaddr_in sa;
					int len = sizeof(sa);
					if (!getpeername(connfd, (struct sockaddr *)&sa, &len)) {
						snprintf(client_ip, sizeof(client_ip), "%s", inet_ntoa(sa.sin_addr));
						snprintf(client_port, sizeof(client_port), "%d", ntohs(sa.sin_port));
					}

					
					// 取一个新的client
					int i = new_idx_from_child_st();
					if (i == -1) {
						log_error("new_idx_from_client_st fail: maybe client queue is full.");

						// send error
						snprintf(greetting, sizeof(greetting), "%s ERR %s%s", TAG_GREET, hostname, DATA_END);
						write(connfd, greetting, strlen(greetting));
						log_debug("send fd[%d]:%s", connfd, greetting);

						continue;		
					}
					child_st[i].used = 1;
					
					int pir[2];
					int piw[2];
					if (pipe(pir) == -1) {
						log_error("unable to create pipe:%s", strerror(errno));
					
						// send error
						snprintf(greetting, sizeof(greetting), "%s ERR %s%s", TAG_GREET, hostname, DATA_END);
						write(connfd, greetting, strlen(greetting));
						log_debug("send fd[%d]:%s", connfd, greetting);
						
						continue;
					}
					if (pipe(piw) == -1) {
						log_error("unable to create pipe:%s", strerror(errno));

						close(pir[0]);
						close(pir[1]);
						pir[0] = -1;
						pir[1] = -1;

						// send error
                        snprintf(greetting, sizeof(greetting), "%s ERR %s%s", TAG_GREET, hostname, DATA_END);
                        write(connfd, greetting, strlen(greetting));
                        log_debug("send fd[%d]:%s", connfd, greetting);

                        continue;
					}
					log_debug("create pir[0]:%d pir[1]:%d", pir[0], pir[1]);
					log_debug("create piw[0]:%d piw[1]:%d", piw[0], piw[1]);
					
					
					// 当程序执行exec函数时本fd将被系统自动关闭,表示不传递给exec创建的新进程
					//fcntl(pir[0], F_SETFD, FD_CLOEXEC);			
					//fcntl(piw[1], F_SETFD, FD_CLOEXEC);			

					int f = fork();
					if (f < 0) {
						log_error("fork fail:%s", strerror(errno));

						close(pir[0]);
						close(pir[1]);
						pir[0] = -1;
						pir[1] = -1;

						close(piw[0]);
						close(piw[1]);
						piw[0] = -1;
						piw[1] = -1;
						
						child_st[i].used = 0;

						// send error
                        snprintf(greetting, sizeof(greetting), "%s ERR %s%s", TAG_GREET, hostname, DATA_END);
                        write(connfd, greetting, strlen(greetting));
                        log_debug("send fd[%d]:%s", connfd, greetting);

                        continue;
					}

					struct timeval tm;
					gettimeofday(&tm, NULL);
					snprintf(child_st[i].mid, sizeof(child_st[i].mid), "%05u%u", (uint32_t)tm.tv_usec, (uint32_t)f);
					snprintf(msg_id, sizeof(msg_id), "%s", child_st[i].mid);

					if (f == 0) {
						// 子进程
						close(pir[0]);
						close(piw[1]);
						close(listenfd);

						char _cmid[512] = {0};
						char _cchild_st[512] = {0};
						char _ccip[20] = {0};
						char _ccport[20] = {0};

						snprintf(_cmid, sizeof(_cmid), "-m%s", child_st[i].mid);
						snprintf(_cchild_st, sizeof(_cchild_st), "-c%s", config_st.child_cf);
						snprintf(_ccip, sizeof(_ccip), "-i%s", client_ip);
						snprintf(_ccport, sizeof(_ccport), "-p%s", client_port);

						char *args[6];
						args[0] = "./liao_command";
						args[1] = _cmid;
						args[2] = _cchild_st;
						args[3] = _ccip;
						args[4] = _ccport;
						args[5] = 0;

						if (fd_move(0, connfd) == -1) {
							log_info("%s fd_move(0, %d) failed:%d %s", child_st[i].mid, connfd, errno, strerror(errno));
							_exit(111);
						}

						if (fd_move(1, pir[1]) == -1) {
							log_info("%s fd_move(pipe_w, %d) failed:%d %s", child_st[i].mid, pir[1], errno, strerror(errno));
							_exit(111);
						}
						if (fd_move(2, piw[0]) == -1) {
							log_info("%s fd_move(pipe_r, %d) failed:%d %s", child_st[i].mid, piw[0], errno, strerror(errno));
							_exit(111);
						}

						if (execvp(*args, args) == -1) {
							log_error("execp fail:%s", strerror(errno));
							_exit(111);
						}
						//if (error_temp(errno))
						//	_exit(111);
						log_debug("execp succ");
						_exit(100);							

					}

					close(connfd);
			
					child_st[i].pipe_r_in = pir[0];
					close(pir[1]);
					pir[1] = -1;
					child_st[i].pipe_r_out = -1;

					child_st[i].pipe_w_out = piw[1];
					close(piw[0]);
					piw[0] = -1;
					child_st[i].pipe_w_in = -1;


					child_st[i].pid = f;

					
					if (setnonblocking(child_st[i].pipe_r_in) != 0) {
						log_error("setnonblocking fd[%d] failed", child_st[i].pipe_r_in);
					}

					
					struct epoll_event pipe_in_ev;
					pipe_in_ev.events = EPOLLIN | EPOLLET;	
					pipe_in_ev.data.fd = child_st[i].pipe_r_in;
					if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, pipe_in_ev.data.fd, &pipe_in_ev) == -1) {
						log_error("epoll_ctl client fd[%d] EPOLL_CTL_ADD failed:[%d]%s", pipe_in_ev.data.fd, errno, strerror(errno));
					}
					log_debug("epoll_add fd[%d]", pipe_in_ev.data.fd);

					

				} else if (connfd == -1) {
					if (errno != EAGAIN && errno != ECONNABORTED && errno != EPROTO && errno != EINTR) {
						log_error("accept failed:[%d]%s", errno, strerror(errno));
					}

					continue;
				}

			} else if (epoll_evts[epoll_i].events & EPOLLIN) {
				
				int ci = get_idx_with_sockfd(evt_fd);
				if (ci < 0) {
					log_error("socket fd[%d] get_idx_with_sockfd fail", evt_fd);
					continue;
				}	
				log_debug("%s get event EPOLLIN: epoll_i[%d] fd[%d] get d_i[%d] fd[%d], used[%d]", child_st[ci].mid, epoll_i, epoll_evts[epoll_i].data.fd, child_st[ci].pipe_r_in, child_st[ci].used);

				// 读取内容 ----------------------
				char inbuf[BUF_SIZE] = {0};
				char *pinbuf = inbuf;
				int inbuf_size = BUF_SIZE;
				int inbuf_len = 0;
				char ch;
				
				
				do {
					i = 0;
					nread = read(child_st[ci].pipe_r_in, inbuf, inbuf_size);
					log_debug("%s read from liao_command:[%d]", child_st[ci].mid, nread);

					if (nread == -1) {
						// read error on a readable pipe? be serious
						//log_error("it is failed from fd[%d] read. error:%d %s", child_st[ci].fd_in, errno, strerror(errno));
						//log_debug("it is failed from fd[%d] read. error:%d %s", child_st[ci].pipe_r_in, errno, strerror(errno));
						break;

					} else if (nread > 0) {
						if (child_st[ci].mfp_out == NULL) {
							child_st[ci].mfp_out = mopen(MAX_BLOCK_SIZE, NULL, NULL);
							if (child_st[ci].mfp_out == NULL) {
								log_debug("%s mopen for body fail", child_st[ci].mid);
								break;
							}
						}	

						while (i < nread) {	
							ch = inbuf[i];	
							
							if ((inbuf_size - inbuf_len) < 2) {
								int r = fast_write(child_st[ci].mfp_out, inbuf, inbuf_len);
								if (r == 0) {
									log_error("%s fast_write fail", child_st[ci].mid);
									break;
								}	

								memset(inbuf, 0, inbuf_size);
								inbuf_len = 0;
							}	

							mybyte_copy(pinbuf + inbuf_len, 1, &ch);
							inbuf_len++;	

							if (ch == '\n') {
								if (inbuf_len > 0) {
									int r = fast_write(child_st[ci].mfp_out, inbuf, inbuf_len);
									if (r == 0) {
										log_error("%s fast_write fail", child_st[ci].mid);
										break;
									}

									memset(inbuf, 0, inbuf_size);
									inbuf_len = 0;
								}
								
								// 处理当前指令
								// ...
								process_system(&child_st[ci]);
								// ...
								
								// 处理完成后
								if (child_st[ci].mfp_out != NULL) {
									mclose(child_st[ci].mfp_out);
									child_st[ci].mfp_out = NULL;
									
									child_st[ci].mfp_out = mopen(MAX_BLOCK_SIZE, NULL, NULL);
									if (child_st[ci].mfp_out == NULL) {
										log_error("mopen fail for mfp_out");
										break;
									}
								}
								
								pinbuf = inbuf + 0;
							}

							i++;
						}
						
						
					} else {
						break;
					}

				} while (1);	


			} else if ((epoll_evts[epoll_i].events & EPOLLHUP) && (epoll_evts[epoll_i].data.fd != listenfd)) {

				int ci = get_idx_with_sockfd(evt_fd);
				if ( ci < 0 ) {
					log_error("get_idx_with_sockfd(%d) fail, so not write", evt_fd);

					continue;
				}
				log_debug("%s get event EPOLLHUP: epoll_i[%d] fd[%d] get d_i[%d] fd[%d], used[%d]", child_st[ci].mid, epoll_i, epoll_evts[epoll_i].data.fd, child_st[ci].pipe_r_in, child_st[ci].used);

				epoll_delete_evt(epoll_fd, child_st[ci].pipe_r_in);

				continue;

			}


		}
		sig_childunblock();

	}

	close(epoll_fd);
	close(listenfd);

	log_info("i'm finish");
    
	return 0;
}
示例#17
0
文件: xdb.c 项目: smokku/wpjabber
/* blocks until namespace is retrieved, host must map back to this service! */
xmlnode xdb_get(xdbcache xc, jid owner, char *ns)
{
	xdbrequest_p cur;
	xmlnode x;
	struct timeval tv;

	if (xc->shutdown)
		return NULL;

	if (xc == NULL || owner == NULL || ns == NULL) {
		if (ns) {
			log_alert("xdb_get",
				  "Programming Error: xdb_get() called with NULL ns: %s\n",
				  ns);
		} else {
			log_alert("xdb_get",
				  "Programming Error: xdb_get() called with NULL ns: NULL\n");
		}

		if (owner) {
			log_alert("owner", "%s", jid_full(owner));
		}
		return NULL;
	}

	log_debug("XDB GET");

	/* init this newx */
	cur = malloc(sizeof(xdbrequest_t));
	memset(cur, 0, sizeof(xdbrequest_t));
	// cur->set = 0;
	// cur->data = NULL;
	cur->ns = ns;
	cur->owner = owner;
	gettimeofday(&tv, NULL);
	cur->sent = tv.tv_sec;

	SEM_LOCK(xc->sem);
	cur->id = xc->id++;

	cur->next = xc->first;
	xc->first = cur;

	SEM_UNLOCK(xc->sem);

	/* send it on it's way */
	xdb_deliver(xc->i, cur, 0);
	cur->external = 1;

	/* if it hasn't already returned, we should block here until it returns */
	while (cur->preblock != 1)
		usleep(10);

	/* newx.data is now the returned xml packet */

	/* return the xmlnode inside <xdb>...</xdb> */
	for (x = xmlnode_get_firstchild(cur->data);
	     x != NULL && xmlnode_get_type(x) != NTYPE_TAG;
	     x = xmlnode_get_nextsibling(x));

	/* there were no children (results) to the xdb request, free the packet */
	if (x == NULL)
		xmlnode_free(cur->data);

	free(cur);
	return x;
}
示例#18
0
文件: init.c 项目: bigclouds/opendove
/*
 ******************************************************************************
 * dcs_set_service_role --                                                *//**
 *
 * \brief This routine starts or stops the DCS service role
 *
 * \param action 1:Activate/Set Local Node, 0:Reset Local Node
 *
 * \return dove_status
 *
 *****************************************************************************/
dove_status dcs_set_service_role(uint32_t action)
{
	dove_status status = DOVE_STATUS_ERROR;
	do
	{
		if (action)
		{
			status = dcs_cluster_node_local_update(&dcs_local_ip);
			if (status != DOVE_STATUS_OK)
			{
				log_alert(RESTHandlerLogLevel,
				          "ALERT! DCS Clustering cannot set local IP");
				break;
			}
			status = dcs_controller_interface_start();
			if (status != DOVE_STATUS_OK)
			{
				log_alert(RESTHandlerLogLevel,
				          "ALERT! DCS Controller Interface cannot be started");
				break;
			}
			status = dcs_protocol_handler_start();
			if (status != DOVE_STATUS_OK)
			{
				log_alert(RESTHandlerLogLevel,
				          "ALERT! DCS Client Server Protocol cannot be started");
				break;
			}
			/* do "cluster node add" via sending "query cluster info" */
			status = dcs_cluster_node_local_activate(1);
			if (status != DOVE_STATUS_OK)
			{
				log_alert(RESTHandlerLogLevel,
				          "ALERT! DCS Clustering cannot activate Local Node");
				break;
			}
			//Query the Controller for Cluster Information
			dcs_role_assigned = 1;
		}
		else
		{
			status = dcs_cluster_node_local_activate(0);
			if (status != DOVE_STATUS_OK)
			{
				log_alert(RESTHandlerLogLevel,
				          "ALERT! DCS Clustering cannot deactivate Local Node");
				break;
			}
			status = dcs_protocol_handler_stop();
			if (status != DOVE_STATUS_OK)
			{
				log_alert(RESTHandlerLogLevel,
				          "ALERT! DCS Client Server Protocol cannot be stopped");
				dcs_cluster_node_local_activate(1);
				break;
			}
			status = dcs_controller_interface_stop();
			if (status != DOVE_STATUS_OK)
			{
				log_alert(RESTHandlerLogLevel,
				          "ALERT! DCS Controller Interface cannot be stopped");
				dcs_cluster_node_local_activate(1);
				dcs_protocol_handler_start();
				break;
			}
			dcs_role_assigned = 0;
			cluster_config_version = 0;
		}
		dcs_write_role_to_file(dcs_role_assigned);
		do
		{
			if (!controller_location_set)
			{
				log_info(RESTHandlerLogLevel, "Controller not set by user");
				break;
			}
			if (dcs_local_ip.ip4 == htonl(INADDR_LOOPBACK))
			{
				log_info(RESTHandlerLogLevel,
				         "Local IP not yet set. Not point in sending query");
				break;
			}
			if(get_dps_appliance_registration_needed()) {
				log_notice(RESTHandlerLogLevel, "DCS: Sending Appliance Registration");
				dps_appliance_registration();
			}
			/*if (action)
			{
				log_notice(RESTHandlerLogLevel,
				           "DCS: Sending Query to DMC for list of Nodes");
				dps_rest_client_query_dove_controller_cluster_info();
			}*/
		}while(0);
	}while(0);

	return status;
}
示例#19
0
/*
 ******************************************************************************
 * dgadmin_rest_sync_process --                                               *//**
 *
 * \brief This routine starts a new sync circle.
 *
 * \retval 0 	Success
 * \retval >0 	Failure
 *
 *****************************************************************************/
static int dgadmin_rest_sync_process(void)
{
	char *version_query_body_buf = NULL, *target_uri_body_buf = NULL, *ptr = NULL;
	char target_uri[DGADMIN_URI_LEN];
    char new_uri[DGADMIN_URI_LEN];
	enum evhttp_cmd_type cmd_type;
	int version;
	int operation;
	int version_create, version_update;
	bool more = false;
	int ret = DOVE_STATUS_OK;
    int is_tombstone=0;
    int is_uuid=0;
    int resp_code=0;
	char deluri[DGADMIN_URI_LEN];

	do
	{
		do
		{
			/* step 1 - send version query request to DMC */
			ret = dgadmin_rest_sync_version_query(&version_query_body_buf, &resp_code);
			if (ret != DOVE_STATUS_OK)
			{
                log_alert(ServiceUtilLogLevel,
                          "ERROR\n");
                more = false;
				break;
			}

			/* step 2.a - parse and extract version/uri/cmd_type from response */
			memset(target_uri, 0, sizeof(target_uri));
			ret = dgadmin_rest_sync_version_resp_parser(version_query_body_buf, 
                                                        &version, target_uri, 
                                                        (int *)&operation);
			if (ret != DOVE_STATUS_OK)
			{
                log_alert(ServiceUtilLogLevel,
                          "ERROR\n");
                more = false;
				break;
			}
            else
            {
                if(strlen(target_uri)==0)
                {
                    g_dgwconfig_curversion = version;
                    /* NO URI: go to next version */
                    more = true;
                    break;
                }
            }

            if((operation == DGADMIN_REST_SYNC_OPERATION_GET)||
               (operation == DGADMIN_REST_SYNC_OPERATION_DELETE))
            {
                resp_code=0;
                /* step 2.b - send the GET request for target URI to DMC */
                ret = dgadmin_rest_sync_target_uri_get(target_uri, &target_uri_body_buf,&resp_code);
                if (ret != DOVE_STATUS_OK)
                {
                    if(resp_code==204)
                    {
                        /* content not found 
                         * SKIP this version */
                        g_dgwconfig_valid_curversion = g_dgwconfig_curversion;
                        g_dgwconfig_curversion = version;
                        more = true;
                    }
                    else
                    {
                        log_alert(ServiceUtilLogLevel,
                                  "ERROR %d\n",resp_code);
                        more = false;
                    }
                    break;
                }

                memset(deluri,0,sizeof(deluri));
                ret = dgadmin_rest_sync_version_get_from_buf(target_uri_body_buf, 
                                                             target_uri,
                                                             &version_create, 
                                                             &version_update,
                                                             &is_tombstone,
                                                             &is_uuid, deluri);
                if (ret != DOVE_STATUS_OK)
                {
                    log_alert(ServiceUtilLogLevel, "Fail to get version_create and version_update!");
                    more = false;
                    break;
                }

                if(is_uuid==0)
                {
                    /* SKIP this version */
                    g_dgwconfig_valid_curversion = g_dgwconfig_curversion;
                    g_dgwconfig_curversion = version;
                    more = true;
                    break;
                }


                if (is_tombstone && 
                    (version_create != g_dgwconfig_curversion))
                    /* tombstoned entry ! still lets run thru create 
                     * if we are at create version;
                     * expected change/delete version later*/
                {
                    cmd_type = EVHTTP_REQ_DELETE;
                    if(strlen(deluri) == 0)
                    {
                        log_alert(ServiceUtilLogLevel, "ERROR\n");
                        break;
                    }
                    /* step 3.c - route the DELETE response to dmc agent */
                    ret = dgadmin_rest_sync_dmc_agent(NULL, cmd_type, deluri);
                    if (ret != DOVE_STATUS_OK)
                    {
                        log_alert(ServiceUtilLogLevel, "ERROR\n");
                    }
                }
                else
                {
                    strcpy(new_uri, target_uri);
                    
                    /* step 3.b - 
                     * build new uri. for example, /api/dove/dgw/xyz/1 => /api/dove/dgw/xyz
                     * */
                    ptr = new_uri + strlen(target_uri);
                    while (*ptr != '/')
                    {
                        ptr--;
                    }
                    *ptr = '\0';

                    cmd_type = EVHTTP_REQ_POST;
                    log_alert(ServiceUtilLogLevel, "POST %s", new_uri);
                    log_alert(ServiceUtilLogLevel, "%s\r\n",target_uri_body_buf);

                    /* step 3.c - route the GET response to dmc agent */
                    ret = dgadmin_rest_sync_dmc_agent(target_uri_body_buf, cmd_type, new_uri);
                    if (ret != DOVE_STATUS_OK)
                    {
                        log_alert(ServiceUtilLogLevel, "ERROR\n");
                    }
                }

                g_dgwconfig_valid_curversion = g_dgwconfig_curversion;
                g_dgwconfig_curversion = version;
                log_notice(ServiceUtilLogLevel,"curversion %d valid_curversion %d\r\n",
                           g_dgwconfig_curversion, g_dgwconfig_valid_curversion);
                more = true;

            }
#if 0
            else if(operation == DGADMIN_REST_SYNC_OPERATION_DELETE)
            {
                cmd_type = EVHTTP_REQ_DELETE;
                ret = dgadmin_rest_sync_dmc_agent(NULL, cmd_type, target_uri);
                if (ret != DOVE_STATUS_OK)
                {
                    log_alert(ServiceUtilLogLevel,
                              "ERROR\n");
                    //break;
                }
            
                /* step 4 - update the cluster version if all things success */
                g_dgwconfig_curversion = version;
                more = true;                
            }
#endif
            else
            {
                ret = DOVE_STATUS_NOT_SUPPORTED;
                log_alert(ServiceUtilLogLevel,
                          "ERROR\n");
                break;
            }
        } while(0);

		if (version_query_body_buf)
		{
			free(version_query_body_buf);
			version_query_body_buf = NULL;
		}
		if (target_uri_body_buf)
		{
			free(target_uri_body_buf);
			target_uri_body_buf = NULL;
		}
        /*
		if (ret != DOVE_STATUS_OK)
		{
			more = false;
		}
        */
	} while (more);

	return ret;
}
示例#20
0
int main(int argc, char * const *argv) {
  uint32_t client_opts, send_level;
  const char *identity, *facility;
  
  // ASL client options
  client_opts = 0;
  
  // What level of messages are sent to syslogd
  send_level = ASL_LEVEL_NOTICE;
  
  // Sender identity. This should be NULL, as asl_open() will set this to the
  // name of the program. Only set this if you really need to.
  identity = NULL;
  
  // This should be your UTI
  facility = "se.hunch.asl.example";
  
  // Options accepted by our example program
  int ch;
  static struct option longopts[] = {
    { "debug", no_argument, NULL, 'd' },
    { "stderr", no_argument, NULL, 's' },
    { "no-remote", no_argument, NULL, 'n' },
    { "help", no_argument, NULL, 'h' },
    { NULL, 0, NULL, '\0' }
  };
  
  // Parse options
  while ((ch = getopt_long(argc, argv, "dsnh", longopts, NULL)) != -1) switch (ch) {
    
    case 'd':
      // Send all messages
      send_level = ASL_LEVEL_DEBUG;
      // This disables the remote-control mechanism for adjusting
      // filter levers for processes using e.g. syslog -c ...
      client_opts |= ASL_OPT_NO_REMOTE;
      break;
    
    case 's':
      // Print messages to stderr (adds stderr as an output file descriptor)
      client_opts |= ASL_OPT_STDERR;
      break;
    
    case 'n':
      // Send no messages at all. This does only affect what messages are sent
      // to the server and does not restrict which message are printed to
      // stderr, if enabled.
      send_level = -1;
      break;
    
    // Print usage and help
    default:
      usage(argv[0]);
      exit(1);
  }
  argc -= optind;
  argv += optind;
  
  // Setting ASL_OPT_NO_DELAY connects to the server immediately when calling asl_open()
  client_opts |= ASL_OPT_NO_DELAY;
  
  // Open connection to ASL (log_asl_client is defined in logging.h)
  // See /usr/include/asl.h for more details.
  log_asl_client = asl_open(identity, facility, client_opts);
  // The log_asl_client variable is used by the log_* and Log_* macros in logging.h
  
  // Handle errors from asl_open()
  if (log_asl_client == NULL) {
    perror("asl_open");
    exit(2);
  }
  
  // Set the level for which messages are sent to the server
  log_set_send_filter(send_level);
  
  // Emit one message for each level
  log_emerg("This is a emerg-level message -- this message may propagate "
            "to all TTYs and/or other user interfaces");
  log_alert("This is a alert-level message");
  log_crit("This is a crit-level message");
  log_err("This is a err-level message");
  log_warn("This is a warn-level message");
  log_notice("This is a notice-level message");
  log_info("This is a info-level message");
  log_debug("This message is a debug-level message");
  
  // Close connection to syslogd
  asl_close(log_asl_client);
  
  return 0;
}
示例#21
0
文件: mtq.c 项目: Doap/transports
void mtq_send(mtq q, pool p, mtq_callback f, void *arg)
{
    mtqqueue mq;  /* one element */ 
	mtq mtq;


    /* initialization stuff */
    if(mtq__master == NULL)
    {
	  mtq_init();
    }

    if(q != NULL)  {
      mtq = q;
    }
    else {
      /* take next thread */
	  mtq__master->random++;
	  if (mtq__master->random >= MTQ_THREADS)
		mtq__master->random = 0;
	  
	  mtq = mtq__master->all[mtq__master->random]->mtq;      
    }
	
    /* build queue */
    log_debug(ZONE,"mtq_send insert into mtq=%p",mtq);

    /* lock operation on queue */
    SEM_LOCK(mtq->sem);

    /* find free memory */
    mq = mtq->free_last;
            
    if (mq == NULL)
    {  
	  while ((mq = malloc(sizeof(_mtqqueue)))==NULL) Sleep(1000);
	  /* it means new malloc 
		 maybe we should free this mq later ? */
	  log_alert(ZONE,"MTQ new queue malloc");
	  mq->memory = 1;
	  mtq->length++;
    }
    else   {
	  /* take it out from queue */
	  mtq->free_last = mtq->free_last->prev;
    }
    
    mq->f = f;
    mq->arg = arg;
    mq->prev = NULL;
    
    mtq->dl++;
    
    /* if queue is empty */
    if (mtq->last == NULL)
      mtq->last = mq;
    else
      mtq->first->prev = mq;

    mtq->first = mq;

	COND_SIGNAL(mtq->cond);

    SEM_UNLOCK(mtq->sem);
}
示例#22
0
/*
 ******************************************************************************
 * dgadmin_rest_sync_version_query --                                         *//**
 *
 * \brief This routine sends version GET request to DMC.
 *
 * \param [out]	req_body_buf	A pointer to request input body buffer.
 *
 * \retval 0 	Success
 * \retval >0 	Failure
 *
 *****************************************************************************/
static int dgadmin_rest_sync_version_query(char **req_body_buf, int *resp)
{
	struct evhttp_request *new_request = NULL;
	dgadmin_rest_sync_response_args_t args;
	char uri[DGADMIN_URI_LEN];
	char host_header_str[128];
	int ret = DOVE_STATUS_OK;

    if((!g_dmc_ipv4) || (!g_dmc_port) )
    {
        log_alert(ServiceUtilLogLevel,
                  "Unknown: DMC Info!\n"); 
        return 0;
    }


	do
	{
        struct sockaddr_in sa;
	    char *dmc_httpd_addr = NULL;
		/* construct a new request */
		memset(&args, 0, sizeof(args));
		new_request = evhttp_request_new(dgadmin_rest_sync_response_handler, &args);
		if (new_request == NULL)
		{
			ret = DOVE_STATUS_NO_MEMORY;
            log_notice(ServiceUtilLogLevel,"ERROR");
			break;
		}

        sa.sin_addr.s_addr = g_dmc_ipv4;
        dmc_httpd_addr = inet_ntoa(sa.sin_addr);
		sprintf(host_header_str,"%s:%d", dmc_httpd_addr, g_dmc_port);

		evhttp_add_header(evhttp_request_get_output_headers(new_request), "Host", host_header_str);

        /* Set HTTP Authorization Field
          Basic YWRtaW46YWRtaW4=  Base_64 Encoded Value of the String 'Basic admin:admin" */
        evhttp_add_header(evhttp_request_get_output_headers(new_request),
                          "Authorization", "Basic YWRtaW46YWRtaW4=");

		/* send the GET request to DMC */
		memset(uri, 0, sizeof(uri));
		sprintf(uri, "%s/%d", DGADMIN_REST_SYNC_VERSION_URI, g_dgwconfig_curversion);
		log_notice(ServiceUtilLogLevel, "Sending %s GET REQ to DMC[%s:%d]", 
                  uri, dmc_httpd_addr, g_dmc_port);
		ret = dove_rest_request_and_syncprocess(dmc_httpd_addr,
                                                g_dmc_port,
                                                EVHTTP_REQ_GET, uri,
                                                new_request, NULL,
                                                DGADMIN_REST_SYNC_CONNECT_TIMEOUT);

		*req_body_buf = args.req_body_buf;

		if (ret)
		{
            log_alert(ServiceUtilLogLevel,
                      "ERROR:REST syncprocess\n");
			ret = DOVE_STATUS_ERROR;
			break;
		}
        *resp = args.res_code;
		if ((args.res_code != HTTP_OK) && (args.res_code != 201))
		{
            log_alert(ServiceUtilLogLevel,
                      "ERROR:REST DMC changeversion respose %d\n",args.res_code);
			ret = DOVE_STATUS_ERROR;
			break;
		}
	} while (0);

	return ret;
}
示例#23
0
/** Start up transport. Read configuration, register callbacks. */
void icqtrans(instance i, xmlnode x)
{
    iti ti;
    pool p = i->p;
    xmlnode config;
    xmlnode cur;
	int check;

    log_debug(ZONE,"ICQ Transport, initializing for section '%s'",i->id);

    /* create new transport instance */
    ti = pmalloco(p,sizeof(_iti));
    ti->i = i;
    ti->xc = xdb_cache(i);

    config = xdb_get(ti->xc,jid_new(xmlnode_pool(x),"config@-internal"),"jabber:config:icqtrans");
    if (config == NULL)
    {
        log_error(i->id,"Configuration not found!");
        return;
    }

    ti->registration_instructions = pstrdup(p,xmlnode_get_tag_data(config,"instructions"));
    if (ti->registration_instructions == NULL)
    { 
        log_debug(i->id,"Registration instructions not found");
    }

    ti->search_instructions = pstrdup(p,xmlnode_get_tag_data(config,"search"));
    if (ti->search_instructions == NULL)
    {
        log_debug(i->id,"Search instructions not found");
    }

    ti->charset = pstrdup(p,xmlnode_get_tag_data(config,"charset"));
    if (ti->charset == NULL)
    {
	  log_debug(i->id,"Charset not specified, set default to %s ",DEFAULT_CHARSET);
	  ti->charset = pstrdup(p,DEFAULT_CHARSET);
    }

    _ucs2utf = iconv_open("UTF-8","UCS-2BE");

    _win2utf = iconv_open("UTF-8",ti->charset);
    if (_win2utf==(iconv_t)-1) {
      ti->charset = pstrdup(p,DEFAULT_CHARSET);
      _win2utf = iconv_open("UTF-8",ti->charset);
      if (_win2utf==(iconv_t)-1) {
        log_error(i->id,"Charset error!");
        return;
      }
    }

    _utf2win = iconv_open(ti->charset,"UTF-8");
    if (_utf2win ==(iconv_t)-1) {
      ti->charset = pstrdup(p,DEFAULT_CHARSET);
      _utf2win = iconv_open(ti->charset,"UTF-8");
      if (_utf2win ==(iconv_t)-1) {
        log_error(i->id,"Charset error!");
        return;
      }
    }

	log_notice("config","charset %s",ti->charset);
	
    ti->msg_chat = xmlnode_get_tag(config,"chat") ? 1 : 0;
	if (ti->msg_chat) {
	  log_notice("config","chat messages enabled");
	}
    ti->web_aware = xmlnode_get_tag(config,"web") ? 1 : 0;
	if (ti->web_aware) {
	  log_notice("config","web presence enabled");
	}
    ti->own_roster = xmlnode_get_tag(config,"own_roster") ? 1 : 0;
	if (ti->own_roster) {
	  log_notice("config","JIT will use own roster");
	}
    ti->no_jabber_roster = xmlnode_get_tag(config,"no_jabber_roster") ? 1 : 0;
	if (ti->no_jabber_roster) {
	  log_notice("config","JIT willn't get users from jabber roster");
	}
	ti->no_x_data = xmlnode_get_tag(config,"no_xdata") ? 1 : 0;
	if (ti->no_x_data) {
	  log_notice("config","JIT will not use xdata");
	}

    cur = xmlnode_get_tag(config,"sms");

    if (cur) {
      ti->sms_id = pstrdup(p,xmlnode_get_tag_data(cur,"host"));
      if (ti->sms_id) {
        ti->sms_show = jit_show2status(xmlnode_get_tag_data(cur,"show"));

        if (ti->sms_show==ICQ_STATUS_NOT_IN_LIST) {
          ti->sms_show = ICQ_STATUS_ONLINE;
        }
        
        log_notice("config","sms host %s show: %d",ti->sms_id,ti->sms_show);

        ti->sms_status = pstrdup(p,xmlnode_get_tag_data(cur,"status"));

        if (ti->sms_status) {
          log_debug(ZONE,"sms st %s ",ti->sms_status);
        }

        ti->sms_name = pstrdup(p,xmlnode_get_tag_data(cur,"name"));

	if (ti->sms_name) {
	  log_debug(ZONE,"sms name %s",ti->sms_name);
	}
      }
    }

    ti->count_file = pstrdup(p,xmlnode_get_tag_data(config,"user_count_file"));
    if (ti->count_file == NULL)  {
      ti->count_file = "icqcount";
    }

	log_notice("config","Using %s as count log file",ti->count_file);

    for (cur = xmlnode_get_firstchild(xmlnode_get_tag(config,"server"));
     cur != NULL;
     cur = xmlnode_get_nextsibling(cur)) {

      char * port;
      char * host;

      if (xmlnode_get_type(cur) != NTYPE_TAG) continue;

      if ((port = xmlnode_get_attrib(cur,"port")) == NULL) continue;
   
      if ((host = xmlnode_get_data(cur)) == NULL) continue;

      ti->auth_hosts[ti->auth_hosts_count] = pstrdup(p,host);
      ti->auth_ports[ti->auth_hosts_count] = j_atoi(port,5190);
      log_debug(ZONE,"Host %s port %d at pos %d",
				ti->auth_hosts[ti->auth_hosts_count],
				ti->auth_ports[ti->auth_hosts_count],
				ti->auth_hosts_count);
      ti->auth_hosts_count++;

      if (ti->auth_hosts_count >= MAX_AUTH_HOSTS) break;
    }

    if (ti->auth_hosts_count == 0) {
      log_alert("err","No hosts to auth icq client !. Using default");
      ti->auth_hosts[ti->auth_hosts_count] = pstrdup(p,"205.188.179.233");
      ti->auth_ports[ti->auth_hosts_count] = 5190;
      ti->auth_hosts_count++;
    }

	/* add queue for unknown packets */
	ti->q = mtq_new(i->p);

    ti->sessions = wpxhash_new(j_atoi(xmlnode_get_tag_data(config,"prime"),509));
    ti->sessions_alt = wpxhash_new(j_atoi(xmlnode_get_tag_data(config,"prime"),509));
    SEM_INIT(ti->sessions_sem);
    ti->vcard = xmlnode_new_tag_pool(p,"vCard");

    xmlnode_put_attrib(ti->vcard,"xmlns",NS_VCARD);
    xmlnode_insert_node(ti->vcard,xmlnode_get_firstchild(xmlnode_get_tag(config,"vCard")));

    /* default 5 hours */
    ti->session_timeout = j_atoi(xmlnode_get_tag_data(config,"session_timeout"),18000);
	log_notice("config","session_timeout in sec : %d",ti->session_timeout);

    ti->reconnect = j_atoi(xmlnode_get_tag_data(config,"reconnects"),0);
    log_notice("config","Number of reconnects for session %d",ti->reconnect);

	check = j_atoi(xmlnode_get_tag_data(config,"session_check"),10);
    log_notice("config","JIT will check session every %d sec",check);
      
	//    ti->admin = xmlnode_dup(xmlnode_get_tag(config,"admin"));
    ti->start = time(NULL);

    /* Register callbacks */
    register_phandler(i,o_DELIVER,it_receive,(void *) ti);
    register_shutdown(it_shutdown,(void *) ti);

    /* Start up heartbeat thread */
    register_beat(check,it_sessions_check,(void *) ti);

    xmlnode_free(config);
}
示例#24
0
/** Callback processing incoming Jabber packets. */
result it_receive(instance i, dpacket d, void *arg) {
    iti ti = (iti) arg;
    jpacket jp;
    session s;
    session_ref alt_s;
    unsigned char *user;
    
    log_debug(ti->i->id,"Packet received: %s\n",xmlnode2str(d->x)); 

    switch(d->type) {
    case p_ROUTE: {
      /* ignore */
      return r_PASS;
    }
            
    case p_NONE:
    case p_NORM:
      jp = jpacket_new(d->x);
      break;

    default:
      return r_ERR;
    }

    if (!jp->from ||/* !jp->from->user ||*/ jp->type == JPACKET_UNKNOWN /* || jpacket_subtype(jp) == JPACKET__ERROR */)
    { /* ignore invalid packets */
        xmlnode_free(jp->x);
        return r_DONE;
    }

    /* JID user part should be case insensitive */
    /* convert user part of from JID to lower case */
    if(jp->from->user != NULL) 
	  for(user = jp->from->user; *user != '\0'; user++)
		if(*user < 128)
		  *user = tolower(*user);
	/* Mangle "from" JID, save original attribute for XDB conversion */
	xmlnode_put_attrib(jp->x, "origfrom", xmlnode_get_attrib(jp->x, "from"));
	xmlnode_put_attrib(jp->x, "from", jid_full(jp->from));

    SEM_LOCK(ti->sessions_sem);
    s = (session) wpxhash_get(ti->sessions,jid_full(jid_user(jp->from)));
    alt_s = (session_ref) wpxhash_get(ti->sessions_alt,jp->to->user);
    if (s != NULL) {
      if (s->exit_flag) {
    SEM_UNLOCK(ti->sessions_sem);
    log_alert("exit flag","message to exiting session");
    if (jp->type != JPACKET_PRESENCE){
      jutil_error(jp->x,TERROR_NOTFOUND);
      it_deliver(ti,jp->x);
    }
    else
      xmlnode_free(jp->x);
      } else if ((alt_s != NULL) && (
               (jp->type == JPACKET_MESSAGE)            // all messages
            || ((jp->type == JPACKET_IQ) && (j_strcmp(xmlnode_get_attrib(jp->iq,"xmlns"),NS_VCARD) == -1)) // all IQs except of vCard
            || (jp->type == JPACKET_PRESENCE) )) {      // all presences _targeted_to_specific_user_
        // rewriting "to" and "from" and putting packet back on the wire
        xmlnode_put_attrib(jp->x, "from", jid_full(it_uin2jid(jp->p,s->uin,jp->to->server)));
        xmlnode_put_attrib(jp->x, "to", jid_full(alt_s->s->orgid));
        SEM_UNLOCK(ti->sessions_sem);
        it_deliver(ti,jp->x);
      } else {
        jp->aux1 = (void *) s;
        mtq_send(s->q,jp->p,it_session_jpacket,(void *) jp);
        SEM_UNLOCK(ti->sessions_sem);
      }
    }
    else {
	  SEM_UNLOCK(ti->sessions_sem);

      if(jpacket_subtype(jp)!=JPACKET__ERROR)
    it_unknown(ti,jp);
      else
    xmlnode_free(jp->x);
    }
    return r_DONE;
}
/*
 ******************************************************************************
 * dps_rest_client_fill_evhttp --                                         *//**
 *
 * \brief This routine crate the HTTP Request from the JSON Body
 *
 * \param req: The EVHTTP_REQUEST
 * \param js_res: The JSON Body of the Request
 * \param remote_ip_string: The DPS IP Address to send the request to.
 *
 * \return PyObject
 *
 *****************************************************************************/
static void dps_rest_client_fill_evhttp(struct evhttp_request *req,
                                        json_t *js_res,
                                        char *remote_ip_string)
{
	char *res_body_str = NULL;
	struct evbuffer *retbuf = NULL;
	char host_header_str[64];

	log_debug(RESTHandlerLogLevel, "Enter");

	memset(host_header_str, 0, 64);
	do
	{
		if(js_res != NULL)
		{
			//add to the http request output buffer for sending
			res_body_str = json_dumps(js_res, JSON_PRESERVE_ORDER);
			if (NULL == res_body_str)
			{
				log_alert(RESTHandlerLogLevel, "JSON string is NULL or Bad");
				break;
			}
			retbuf = evbuffer_new();
			if (NULL == retbuf)
			{
				log_error(RESTHandlerLogLevel, "retbuf = evbuffer_new() ERROR");
				break;
			}
			//add to the http request output buffer for sending
			log_debug(RESTHandlerLogLevel,
			          "strlen(res_body_str) = %d, content is %s",
			          strlen((const char *)res_body_str), res_body_str);
			evbuffer_add(retbuf, res_body_str, strlen((const char *)res_body_str) + 1);
			evbuffer_add_buffer(evhttp_request_get_output_buffer(req), retbuf);
		}
		/* No need to add "content-length,
		 * as evhttp will add it for POST and PUT, and
		 * GET should not have it
		*/

		log_debug(RESTHandlerLogLevel,
		          "Remote DPS Node IP ==>> [%s : REST Port %d]",
		          remote_ip_string, DPS_REST_HTTPD_PORT);
		if (DPS_REST_HTTPD_PORT != HTTPD_DEFAULT_PORT)
		{
			sprintf(host_header_str,"%s:%d",
			        remote_ip_string,
			        DPS_REST_HTTPD_PORT);
		}
		else
		{
			sprintf(host_header_str,"%s",remote_ip_string);
		}
		log_debug(RESTHandlerLogLevel, "host_header_str %s", host_header_str);

		if(evhttp_find_header(req->output_headers, "Host") == NULL)
		{
			evhttp_add_header(evhttp_request_get_output_headers(req),
			                  "Host", host_header_str);
		}

		
		if(evhttp_find_header(req->output_headers, "Content-Type") == NULL)
		{
			evhttp_add_header(evhttp_request_get_output_headers(req), 
			"Content-Type", "application/json");
		}
	} while(0);

	if (res_body_str)
	{
		free(res_body_str);
	}

	log_debug(RESTHandlerLogLevel, "Exit");

	return;

}