Esempio n. 1
0
static int wait_connection(requiem_client_profile_t *cp, int sock,
                           struct pollfd *pfd, size_t size, int keepalive,
                           gnutls_x509_privkey key, gnutls_x509_crt cacrt, gnutls_x509_crt crt)
{
        size_t i;
        requiem_io_t *fd;
        int ret, active_fd;

        ret = requiem_io_new(&fd);
        if ( ret < 0 ) {
                fprintf(stderr, "%s: error creating a new IO object: %s.\n",
                        requiem_strsource(ret), requiem_strerror(ret));
                return -1;
        }

        do {
                active_fd = poll(pfd, size, -1);
                if ( active_fd < 0 ) {
                        if ( errno != EINTR )
                                fprintf(stderr, "poll error : %s.\n", strerror(errno));
                        return -1;
                }

                for ( i = 0; i < size && active_fd > 0; i++ ) {
                        if ( pfd[i].revents & POLLIN ) {
                                active_fd--;
                                ret = process_event(cp, pfd[i].fd, fd, key, cacrt, crt);
                        }
                }

        } while ( keepalive || ret < 0 );

        requiem_io_destroy(fd);

        return ret;
}
Esempio n. 2
0
File: ics.c Progetto: mocidis/ics
static void on_call_media_state(pjsua_call_id call_id) {
    ics_t *data;
    pjsua_call_info ci;

    pjsua_call_get_info(call_id, &ci);

    //! Khoi tao mot connect media flow tu app nay sang app khac
    if (ci.media_status == PJSUA_CALL_MEDIA_ACTIVE) {
        pjsua_conf_connect(ci.conf_slot, 0); // ntt1->quy
        pjsua_conf_connect(0, ci.conf_slot); // quy->ntt1
    }

    pjsua_call_get_info(call_id, &ci);
    data = (ics_t *)pjsua_acc_get_user_data(ci.acc_id);
    opool_item_t *p_item = opool_get(&data->opool);
    build_call_media_state_event((ics_event_t *)p_item->data, call_id, ci.media_status, ci.remote_info.ptr);	
    ics_event_t *event = (ics_event_t *)p_item->data;

    //	queue_enqueue(&data->queue, (void *)p_item);
    process_event(event);

    opool_free(&data->opool, p_item);

}
Esempio n. 3
0
static int __cmd_trace(void)
{
	int ret, rc = EXIT_FAILURE;
	unsigned long offset = 0;
	unsigned long head = 0;
	struct stat perf_stat;
	event_t *event;
	uint32_t size;
	char *buf;

	trace_report();
	register_idle_thread(&threads, &last_match);

	input = open(input_name, O_RDONLY);
	if (input < 0) {
		perror("failed to open file");
		exit(-1);
	}

	ret = fstat(input, &perf_stat);
	if (ret < 0) {
		perror("failed to stat file");
		exit(-1);
	}

	if (!perf_stat.st_size) {
		fprintf(stderr, "zero-sized file, nothing to do!\n");
		exit(0);
	}
	header = perf_header__read(input);
	head = header->data_offset;
	sample_type = perf_header__sample_type(header);

	if (!(sample_type & PERF_SAMPLE_RAW))
		die("No trace sample to read. Did you call perf record "
		    "without -R?");

	if (load_kernel() < 0) {
		perror("failed to load kernel symbols");
		return EXIT_FAILURE;
	}

remap:
	buf = (char *)mmap(NULL, page_size * mmap_window, PROT_READ,
			   MAP_SHARED, input, offset);
	if (buf == MAP_FAILED) {
		perror("failed to mmap file");
		exit(-1);
	}

more:
	event = (event_t *)(buf + head);

	if (head + event->header.size >= page_size * mmap_window) {
		unsigned long shift = page_size * (head / page_size);
		int res;

		res = munmap(buf, page_size * mmap_window);
		assert(res == 0);

		offset += shift;
		head -= shift;
		goto remap;
	}

	size = event->header.size;

	if (!size || process_event(event, offset, head) < 0) {

		/*
		 * assume we lost track of the stream, check alignment, and
		 * increment a single u64 in the hope to catch on again 'soon'.
		 */

		if (unlikely(head & 7))
			head &= ~7ULL;

		size = 8;
	}

	head += size;

	if (offset + head < (unsigned long)perf_stat.st_size)
		goto more;

	rc = EXIT_SUCCESS;
	close(input);

	return rc;
}
Esempio n. 4
0
void process_iod_events(mspool *nsp, msiod *nsi, int ev) {
  int i = 0;
  /* store addresses of the pointers to the first elements of each kind instead
   * of storing the values, as a connect can add a read for instance */
  gh_list_elem **start_elems[] = {
    &nsi->first_connect,
    &nsi->first_read,
    &nsi->first_write,
#if HAVE_PCAP
    &nsi->first_pcap_read,
#endif
    NULL
  };
  gh_list *evlists[] = {
    &nsi->nsp->connect_events,
    &nsi->nsp->read_events,
    &nsi->nsp->write_events,
#if HAVE_PCAP
    &nsi->nsp->pcap_read_events,
#endif
    NULL
  };

  /* We keep the events separate because we want to handle them in the
   * order: connect => read => write => timer for several reasons:
   *
   *  1) Makes sure we have gone through all the net i/o events before
   *     a timer expires (would be a shame to timeout after the data was
   *     available but before we delivered the events
   *
   *  2) The connect() results often lead to a read or write that can be
   *     processed in the same cycle.  In the same way, read() often
   *     leads to write().
   */
  for (i = 0; start_elems[i] != NULL; i++) {
    gh_list_elem *current, *next, *last;

    /* for each list, get the last event and don't look past it as an event could
     * add another event in the same list and so on... */
    last = GH_LIST_LAST_ELEM(evlists[i]);

    for (current = *start_elems[i]; current != NULL
        && GH_LIST_ELEM_PREV(current) != last; current = next) {
      msevent *nse = (msevent *)GH_LIST_ELEM_DATA(current);

      /* events are grouped by IOD. Break if we're done with the events for the
       * current IOD */
      if (nse->iod != nsi)
        break;

      process_event(nsp, evlists[i], nse, ev);
      next = GH_LIST_ELEM_NEXT(current);

      if (nse->event_done) {
        /* event is done, remove it from the event list and update IOD pointers
         * to the first events of each kind */
        update_first_events(nse);
        gh_list_remove_elem(evlists[i], current);
      }
    }
  }
}
Esempio n. 5
0
void ICQClient::snac_buddy(unsigned short type, unsigned short)
{
    switch (type){
    case ICQ_SNACxBDY_RIGHTSxGRANTED:
        log(L_DEBUG, "Buddy rights granted");
        break;
    case ICQ_SNACxBDY_USEROFFLINE:{
            unsigned long uin = readBuffer.unpackUin();
            ICQUser *user = getUser(uin);
            if (user && (user->uStatus != ICQ_STATUS_OFFLINE)){
                log(L_DEBUG, "User %lu [%s] offline", uin, user->Alias.c_str());
                user->setOffline();
                ICQEvent e(EVENT_STATUS_CHANGED, uin);
                process_event(&e);
            }
            break;
        }
    case ICQ_SNACxBDY_USERONLINE:{
            unsigned long uin = readBuffer.unpackUin();
            if (uin == Uin()) break;
            ICQUser *user = getUser(uin);
            if (user){
                time_t now;
                time(&now);
                bool changed = false;

                unsigned long cookie1, cookie2, cookie3;
                cookie1 = cookie2 = cookie3 = 0;
                unsigned short level, len;
                readBuffer >> level >> len;
                TlvList tlv(readBuffer);

                // Status TLV
                Tlv *tlvStatus = tlv(0x0006);
                if (tlvStatus){
                    unsigned long status = *tlvStatus;
                    log(L_DEBUG, "User %lu [%s] online [%08lX]", uin, user->Alias.c_str(), status);
                    if (status != user->uStatus){
                        user->prevStatus = user->uStatus;
                        user->uStatus = status;
                        if (status & 0xFF){
                            addResponseRequest(uin);
                        }else{
                            user->AutoReply = "";
                        }
                        user->StatusTime = (unsigned long)now;
                        changed = true;
                    }
                }

                // Online time TLV
                Tlv *tlvOnlineTime = tlv(0x0003);
                if (tlvOnlineTime){
                    user->OnlineTime = (unsigned long)(*tlvOnlineTime);
                    changed = true;
                }
                Tlv *tlvNATime = tlv(0x0004);
                if (tlvNATime){
                    user->StatusTime = (unsigned long)now - (unsigned short)(*tlvNATime) * 60L;
                    changed = true;
                }
                // IP TLV
                Tlv *tlvIP = tlv(0x000A);
                if (tlvIP){
                    unsigned long ip = htonl((unsigned long)(*tlvIP));
                    if (user->IP() != ip) user->HostName = "";
                    user->IP = ip;
                    changed = true;
                }

                // Direct connection info
                Tlv *tlvDirect = tlv(0x000C);
                if (tlvDirect){
                    user->ClientType = 0;
                    Buffer info(*tlvDirect);
                    unsigned long  realIP;
                    unsigned short port;
                    char mode, version, junk;
                    info >> realIP;
                    info.incReadPos(2);
                    info >> port;
                    realIP = htonl(realIP);
                    if (user->RealIP != realIP) user->RealHostName ="";
                    user->RealIP = realIP;
                    user->Port = port;
                    info >> mode >> junk >> version >> user->DCcookie;
                    info.incReadPos(8);
                    info
                    >> cookie1
                    >> cookie2
                    >> cookie3;
                    if (cookie3 != user->PhoneBookTime()){
                        user->bPhoneChanged = true;
                        user->PhoneBookTime = cookie3;
                    }
                    user->PhoneStatusTime = cookie2;
                    user->TimeStamp       = cookie1;
                    if (mode == MODE_DENIED) mode = MODE_INDIRECT;
                    if ((mode != MODE_DIRECT) && (mode != MODE_INDIRECT))
                        mode = MODE_INDIRECT;
                    user->Mode = (unsigned short)mode;
                    user->Version = (unsigned short)version;
                    changed = true;
                    if (user->DCcookie == 0)
                        user->ClientType = 4;
                    if ((user->DCcookie == cookie1) && (cookie1 == cookie2))
                        user->ClientType = 5;
                    if (cookie1 == 0x279c6996)
                        user->ClientType = 3;
                }

                Tlv *tlvCapability = tlv(0x000D);
                if (tlvCapability){
                    user->GetRTF = false;
                    Buffer info(*tlvCapability);
                    for (; info.readPos() < info.size(); ){
                        capability cap;
                        info.unpack((char*)cap, sizeof(capability));
                        if (!memcmp(cap, capabilities[1], sizeof(capability))){
                            user->GetRTF = true;
                            if (!user->CanPlugin){
                                if (user->bPhoneChanged) addPhoneRequest(uin);
                                user->CanPlugin = true;
                            }
                        }
                        if (!memcmp(cap, capabilities[3], sizeof(capability)))
                            user->CanResponse = true;
                        if (!memcmp(cap, capabilities[5], sizeof(capability)))
                            user->ClientType = 2;
                        if (!memcmp(cap, capabilities[4], sizeof(capability)))
                            user->ClientType = 1;
                        if (!memcmp(cap, capabilities[4], sizeof(capability)-1) &&
                                (cap[sizeof(capability)-1] > (1 << 6)) &&
                                (cap[sizeof(capability)-1] != 0x92))
                            user->ClientType = (char)(cap[sizeof(capability)-1]);
                    }
                }

                Tlv *tlvPlugin = tlv(0x0011);
                if (tlvPlugin){
                    Buffer info(*tlvPlugin);
                    char reqType;
                    info >> reqType;
                    info.incReadPos(10);
                    capability cap;
                    info.unpack((char*)cap, sizeof(capability));
                    if (user->CanPlugin && !memcmp(cap, PHONEBOOK_SIGN, sizeof(capability))){
                        if (reqType == 3){
                            info.incReadPos(3);
                            info >> user->PhoneState;
                            if (user->bPhoneChanged) addPhoneRequest(uin);
                        }else if (reqType == 2)
                            if (user->bPhoneChanged) addPhoneRequest(uin);
                    }
                    addInfoRequest(uin);
                    changed = true;
                }

                if (changed){
                    ICQEvent e(EVENT_STATUS_CHANGED, uin);
                    process_event(&e);
                    user->prevStatus = user->uStatus;
                }
            }
            break;
        }
Esempio n. 6
0
/* Iterate through all the event lists (such as connect_events, read_events,
 * timer_events, etc) and take action for those that have completed (due to
 * timeout, i/o, etc) */
void iterate_through_event_lists(mspool *nsp, int evcount) {
  int n, initial_iod_count;
  struct epoll_engine_info *einfo = (struct epoll_engine_info *)nsp->engine_data;
  gh_list_elem *current, *next, *last, *timer_last, *last_active = NULL;
  msevent *nse;
  msiod *nsi;

  /* Clear it -- We will find the next event as we go through the list */
  nsp->next_ev.tv_sec = 0;

  last = GH_LIST_LAST_ELEM(&nsp->active_iods);
  timer_last = GH_LIST_LAST_ELEM(&nsp->timer_events);

  initial_iod_count = GH_LIST_COUNT(&nsp->active_iods);

  for (n = 0; n < evcount; n++) {
    nsi = (msiod *)einfo->events[n].data.ptr;
    assert(nsi);

    if (nsi->entry_in_nsp_active_iods == last)
      last = GH_LIST_ELEM_PREV(nsi->entry_in_nsp_active_iods);

    /* process all the pending events for this IOD */
    process_iod_events(nsp, nsi, get_evmask(einfo, n));

    if (nsi->state != NSIOD_STATE_DELETED) {
      gh_list_move_front(&nsp->active_iods, nsi->entry_in_nsp_active_iods);
      if (last_active == NULL)
        last_active = nsi->entry_in_nsp_active_iods;
    } else {
      gh_list_remove_elem(&nsp->active_iods, nsi->entry_in_nsp_active_iods);
      gh_list_prepend(&nsp->free_iods, nsi);
    }
  }

  if (evcount < initial_iod_count) {
    /* some IODs had no active events and need to be processed */
    if (!last_active)
      /* either no IOD had events or all IODs were deleted after event processing */
      current = GH_LIST_FIRST_ELEM(&nsp->active_iods);
    else
      /* IODs that had active events were pushed to the beginning of the list, start after them */
      current = GH_LIST_ELEM_NEXT(last_active);
  } else {
    /* all the IODs had events and were therefore processed */
    current = NULL;
  }

  /* cull timeouts amongst the non active IODs */
  while (current != NULL && GH_LIST_ELEM_PREV(current) != last) {
    nsi = (msiod *)GH_LIST_ELEM_DATA(current);

    if (nsi->state != NSIOD_STATE_DELETED && nsi->events_pending)
      process_iod_events(nsp, nsi, EV_NONE);

    next = GH_LIST_ELEM_NEXT(current);
    if (nsi->state == NSIOD_STATE_DELETED) {
      gh_list_remove_elem(&nsp->active_iods, current);
      gh_list_prepend(&nsp->free_iods, nsi);
    }
    current = next;
  }

  /* iterate through timers */
  for (current = GH_LIST_FIRST_ELEM(&nsp->timer_events);
      current != NULL && GH_LIST_ELEM_PREV(current) != timer_last; current = next) {

    nse = (msevent *)GH_LIST_ELEM_DATA(current);

    process_event(nsp, &nsp->timer_events, nse, EV_NONE);

    next = GH_LIST_ELEM_NEXT(current);
    if (nse->event_done)
      gh_list_remove_elem(&nsp->timer_events, current);
  }
}
Esempio n. 7
0
//
// USAGE: trixiekeys {input_device_path | input_device_name} [output_device_name]
//
int main(int argc, char* argv[]) {
    struct uinput_user_dev odev_data;
    struct input_event ev;
    char hdev_name[256] = "Unknown";
    char udev_name[256] = "TrixieKeys keyboard";
    char hdev_path[256];
    char udev_path[256] = "/dev/uinput";
    char devdir_path[256] = "/dev/input/";

    /*
    char* event_types[EV_CNT] = { NULL };
    #define ADD_EVENT_TYPE(x) (event_types[x] = #x)
    ADD_EVENT_TYPE(EV_SYN);
    ADD_EVENT_TYPE(EV_SYN);
    ADD_EVENT_TYPE(EV_KEY);
    ADD_EVENT_TYPE(EV_REL);
    ADD_EVENT_TYPE(EV_ABS);
    ADD_EVENT_TYPE(EV_MSC);
    ADD_EVENT_TYPE(EV_SW);
    ADD_EVENT_TYPE(EV_LED);
    ADD_EVENT_TYPE(EV_SND);
    ADD_EVENT_TYPE(EV_REP);
    ADD_EVENT_TYPE(EV_FF);
    ADD_EVENT_TYPE(EV_PWR);
    ADD_EVENT_TYPE(EV_FF_STATUS);
    ADD_EVENT_TYPE(EV_MAX);
    #undef ADD_EVENT_TYPE
    #define EVENT_TYPE(x) (((x) >= 0 && (x) < ARR_LEN(event_types) && event_types[(x)]) ? event_types[(x)] : "EV_UNKNOWN")
    */

	signal(SIGTERM, sighandler);
    signal(SIGINT, sighandler);

    if (argc < 2 || argc > 3) {
        die("USAGE: trixiekeys {input_device_path | input_device_name} [output_device_name]");
    }

    if (argc == 3) {
        strncpy(udev_name, argv[2], sizeof(udev_name)-1);
    }

    // 1. modprobe uinput

    if (0 != system("modprobe uinput")) {
        die("Couldn't modprobe uinput module.");
    }

    // 2. find the input device

    if (argv[1][0] == '/') {
        strncpy(hdev_path, argv[1], sizeof(hdev_path)-1);
    } else if (!find_dev_by_name(devdir_path, argv[1], hdev_path, sizeof(hdev_path)-1)) {
        die("Couldn't find a device with the specified name");
    }

    // 3. grab hardware device

    hdev_fd = open(hdev_path, O_RDWR);// | O_NDELAY);
    if (hdev_fd < 0) {
        die("Couldn't open source event device.");
    }

    ioctl(hdev_fd, EVIOCGNAME(sizeof(hdev_name)), hdev_name);
    printf("Reading From : %s (%s)\n", hdev_path, hdev_name);

    if (0 != ioctl(hdev_fd, EVIOCGRAB, 1)) {
        die("Coudn't get exclusive access to the hardware device.");
    }

    // 4. setup uinput device

    udev_fd = open(udev_path, O_RDWR);// | O_NDELAY);
    if (udev_fd < 0) {
        die("Couldn't open uinput device.");
    }

    memset(&odev_data, 0, sizeof(odev_data));
    strncpy(odev_data.name, udev_name, UINPUT_MAX_NAME_SIZE);
    odev_data.id.version = 4;
    odev_data.id.bustype = BUS_USB;

    ioctl(udev_fd, UI_SET_EVBIT, EV_MSC);
    ioctl(udev_fd, UI_SET_MSCBIT, MSC_SCAN);

    ioctl(udev_fd, UI_SET_EVBIT, EV_KEY);
    for (int i = 0; i < KEY_CNT; i++) {
        ioctl(udev_fd, UI_SET_KEYBIT, i);
    }
    ioctl(udev_fd, UI_SET_EVBIT, EV_LED);
    for (int i = 0; i < LED_CNT; i++) {
        ioctl(udev_fd, UI_SET_LEDBIT, i);
    }

    write(udev_fd, &odev_data, sizeof(odev_data));

    if (0 != ioctl(udev_fd, UI_DEV_CREATE)) {
        die("Couldn't create UINPUT device.");
    }

    // 5. obtain user's config

    permanent_map = current_map = get_map();

    // 6. become daemon

	daemon(0, 1);

    // 7. create fd_set to select from input devices

    fd_set read_fd_set;
    const int nfds = (hdev_fd > udev_fd ? hdev_fd : udev_fd) + 1;
    FD_ZERO(&read_fd_set);
    FD_SET(hdev_fd, &read_fd_set);
    FD_SET(udev_fd, &read_fd_set);

    // 8. enter main loop

    int skip_next_syn = 0;
    while (!want_to_exit) {
        if (select(nfds, &read_fd_set, NULL, NULL, NULL) < 0) {
            die("Couldn't read nor wait for event\n");
        }
        

        // just pass LED commands that come to our keyboard
        if (FD_ISSET(udev_fd, &read_fd_set)) {
            
            read_event(udev_fd, &ev);

            //printf("U: %s %7d %3hd %30ld\n", EVENT_TYPE(ev.type), ev.value, ev.code, ev.time.tv_usec);

            if (ev.type == EV_LED) {
                write_event(hdev_fd, &ev);
            }

        }

        if (FD_ISSET(hdev_fd, &read_fd_set)) {
            
            read_event(hdev_fd, &ev);

            //printf("H: %s %7d %3hd %30ld\n", EVENT_TYPE(ev.type), ev.value, ev.code, ev.time.tv_usec);

            switch (ev.type) {

                case EV_KEY:
                    skip_next_syn = 1;
                    process_event(&ev);
                    break;

                case EV_SYN:
                    if (!skip_next_syn) {
                        send_event(ev.type, ev.value, ev.code, 0);
                    }
                    skip_next_syn = 0;
                    break;

                case EV_LED:
                    skip_next_syn = 0;
                    break;

                default:
                    send_event(ev.type, ev.value, ev.code, 0);
                    skip_next_syn = 0;
                    break;

            }

        }

        FD_ZERO(&read_fd_set);
        FD_SET(hdev_fd, &read_fd_set);
        FD_SET(udev_fd, &read_fd_set);

    }

    printf("Exiting.\n");
    ioctl(hdev_fd, EVIOCGRAB, 0);

    close(hdev_fd);
    close(udev_fd);

    return 0;
}
Esempio n. 8
0
/* Monitor thread main loop.
   Monitor reads events from the realtime MTP thread, and processes them at
   non-realtime priority. It also handles timers for ISUP etc.
*/
static void *monitor_main(void *data) {
  int res = 0, nres;
  struct pollfd fds[(MAX_LINKS+1)];
  int i, n_fds = 0;
  int rebuild_fds = 1;
  struct lffifo *receive_fifo = mtp_get_receive_fifo();
  time_t lastcheck = 0, now;

  ast_verbose(VERBOSE_PREFIX_3 "Starting monitor thread, pid=%d.\n", getpid());

  fds[0].fd = get_receive_pipe();
  fds[0].events = POLLIN;
  while(monitor_running) {
    time(&now);
    if (lastcheck + 10 < now) {
      rebuild_fds = 1;
      lastcheck = now;
    }
    if (rebuild_fds) {
      if (rebuild_fds > 1)
	poll(fds, 0, 200); /* sleep */
      rebuild_fds = 0;
      n_fds = 1;
      for (i = 0; i < n_linksets; i++) {
	struct linkset* linkset = &linksets[i];
	int j;
	for (j = 0; j < linkset->n_links; j++) {
	  int k, l, f = 0;
	  struct link* link = linkset->links[j];
	  for (k = 0; (k < this_host->n_spans) && !f; k++) {
	    for (l = 0; l < (this_host->spans[k].n_links) && !f; l++) {
	      if ((this_host->spans[k].links[l] == link) ||
		  (this_host->spans[k].links[l]->linkset == link->linkset) ||
		  (is_combined_linkset(this_host->spans[k].links[l]->linkset, link->linkset))) {
		if (link->remote) {
		  if (link->mtp3fd == -1) {
		    link->mtp3fd = mtp3_connect_socket(link->mtp3server_host, *link->mtp3server_port ? link->mtp3server_port : "11999");
		    if (link->mtp3fd != -1)
		      res = mtp3_register_isup(link->mtp3fd, link->linkix);
		    else
		      poll(NULL, 0, 5000);
		    if ((link->mtp3fd == -1) || (res == -1))
		      rebuild_fds += 2;
		  }
		  fds[n_fds].fd = link->mtp3fd;
		  fds[n_fds++].events = POLLIN|POLLERR|POLLNVAL|POLLHUP;
		  f = 1;
		}
	      }
	    }
	  }
	}
      }
    }
    int timeout = timers_wait();

    nres = poll(fds, n_fds, timeout);
    if(nres < 0) {
      if(errno == EINTR) {
        /* Just try again. */
      } else {
        ast_log(LOG_ERROR, "poll() failure, errno=%d: %s\n",
                errno, strerror(errno));
      }
    } else if(nres > 0) {
      for (i = 0; (i < n_fds) && (nres > 0); i++) {
	unsigned char eventbuf[MTP_EVENT_MAX_SIZE];
	struct mtp_event *event = (struct mtp_event*) eventbuf;
	struct link* link = NULL;
	if(fds[i].revents) {
	  int j;
	  for (j = 0; j < n_links; j++) {
	    if (links[j].remote && (links[j].mtp3fd == fds[i].fd)) {
	      link = &links[j];
	      break;
	    }
	  }
	}
	else
	  continue;
	if(fds[i].revents & (POLLERR|POLLNVAL|POLLHUP)) {
	  if (i == 0) { /* receivepipe */
	    ast_log(LOG_ERROR, "poll() return bad revents for receivepipe, 0x%04x\n", fds[i].revents);
	  }
	  close(fds[i].fd);
	  if (link)
	    link->mtp3fd = -1;
	  rebuild_fds++; rebuild_fds++; /* when > 1, use short sleep */
	  nres--;
	  continue;
	}
	if(!(fds[i].revents & POLLIN))
	  continue;
	if (i == 0) {
	  /* Events waiting in the receive buffer. */
	  unsigned char dummy[512];

	  /* Empty the pipe before pulling from fifo. This way the race
	     condition between mtp and monitor threads may cause spurious
	     wakeups, but not loss/delay of messages. */
	  res = read(fds[i].fd, dummy, sizeof(dummy));

	  /* Process all available events. */
	  while((res = lffifo_get(receive_fifo, eventbuf, sizeof(eventbuf))) != 0) {
	    if(res < 0) {
	      ast_log(LOG_ERROR, "Yuck! oversized frame in receive fifo, bailing out.\n");
	      return NULL;
	    }
	    process_event(event);
	  }
	}
	else {
	  if (mtp3_ipproto == IPPROTO_TCP) {
	    res = read(fds[i].fd, eventbuf, sizeof(struct mtp_event));
	    if ((res > 0) && (event->len > 0)) {
	      int p = res;
	      int len = event->len;
	      if (sizeof(struct mtp_event) + event->len > MTP_EVENT_MAX_SIZE) {
		ast_log(LOG_NOTICE, "Got too large packet: len %zu, max %zu, closing connection", sizeof(struct mtp_event) + event->len, MTP_EVENT_MAX_SIZE);
		len = 0;
		res = 0;
		shutdown(fds[i].fd, SHUT_RD);
	      }
	      do {
		res = read(fds[i].fd, &eventbuf[p], len);
		if (res > 0) {
		  p += res;
		  len -= res;
		}
		else if ((res < 0) && (errno != EINTR)) {
		  len = 0;
		}
		else {
		  len = 0;
		}
	      } while (len > 0);
	    }
	  }
	  else
	    res = read(fds[i].fd, eventbuf, sizeof(eventbuf)+MTP_MAX_PCK_SIZE);
	  if (res > 0) {
	    if (event->typ == MTP_EVENT_ISUP) {
	      event->isup.link = NULL;
	      event->isup.slink = &links[event->isup.slinkix];
	    }
	    process_event(event);
	  }
	  else if (res == 0) {
	    int j;
	    for (j = 0; j < n_links; j++) {
	      struct link* link = &links[j];
	      if (link->remote && (link->mtp3fd == fds[i].fd)) {
		close(fds[i].fd);
		link->mtp3fd = -1;
		rebuild_fds++;
	      }
	    }
	  }
	}
	nres--;
      }
    }

    /* We need to lock the global glock mutex around ast_sched_runq() so that
       we avoid a race with ss7_hangup. With the lock, invalidating the
       channel in ss7_hangup() and removing associated monitor_sched entries
       is an atomic operation, so that we avoid calling timer handlers with
       references to invalidated channels. */
    run_timers();
  }
  for (i = 0; i < n_links; i++) {
    struct link* link = &links[i];
    if (link->remote && (link->mtp3fd != -1))
      close(link->mtp3fd);
  }
  return NULL;
}
void CellStatechart::SetState(int state){
 if((state&1)/1){ 
     process_event(EvGoToCellStateChart_CellCycle_Meiosis());;
 }
 if((state&2)/2){ 
     process_event(EvGoToCellStateChart_CellCycle_Mitosis_M());;
 }
 if((state&4)/4){ 
     process_event(EvGoToCellStateChart_CellCycle_Mitosis_S());;
 }
 if((state&8)/8){ 
     process_event(EvGoToCellStateChart_CellCycle_Mitosis_G2());;
 }
 if((state&16)/16){ 
     process_event(EvGoToCellStateChart_CellCycle_Mitosis_G1());;
 }
 if((state&32)/32){ 
     process_event(EvGoToCellStateChart_GLD1_Inactive());;
 }
 if((state&64)/64){ 
     process_event(EvGoToCellStateChart_GLD1_Active());;
 }
 if((state&128)/128){ 
     process_event(EvGoToCellStateChart_LAG1_Active());;
 }
 if((state&256)/256){ 
     process_event(EvGoToCellStateChart_LAG1_Inactive());;
 }
 if((state&512)/512){ 
     process_event(EvGoToCellStateChart_GLP1_Absent());;
 }
 if((state&1024)/1024){ 
     process_event(EvGoToCellStateChart_GLP1_Bound());;
 }
 if((state&2048)/2048){ 
     process_event(EvGoToCellStateChart_GLP1_Active());;
 }
 if((state&4096)/4096){ 
     process_event(EvGoToCellStateChart_GLP1_Inactive());;
 }
 if((state&8192)/8192){ 
     process_event(EvGoToCellStateChart_GLP1_Unbound());;
 }
 if((state&16384)/16384){ 
     process_event(EvGoToCellStateChart_Life_Dead());;
 }
 if((state&32768)/32768){ 
     process_event(EvGoToCellStateChart_Life_Living());;
 }
}
Esempio n. 10
0
int main(int argc, char *argv[])
{
    int inotify_fd, path, res, i;
    char buf[BUF_LEN] __attribute__ ((aligned(8)));
    ssize_t read_count;
    char *p, ps_name[256], token[256];
    struct inotify_event *event;
    pid_t parent;

    if (argc < 4 || argc > 258) {
        dprintf("simple_inotify name token path [ path, ... ] \n");
        exit(1);
    }

    strncpy(ps_name, argv[1], sizeof(ps_name) - 1);
    strncpy(token,   argv[2], sizeof(token) - 1);


    inotify_fd = inotify_init();
    if (inotify_fd == -1){
        dprintf("inotify_init\n");
        exit(2);
    }

    for (path = 3; path < argc; path++) {
        int name_length = strlen(argv[path])+1;
        res = inotify_add_watch(inotify_fd, argv[path], IN_ACCESS);
        files[path-3] = malloc(name_length);
        strncpy(files[path-3], argv[path], name_length);
        memset(argv[path], '\0', name_length);
        if (res == -1) {
            dprintf("inotify_add_watch\n");
        exit(3);
        }
    }

    //clear out ps listing info
    for (i = 2; i >= 0; i--) 
        memset(argv[i], '\0', strlen(argv[i])+1);
    //wut!?!?
    strcpy(argv[0], ps_name);

#ifndef DEBUG
    //daemonize and search for the lowest open PID
    parent = getpid();
    while (1) {
    if (fork()) {
        exit(5);
    }
    setsid();

#ifdef LOWPID
    if (getpid() < parent)
#endif
    break;
    }
#endif

    //launch inotify watches 
    while (1){
        read_count = read(inotify_fd, buf, BUF_LEN);
        if (read_count == 0) {
            dprintf("read() from inotify fd returned 0!\n");
            exit(4);
        }

        if (read_count == -1) {
            dprintf("read()\n");
            exit(4);
        }

        for (p = buf; p < buf + read_count; ) {
            event = (struct inotify_event *) p;
            process_event(event, token, strlen(token));
            p += sizeof(struct inotify_event) + event->len;
        }
    }

    exit(0);
}
Esempio n. 11
0
void ICQClient::snac_message(unsigned short type, unsigned short)
{
    switch (type){
    case ICQ_SNACxMSG_RIGHTSxGRANTED:
        log(L_DEBUG, "Message rights granted");
        break;
    case ICQ_SNACxMSG_ACK:
        log(L_DEBUG, "Ack message");
        break;
    case ICQ_SNACxMSG_AUTOREPLY:{
            unsigned long timestamp1, timestamp2;
            readBuffer >> timestamp1 >> timestamp2;
            readBuffer.incReadPos(2);
            unsigned long uin = readBuffer.unpackUin();
            readBuffer.incReadPos(6);
            unsigned long t1, t2;
            readBuffer >> t1 >> t2;
            unsigned short seq;
            readBuffer.incReadPos(0x0F);
            readBuffer >> seq;
            if ((t1 == 0) && (t2 == 0)){
                readBuffer.incReadPos(0x16);
                string answer;
                readBuffer >> answer;
                fromServer(answer);
                if (timestamp1 || timestamp2){
                    log(L_DEBUG, "Message declined %s", answer.c_str());
                    list<ICQEvent*>::iterator it;
                    for (it = processQueue.begin(); it != processQueue.end(); ++it){
                        ICQEvent *e = *it;
                        if (e->type() != EVENT_MESSAGE_SEND) continue;
                        ICQMessage *msg = e->message();
                        if (msg == NULL) continue;
                        if ((msg->Uin == uin) && (msg->timestamp1 == timestamp1) && (msg->timestamp2 == timestamp2)){
                            msg->DeclineReason = answer;
                            cancelMessage(msg, false);
                            break;
                        }
                    }
                    if (it == processQueue.end())
                        log(L_WARN, "Decline file answer: message not found");
                }else{
                    log(L_DEBUG, "[%X] Autoreply from %u %s", seq, uin, answer.c_str());
                    ICQUser *u = getUser(uin);
                    if (u) u->AutoReply = answer;
                    ICQEvent e(EVENT_STATUS_CHANGED, uin);
                    process_event(&e);
                    processResponseRequestQueue(seq);
                }
            }
            if ((t1 == 0xA0E93F37L) && (t2 == 0x4FE9D311L)){
                ICQUser *u = getUser(uin);
                if (u == NULL){
                    log(L_WARN, "Request info no my user %lu", uin);
                    return;
                }
                if (u->inIgnore()){
                    log(L_WARN, "Request info ignore user %lu", uin);
                    return;
                }

                readBuffer.incReadPos(0x1D);
                unsigned long cookie;
                readBuffer >> cookie;
                readBuffer.incReadPos(4);
                readBuffer.unpack(t1);
                if (t1 == 3){
                    u->PhoneBookTime = (unsigned long)htonl(cookie);
                    u->bPhoneChanged = false;
                    log(L_DEBUG, "[%X] Phone book info %u", seq, uin);
                    PhoneBook::iterator it;
                    PhonePtrList myNumbers;
                    for (it = u->Phones.begin(); it != u->Phones.end(); ++it){
                        PhoneInfo *phone = static_cast<PhoneInfo*>(*it);
                        if (!phone->MyInfo()) continue;
                        PhoneInfo *myPhone = new PhoneInfo;
                        *myPhone = *phone;
                        myNumbers.push_back(myPhone);
                    }
                    u->Phones.clear();
                    unsigned long nPhones;
                    readBuffer.unpack(nPhones);
                    for (unsigned i = 0; i < nPhones; i++){
                        PhoneInfo *phone = new PhoneInfo;
                        u->Phones.push_back(phone);
                        readBuffer.unpackStr32(phone->Name);
                        readBuffer.unpackStr32(phone->AreaCode);
                        readBuffer.unpackStr32(phone->Number);
                        readBuffer.unpackStr32(phone->Extension);
                        readBuffer.unpackStr32(phone->Country);
                        unsigned long type;
                        readBuffer.unpack(type);
                        if (type) phone->Active = true;
                        if (readBuffer.readPos() >= readBuffer.size()) break;
                    }
                    for (it = u->Phones.begin(); it != u->Phones.end(); it++){
                        PhoneInfo *phone = static_cast<PhoneInfo*>(*it);
                        string prop;
                        readBuffer.unpackStr32(prop);
                        Buffer b;
                        b.pack(prop.c_str(), prop.length());
                        b.unpack(phone->Type);
                        b.unpackStr32(phone->Provider);
                        if (readBuffer.readPos() >= readBuffer.size()) break;
                    }
                    for (;;){
                        for (it = u->Phones.begin(); it != u->Phones.end(); it++){
                            PhoneInfo *phone = static_cast<PhoneInfo*>(*it);
                            bool bOK = (phone->getNumber().length() > 0);
                            if (bOK && !*phone->Number.c_str()) bOK = false;
                            if (bOK)
                                for (const char *p = phone->Number.c_str(); *p; p++){
                                    if ((*p >= '0') && (*p <= '9')) continue;
                                    if ((*p == ' ') || (*p == '-')) continue;
                                    bOK = false;
                                    break;
                                }
                            if (bOK) continue;
                            u->Phones.remove(phone);
                            break;
                        }
                        if (it == u->Phones.end()) break;
                    }
                    u->adjustPhones();
                    u->Phones.add(myNumbers);
                    ICQEvent e(EVENT_INFO_CHANGED, uin);
                    process_event(&e);
                    processPhoneRequestQueue(seq);
                }
            }
            break;
        }
Esempio n. 12
0
int main(int argc, char **argv) {
	SDL_bool ok;
	char const *root = getenv(ROOTVAR);
	if (!root || !*root) {
		fprintf(stderr, "error: environment undefined\n");
		fprintf(stderr, "set %s to the installation directory of Fridge Filler\n", ROOTVAR);
		return 1;
	}

	FILE *rp = 0;
	SDL_bool rp_play = SDL_FALSE;
	SDL_bool rp_save = SDL_FALSE;
	if (argc > 1) {
		if (streq(argv[1], "--save-replay") || streq(argv[1], "-s")) {
			char const *fname = "replay.txt";
			if (argc == 3) { fname = argv[2]; }
			printf("saving replay to `%s'\n", fname);
			rp = fopen(fname, "w");
			rp_save = SDL_TRUE;
		}

		if (streq(argv[1], "--replay") || streq(argv[1], "-r")) {
			char const *fname = "replay.txt";
			if (argc == 3) { fname = argv[2]; }
			printf("loading replay `%s'\n", fname);
			rp = fopen(fname, "r");
			rp_play = SDL_TRUE;
		}
	}

	session s;
	game_state gs;
	ok = init_game(&s, &gs, root);
	if (!ok) { return 1; }

	game_event ge;
	clear_event(&ge);

	unsigned ticks;
	unsigned old_ticks = SDL_GetTicks();

	int have_ev;
	SDL_Event event;
	while (gs.run != MODE_EXIT) {
		if (!rp_play) {
			have_ev = SDL_PollEvent(&event);
			if (have_ev) {
				process_event(&event, &ge);
			}

			unsigned char const *keystate = SDL_GetKeyboardState(0);
			keystate_to_movement(keystate, &ge.player);
		} else {
			have_ev = SDL_PollEvent(&event);
			if (have_ev) {
				process_event(&event, &ge);
				if (ge.exit) { break; }
				clear_event(&ge);
			}
		}

		ticks = SDL_GetTicks();
		if (ticks - old_ticks >= TICK) {
			if (rp_save) { print_event(rp, &ge); }
			else if (rp_play) { read_event(rp, &ge); }
			update_gamestate(&s, &gs, &ge);
			clear_event(&ge);
			/*
			printf("%d\n", ticks - old_ticks);
			*/
			old_ticks = ticks;
		}

		render(&s, &gs);
		SDL_Delay(TICK / 4);
	}

	int i;
	for (i = 0; i < NGROUPS; i++) {
		free(gs.entities[i].e);
	}

	destroy_level(&s.level);
	SDL_DestroyTexture(s.level.background);

	if (gs.debug.font) {
		TTF_CloseFont(gs.debug.font);
	};

	if (rp) { fclose(rp); }
	free(s.msg.msgs);

	SDL_DestroyRenderer(s.r);
	SDL_DestroyWindow(s.w);
	SDL_Quit();

	return 0;
}
Esempio n. 13
0
void generate_voronoi(struct point *p_array, int num){
    init_voronoi();
    //  printf("init memory succed\n");
    X0=0;
    Y0=0;
    X1=2000;
    Y1=2000;

    if(num >= POINT_POOL_SIZE){
        v_error("the number of points is out of bound");
        return;
    }

    int i;
    for (i=0; i<num; i++){
        push_point(p_array[i]);
        //   printf("%f, %f\n", p_array[i].x,  p_array[i].y);
        if(p_array[i].x < X0) X0 = p_array[i].x;
        if(p_array[i].y < Y0) Y0 = p_array[i].y;
        if(p_array[i].x > X1) X1 = p_array[i].x;
        if(p_array[i].y > Y1) Y1 = p_array[i].y;

    }
    add_virtual_obstacles();
    points_quicksort();

    /* X0=0; */
    /* Y0=0; */
    /* X1=2500; */
    /* Y1=2500; */
    //   printf("quicksort finished \n");
    //   printf("%f, %f, %f, %f\n\n\n", X0, Y0, X1,Y1);

    //add 20% margins to the bounding box
    /* double dx = (X1-X0+1)/5.0; */
    /* double dy = (Y1-Y0+1)/5.0; */
    /* X0 -= dx; */
    /* X1 += dx; */
    /* Y0 -= dy; */
    /* Y1 += dy; */
    // printf("%f, %f, %f, %f\n\n\n", X0, Y0, X1,Y1);

    while (!is_pp_empty()){
        if(!is_ep_empty()){
             event_t * top_e = top_event();
             point_t top_p = top_point();
             if(top_e->x <= top_p.x){
                 process_event();
             }else{
                 process_point();
             }

        }else{
            process_point();
        }

    }

    //   print_arc_list();
    while(!is_ep_empty()){
        process_event();
    }
    finish_edges();
    rebuild_seg_list(&seg_list);
    int k;
    char *buf=malloc(sizeof(char)*1024);
    int pcount=0;
    for(k=0;k<seg_list.segs_count;k++){
        pcount+=sprintf(&buf[pcount],"%d;%d;%d;%d",k,seg_list.segs[k]->start.x,seg_list.segs[k]->start.y,seg_list.segs[k]->end.x,seg_list.segs[k]->end.y);
    }
    send_raw_eth_chn(34,buf,603);
}
Esempio n. 14
0
void ICQClient::processMsgQueueAuth()
{
    list<ICQEvent*>::iterator it;
    for (it = msgQueue.begin(); it != msgQueue.end();){
        ICQEvent *e = *it;
        if (e->message() == NULL){
            msgQueue.remove(e);
            e->state = ICQEvent::Fail;
            process_event(e);
            it = msgQueue.begin();
            continue;
        }
        switch (e->message()->Type()){
        case ICQ_MSGxAUTHxREQUEST:{
                ICQAuthRequest *msg = static_cast<ICQAuthRequest*>(e->message());
                snac(ICQ_SNACxFAM_LISTS, ICQ_SNACxLISTS_REQUEST_AUTH);
                ICQUser *u = getUser(msg->getUin());
                writeBuffer.packUin(msg->getUin());
                string message = clearHTML(msg->Message.c_str());
                toServer(message, u);
                writeBuffer << (unsigned short)(message.length());
                writeBuffer << message.c_str();
                writeBuffer << (unsigned short)0;
                sendPacket();
                (*it)->state = ICQEvent::Success;
                break;
            }
        case ICQ_MSGxAUTHxGRANTED:{
                ICQAuthRequest *msg = static_cast<ICQAuthRequest*>(e->message());
                snac(ICQ_SNACxFAM_LISTS, ICQ_SNACxLISTS_AUTHxSEND);
                writeBuffer.packUin(msg->getUin());
                writeBuffer
                << (char)0x01
                << (unsigned long)0;
                sendPacket();
                (*it)->state = ICQEvent::Success;
                break;
            }
        case ICQ_MSGxAUTHxREFUSED:{
                ICQAuthRequest *msg = static_cast<ICQAuthRequest*>(e->message());
                snac(ICQ_SNACxFAM_LISTS, ICQ_SNACxLISTS_REQUEST_AUTH);
                ICQUser *u = getUser(msg->getUin());
                writeBuffer.packUin(msg->getUin());
                string message = clearHTML(msg->Message.c_str());
                string original = message;
                toServer(message, u);
                writeBuffer
                << (char) 0
                << message
                << (unsigned long)0x00010001;
                if (message == original){
                    writeBuffer << (unsigned char)0;
                }else{
                    string charset = "utf-8";
                    writeBuffer << charset;
                }
                writeBuffer << (unsigned short)0;
                sendPacket();
                (*it)->state = ICQEvent::Success;
                break;
            }
        }
        if (e->state != ICQEvent::Success){
            it++;
            continue;
        }
        msgQueue.remove(e);
        process_event(e);
        it = msgQueue.begin();
    }
}
Esempio n. 15
0
void ICQClient::snac_lists(unsigned short type, unsigned short seq)
{
    bool bFull = false;
    switch (type){
    case ICQ_SNACxLISTS_RIGHTS:
        log(L_DEBUG, "List rights");
        break;
    case ICQ_SNACxLISTS_ROSTER:{
            char c;
            unsigned short list_len;
            log(L_DEBUG,"Rosters");
            if (m_bRosters){
                log(L_DEBUG, "Rosters part 2");
                break;
            }
            readBuffer >> c;
            if (c){
                log(L_WARN, "Bad first roster byte %02X", c);
                break;
            }
            vector<ICQGroup*>::iterator it_grp;
            list<ICQUser*>::iterator it_usr;
            for (it_grp = contacts.groups.begin(); it_grp != contacts.groups.end(); it_grp++)
                (*it_grp)->bChecked = false;
            for (it_usr = contacts.users.begin(); it_usr != contacts.users.end(); it_usr++){
                if ((*it_usr)->Type != USER_TYPE_ICQ) continue;
                (*it_usr)->Id = 0;
                (*it_usr)->GrpId = 0;
                (*it_usr)->inIgnore = false;
                (*it_usr)->inVisible = false;
                (*it_usr)->inInvisible = false;
            }
            readBuffer >> list_len;
            for (unsigned i = 0; i < list_len; i++){
                string str;
                unsigned short id, grp_id, type, len;
                readBuffer.unpackStr(str);
                readBuffer >> grp_id >> id >> type >> len;
                TlvList *inf = NULL;
                if (len){
                    Buffer b(len);
                    b.pack(readBuffer.Data(readBuffer.readPos()), len);
                    readBuffer.incReadPos(len);
                    inf = new TlvList(b);
                }
                switch (type){
                case 0x0000: /* User */{
                        unsigned long uin = atol(str.c_str());
                        if (uin == 0){
                            log(L_WARN, "Bad uin record %s\n", str.c_str());
                            break;
                        }
                        Tlv *tlv_name = NULL;
                        if (inf) tlv_name = (*inf)(0x0131);
                        string alias = tlv_name ? (char*)(*tlv_name) : "";
                        fromUTF(alias);
                        bool needAuth = false;
                        if (inf && (*inf)(0x0066)) needAuth = true;
                        ICQUser *user = getUser(uin, true);
                        user->Id = id;
                        user->GrpId = grp_id;
                        user->Alias = alias;
                        user->WaitAuth = needAuth;
                        break;
                    }
                case ICQ_GROUPS:{
                        if (str.size() == 0) break;
                        fromUTF(str);
                        ICQGroup *grp = getGroup(grp_id, true);
                        if (grp == NULL){
                            grp = new ICQGroup();
                            contacts.groups.push_back(grp);
                        }
                        grp->Id = grp_id;
                        grp->Name = str;
                        grp->bChecked = true;
                        break;
                    }
                case ICQ_VISIBLE_LIST:{
                        unsigned long uin = atol(str.c_str());
                        if (uin)
                            getUser(atol(str.c_str()), true)->inVisible = true;
                        break;
                    }
                case ICQ_INVISIBLE_LIST:{
                        unsigned long uin = atol(str.c_str());
                        if (uin)
                            getUser(atol(str.c_str()), true)->inInvisible = true;
                        break;
                    }
                case ICQ_IGNORE_LIST:{
                        unsigned long uin = atol(str.c_str());
                        if (uin)
                            getUser(atol(str.c_str()), true)->inIgnore = true;
                        break;
                    }
                case ICQ_INVISIBLE_STATE:
                    contacts.Invisible = id;
                    break;
                case 0x0009:
                    break;
                default:
                    log(L_WARN,"Unknown roster type %04X", type);
                }
                if (inf) delete inf;
            }
            unsigned long time;
            readBuffer >> time;
            contacts.Time = time;
            for (;;){
                bool ok = true;
                for (it_grp = contacts.groups.begin(); it_grp != contacts.groups.end(); it_grp++){
                    if (!(*it_grp)->bChecked){
                        contacts.groups.erase(it_grp);
                        ok = false;
                        break;
                    }
                }
                if (ok) break;
            }
            for (it_usr = contacts.users.begin(); it_usr != contacts.users.end(); it_usr++){
                unsigned short grpId = (*it_usr)->GrpId();
                bool ok = false;
                for (it_grp = contacts.groups.begin(); it_grp != contacts.groups.end(); it_grp++){
                    if ((*it_grp)->Id() == grpId){
                        ok = true;
                        break;
                    }
                }
                if (!ok) (*it_usr)->GrpId = 0;
            }
            ICQEvent e(EVENT_GROUP_CHANGED);
            process_event(&e);
            m_state = Logged;
            bFull = true;
        }
    case ICQ_SNACxLISTS_ROSTERxOK:	// FALLTHROUGH
        {
            m_bRosters = true;
            log(L_DEBUG, "Rosters OK");
            snac(ICQ_SNACxFAM_LISTS, ICQ_SNACxLISTS_UNKNOWN);
            sendPacket();
            sendCapability();
            sendICMB();
            sendLogonStatus();
            sendClientReady();
            sendMessageRequest();
            sendPhoneInit();
            sendPhoneStatus();
            if (bFull || (Nick.size() == 0)){
                addInfoRequest(Uin);
                searchByUin(Uin);
            }
            list<ICQUser*>::iterator it;
            for (it = contacts.users.begin(); it != contacts.users.end(); it++){
                if ((*it)->inIgnore()) continue;
                if (!bFull && (*it)->Nick.size()) continue;
                addInfoRequest((*it)->Uin);
            }
            if (contacts.groups.size() == 0){
                m_state = Logged;
                createGroup("General");
            }
            break;
        }
    case ICQ_SNACxLISTS_ADDED:{
            readBuffer.incReadPos(8);
            unsigned long uin = readBuffer.unpackUin();
            ICQAddedToList *m = new ICQAddedToList;
            m->Uin.push_back(uin);
            messageReceived(m);
            break;
        }
    case ICQ_SNACxLISTS_AUTHxREQUEST:{
            readBuffer.incReadPos(8);
            unsigned long uin = readBuffer.unpackUin();
            ICQUser *u = getUser(uin);
            string message;
            string charset;
            unsigned short have_charset;
            readBuffer.unpackStr(message);
            readBuffer >> have_charset;
            if (have_charset){
                readBuffer.incReadPos(2);
                readBuffer.unpackStr(charset);
            }
            if (charset.size()){
                translate(localCharset(u), charset.c_str(), message);
            }else{
                fromServer(message, u);
            }
            log(L_DEBUG, "Auth request %lu", uin);

            ICQAuthRequest *m = new ICQAuthRequest;
            m->Uin.push_back(uin);
            m->Message = message;
            messageReceived(m);
            break;
        }
    case ICQ_SNACxLISTS_AUTH:{
            readBuffer.incReadPos(8);
            unsigned long uin = readBuffer.unpackUin();
            char auth_ok; readBuffer >> auth_ok;
            string message;
            string charset;
            unsigned short have_charset;
            readBuffer.unpackStr(message);
            readBuffer >> have_charset;
            if (have_charset){
                readBuffer.incReadPos(2);
                readBuffer.unpackStr(charset);
            }
            ICQUser *u = getUser(uin);
            if (charset.size()){
                translate(localCharset(u), charset.c_str(), message);
            }else{
                fromServer(message, u);
            }
            log(L_DEBUG, "Auth %u %lu", auth_ok, uin);
            if (auth_ok){
                ICQUser *user = getUser(uin);
                if (user){
                    user->WaitAuth = false;
                    ICQEvent e(EVENT_INFO_CHANGED, uin);
                    process_event(&e);
                }
                ICQAuthGranted *m = new ICQAuthGranted();
                m->Uin.push_back(uin);
                messageReceived(m);
            }else{
                ICQAuthRefused *m = new ICQAuthRefused();
                m->Uin.push_back(uin);
                m->Message = message;
                messageReceived(m);
            }
            break;
        }
    case ICQ_SNACxLISTS_DONE:{
            ICQEvent *e = findListEvent(seq);
            if (e == NULL) break;
            readBuffer.incReadPos(8);
            unsigned short res;
            readBuffer >> res;
            e->processAnswer(this, readBuffer, res);
            delete e;
            break;
        }
    default:
        log(L_WARN, "Unknown lists family type %04X", type);
    }
}
Esempio n. 16
0
int main(int argc, char *argv[]) {
        Server server;
        int r = EXIT_FAILURE, n;

        if (getppid() != 1) {
                log_error("This program should be invoked by init only.");
                return EXIT_FAILURE;
        }

        if (argc > 1) {
                log_error("This program does not take arguments.");
                return EXIT_FAILURE;
        }

        log_set_target(LOG_TARGET_AUTO);
        log_parse_environment();
        log_open();

        umask(0022);

        n = sd_listen_fds(true);
        if (n < 0) {
                log_error_errno(r, "Failed to read listening file descriptors from environment: %m");
                return EXIT_FAILURE;
        }

        if (n <= 0 || n > SERVER_FD_MAX) {
                log_error("No or too many file descriptors passed.");
                return EXIT_FAILURE;
        }

        if (server_init(&server, (unsigned) n) < 0)
                return EXIT_FAILURE;

        log_debug("systemd-initctl running as pid "PID_FMT, getpid());

        sd_notify(false,
                  "READY=1\n"
                  "STATUS=Processing requests...");

        while (!server.quit) {
                struct epoll_event event;
                int k;

                k = epoll_wait(server.epoll_fd, &event, 1, TIMEOUT_MSEC);
                if (k < 0) {
                        if (errno == EINTR)
                                continue;
                        log_error_errno(errno, "epoll_wait() failed: %m");
                        goto fail;
                }

                if (k <= 0)
                        break;

                if (process_event(&server, &event) < 0)
                        goto fail;
        }

        r = EXIT_SUCCESS;

        log_debug("systemd-initctl stopped as pid "PID_FMT, getpid());

fail:
        sd_notify(false,
                  "STOPPING=1\n"
                  "STATUS=Shutting down...");

        server_done(&server);

        return r;
}
Esempio n. 17
0
int main (int argc, char *argv[])
{
	SDL_Surface *screen;
	int before = 0;
	int delta = 0;

	if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) {
		fprintf (stderr, "Failed to init SDL: %s\n", SDL_GetError ());
		return -1;
	}
	atexit (SDL_Quit);

	PDL_Init (0);
	atexit (PDL_Quit);

	screen = SDL_SetVideoMode (0, 0, 0, SDL_SWSURFACE);
	if (!screen) {
		fprintf (stderr, "Failed to set video mode: %s\n", SDL_GetError ());
		return -1;
	}

	SDL_Event event;
	while (true) {
		if (paused) {
			//switch to WaitEvent on pause because it blocks
			SDL_WaitEvent (&event);
			if (event.type == SDL_ACTIVEEVENT && event.active.gain == 1 && event.active.state & SDL_APPACTIVE) {
				paused = false;
				continue;
			}

			//while not active the OS may ask us to draw anyway, don't ignore it
			if (event.type == SDL_VIDEOEXPOSE) {
				draw_frame (screen);
			}
		}
		else {
			before = SDL_GetTicks ();

			while (SDL_PollEvent (&event)) {
				process_event (event);
			}

			draw_frame (screen);

			//we don't want to draw too fast, limit framerate
			delta = SDL_GetTicks () - before;
			while (delta < TICKS_PER_FRAME) {
				//we setup a timer that sends a user (custom) event
				SDL_TimerID timer = SDL_AddTimer (TICKS_PER_FRAME - delta, limiter, NULL);

				//clear the event type and wait for another event
				event.type = -1;
				SDL_WaitEvent (&event);

				//if it wasn't the user event process it and loop
				SDL_RemoveTimer (timer);

				if (event.type != SDL_USEREVENT) {
					process_event (event);

					//some time has passed, reset delta
					delta = SDL_GetTicks () - before;
				}
				else {
					break;
				}
			}
			printf ("FPS: %d\n", 1000 / (SDL_GetTicks () - before));
		}
	}
	return 0;
}
Esempio n. 18
0
static void
on_read (gpointer data)
{
    counter_t *counter = data;
    int mask = (N_PAGES * get_page_size() - 1);
    int n_bytes = mask + 1;
    gboolean skip_samples;
    Collector *collector;
    uint64_t head, tail;

    collector = counter->collector;
    
    tail = counter->tail;
    
    head = counter->mmap_page->data_head;
    rmb();
    
    if (head < tail)
    {
	g_warning ("sysprof fails at ring buffers (head "FMT64", tail "FMT64"\n", head, tail);
	
	tail = head;
    }
    
#if 0
    /* Verify that the double mapping works */
    x = g_random_int() & mask;
    g_assert (*(counter->data + x) == *(counter->data + x + n_bytes));
#endif

    skip_samples = in_dead_period (collector);

#if 0
    g_print ("n bytes %d\n", head - tail);
#endif
    
    while (head - tail >= sizeof (struct perf_event_header))
    {	
	struct perf_event_header *header;
	guint8 buffer[4096];
	guint8 *free_me;

	free_me = NULL;

	/* Note that:
	 * 
	 * - perf events are a multiple of 64 bits
	 * - the perf event header is 64 bits
	 * - the data area is a multiple of 64 bits
	 *
	 * which means there will always be space for one header, which means we
	 * can safely dereference the size field.
	 */
	header = (struct perf_event_header *)(counter->data + (tail & mask));

	if (header->size > head - tail)
	{
	    /* The kernel did not generate a complete event.
	     * I don't think that can happen, but we may as well
	     * be paranoid.
	     */
	    break;
	}

	if (counter->data + (tail & mask) + header->size > counter->data + n_bytes)
	{
	    int n_before, n_after;
	    guint8 *b;
	    
	    if (header->size > sizeof (buffer))
		free_me = b = g_malloc (header->size);
	    else
		b = buffer;

	    n_after = (tail & mask) + header->size - n_bytes;
	    n_before = header->size - n_after;
	    
	    memcpy (b, counter->data + (tail & mask), n_before);
	    memcpy (b + n_before, counter->data, n_after);

	    header = (struct perf_event_header *)b;
	}

	if (!skip_samples || header->type != PERF_RECORD_SAMPLE)
	{
	    if (header->type == PERF_RECORD_SAMPLE)
	      collector->n_samples++;
	    
	    process_event (collector, counter, (counter_event_t *)header);
	}

	if (free_me)
	    g_free (free_me);

	tail += header->size;
    }

    counter->tail = tail;
    counter->mmap_page->data_tail = tail;

    if (collector->callback)
    {
	if (collector->n_samples - collector->prev_samples >= N_WAKEUP_EVENTS)
	{
	    gboolean first_sample = collector->prev_samples == 0;
	    
	    collector->callback (first_sample, collector->data);

	    collector->prev_samples = collector->n_samples;
	}
    }
}
Esempio n. 19
0
static void *pipe_keys(void *ptr) {
  int i; 
  int ret;
  struct uinput_user_dev device; 
  struct input_event event;

  if (!keypad_device[0]) {
    syslog(LOG_ERR, "Error: unknown keypad device");
    return NULL;
  }

  memset(&device, 0, sizeof device);

  k_fd=open(keypad_device, O_RDONLY); 
  if (k_fd < 0)  {
    syslog(LOG_ERR, "open keypad (%s) err: %s", keypad_device, strerror(errno));
    goto err;
  }

  u_fd=open(UINPUT_DEVICE ,O_WRONLY); 
  if (u_fd < 0) {
    syslog(LOG_ERR, "open uinput err: %s", strerror(errno));
    goto err;
  }

  strcpy(device.name, "WebOS Internals KeyBoss");

  /* FIXME: any of this matter? */ 
  device.id.bustype=BUS_USB; 
  device.id.vendor=1; 
  device.id.product=1; 
  device.id.version=1;

  for (i=0; i < ABS_MAX; i++) {
    device.absmax[i] = -1;
    device.absmin[i] = -1;
    device.absfuzz[i] = -1;
    device.absflat[i] = -1;
  }

  device.absmin[ABS_X]=0;
  device.absmax[ABS_X]=255;
  device.absfuzz[ABS_X]=0;
  device.absflat[ABS_X]=0;

  if (write(u_fd, &device, sizeof(device)) != sizeof(device))
    goto err;

  if (ioctl(u_fd,UI_SET_EVBIT,EV_KEY) < 0)
    goto err;

  for (i=KEY_ESC; i<=KEY_SLIDER; i++) {
    if (ioctl(u_fd, UI_SET_KEYBIT, i) < 0)
      goto err;
  }

#if 0
    if (ioctl(u_fd,UI_SET_EVBIT,EV_REL) < 0)
            fprintf(stderr, "error evbit rel\n");

    for(i=REL_X;i<REL_MAX;i++)
        if (ioctl(u_fd,UI_SET_RELBIT,i) < 0)
            fprintf(stderr, "error setrelbit %d\n", i);
#endif

  ret = ioctl(u_fd, UI_DEV_CREATE);
  if (ret < 0)
    goto err;

  while (read(k_fd, &event, sizeof (struct input_event)) > 0) {
    process_event(&event);
    //syslog(LOG_DEBUG, "Got Hardware event type: %d, code: %d, value: %d\n", 
        //event.type, event.code, event.value);
    //send_event(u_fd, event.type, event.code, event.value);
  }

err:
  if (u_fd > 0)
    close(u_fd);
  if (k_fd > 0)
    close(k_fd);

  return NULL;
}
void UploadManagerImpl::Tick_StartUploads()
{
    mf::utils::unique_lock<mf::utils::mutex> lock(mutex_);

#ifndef NDEBUG
    // Ensure calling process event never causes recursion here.
    static bool recursing = false;
    assert(!recursing);
    recursing = true;
#endif

    auto CanUploadMore = [this]()
    {
        auto size = current_uploads_ + enqueued_to_start_uploads_.size();
        auto result = ( size < max_concurrent_uploads_ );

        return result;
    };

    if ( ! to_upload_.empty() )
    {
        const auto now = sclock::now();
        if ( action_token_state_ != ActionTokenState::Valid
            || action_token_expires_ < now )
        {
            // Invalid token

            if ( action_token_state_ == ActionTokenState::Error
                && now < action_token_expires_ )
            {
                // Skip till timeout.
            }
            else
            {
                action_token_state_ = ActionTokenState::Retrieving;

                // Unlock before calling external
                lock.unlock();

                auto self = shared_from_this();
                session_maintainer_->Call(
                    action_token::Request(action_token::Type::Upload),
                    [self](action_token::Response response)
                    {
                        self->HandleActionToken(response);
                    }
                    );
            }
            // If retrieving or error and not reached retry timeout, skip.
        }
        else if ( CanUploadMore() )
        {
            assert( ! action_token_.empty() );

            const auto token = action_token_;

            for (auto it = to_upload_.begin();
                it != to_upload_.end() && CanUploadMore();)
            {
                // Skip duplicate hashes
                auto request = *it;
                if (uploading_hashes_.find(request->hash()) ==
                    uploading_hashes_.end())
                {
                    // Remove iterator before process event.
                    it = to_upload_.erase(it);

                    uploading_hashes_.insert(request->hash());

                    enqueued_to_start_uploads_.insert(request.get());

                    auto self = shared_from_this();
                    io_service_->post(
                        [this, self, request, token]()
                        {
                            request->process_event(event::StartUpload{token});
                        });

                    // Only do one
                    break;
                }
                else
                {
                    ++it;
                }
            }
        }
    }

#ifndef NDEBUG
    if (!lock)
        lock.lock();
    recursing = false;
#endif
}
Esempio n. 21
0
static void main_event_loop(void)
{
	uint32 last_event_poll = 0;
	short game_state;

	while ((game_state = get_game_state()) != _quit_game) {
		uint32 cur_time = SDL_GetTicks();
		bool yield_time = false;
		bool poll_event = false;

		switch (game_state) {
			case _game_in_progress:
			case _change_level:
			  if (Console::instance()->input_active() || cur_time - last_event_poll >= TICKS_BETWEEN_EVENT_POLL) {
					poll_event = true;
					last_event_poll = cur_time;
			  } else {				  
					SDL_PumpEvents ();	// This ensures a responsive keyboard control
			  }
				break;

			case _display_intro_screens:
			case _display_main_menu:
			case _display_chapter_heading:
			case _display_prologue:
			case _display_epilogue:
			case _begin_display_of_epilogue:
			case _display_credits:
			case _display_intro_screens_for_demo:
			case _display_quit_screens:
			case _displaying_network_game_dialogs:
				yield_time = interface_fade_finished();
				poll_event = true;
				break;

			case _close_game:
			case _switch_demo:
			case _revert_game:
				yield_time = poll_event = true;
				break;
		}

		if (poll_event) {
			global_idle_proc();

			while (true) {
				SDL_Event event;
				bool found_event = SDL_PollEvent(&event);

				if (yield_time) {
					// The game is not in a "hot" state, yield time to other
					// processes by calling SDL_Delay() but only try for a maximum
					// of 30ms
					int num_tries = 0;
					while (!found_event && num_tries < 3) {
						SDL_Delay(10);
						found_event = SDL_PollEvent(&event);
						num_tries++;
					}
					yield_time = false;
				} else if (!found_event)
					break;

				if (found_event)
					process_event(event); 
			}
		}

		execute_timer_tasks(SDL_GetTicks());
		idle_game_state(SDL_GetTicks());

		if (game_state == _game_in_progress && !graphics_preferences->hog_the_cpu && (TICKS_PER_SECOND - (SDL_GetTicks() - cur_time)) > 10)
		{
			SDL_Delay(1);
		}
	}
}
Esempio n. 22
0
static void	update_triggers_status_to_unknown(zbx_uint64_t hostid, zbx_item_type_t type, int now, char *reason)
{
	const char		*__function_name = "update_triggers_status_to_unknown";
	DB_RESULT		result;
	DB_ROW			row;
	DB_TRIGGER_UPDATE	*tr = NULL, *tr_last;
	int			tr_alloc = 0, tr_num = 0;
	char			*sql = NULL;
	int			sql_alloc = 16 * ZBX_KIBIBYTE, sql_offset = 0;
	char		failed_type_buf[8];

	zabbix_log(LOG_LEVEL_DEBUG, "In %s() hostid:" ZBX_FS_UI64, __function_name, hostid);

	sql = zbx_malloc(sql, sql_alloc);

#ifdef HAVE_ORACLE
	zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, 7, "begin\n");
#endif

	/* determine failed item type */
	switch (type)
	{
		case ITEM_TYPE_ZABBIX:
			zbx_snprintf(failed_type_buf, sizeof(failed_type_buf), "%d", ITEM_TYPE_ZABBIX);
			break;
		case ITEM_TYPE_SNMPv1:
		case ITEM_TYPE_SNMPv2c:
		case ITEM_TYPE_SNMPv3:
			zbx_snprintf(failed_type_buf, sizeof(failed_type_buf), "%d,%d,%d",
					ITEM_TYPE_SNMPv1, ITEM_TYPE_SNMPv2c, ITEM_TYPE_SNMPv3);
			break;
		case ITEM_TYPE_IPMI:
			zbx_snprintf(failed_type_buf, sizeof(failed_type_buf), "%d", ITEM_TYPE_IPMI);
			break;
		default:
			/* we should never end up here */
			assert(0);
	}

	/******************************************************************************
	 * Set trigger status to UNKNOWN if all are true:                             *
	 * - trigger's item status ACTIVE                                             *
	 * - trigger's item type same as failed one                                   *
	 * - trigger does not reference time-based functions- trigger status ENABLED  *
	 * - trigger's host same as failed one                                        *
	 * - trigger's host status MONITORED                                          *
	 * - trigger does not reference "active" item                                 *
	 *                                                                            *
	 * An item is considered "active" if all are true:                            *
	 * - item status ACTIVE                                                       *
	 * - item's host status MONITORED                                             *
	 * - item's trigger references time-based functions                           *
	 *   OR                                                                       *
	 *   item is of different type AND it's host is AVAILABLE                     *
	 ******************************************************************************/
	result = DBselect(
			"select distinct t.triggerid,t.type,t.value,t.error"
			" from items i,functions f,triggers t,hosts h"
			" where i.itemid=f.itemid"
				" and f.triggerid=t.triggerid"
				" and i.hostid=h.hostid"
				" and i.status=%d"
				" and not i.key_ like '%s'"
				" and i.type in (%s)"
				" and f.function not in (" ZBX_SQL_TIME_FUNCTIONS ")"
				" and t.status=%d"
				" and h.hostid=" ZBX_FS_UI64
				" and h.status=%d"
			" and not exists ("
				"select 1"
				" from functions f2,items i2,hosts h2"
				" where f2.triggerid=f.triggerid"
					" and f2.itemid=i2.itemid"
					" and i2.hostid=h2.hostid"
					" and ("
						"f2.function in (" ZBX_SQL_TIME_FUNCTIONS ")"
						" or ("
							"i2.type not in (%s)"
							" and ("
								"i2.type not in (%d,%d,%d,%d,%d)"
								" or (i2.type in (%d) and h2.available=%d)"
								" or (i2.type in (%d,%d,%d) and h2.snmp_available=%d)"
								" or (i2.type in (%d) and h2.ipmi_available=%d)"
							")"
						")"
					")"
					" and i2.status=%d"
					" and not i2.key_ like '%s'"
					" and h2.status=%d"
			")"
			" order by t.triggerid",
			ITEM_STATUS_ACTIVE,
			SERVER_STATUS_KEY,
			failed_type_buf,
			TRIGGER_STATUS_ENABLED,
			hostid,
			HOST_STATUS_MONITORED,
			failed_type_buf,
			ITEM_TYPE_ZABBIX, ITEM_TYPE_SNMPv1, ITEM_TYPE_SNMPv2c, ITEM_TYPE_SNMPv3, ITEM_TYPE_IPMI,
			ITEM_TYPE_ZABBIX, HOST_AVAILABLE_TRUE,
			ITEM_TYPE_SNMPv1, ITEM_TYPE_SNMPv2c, ITEM_TYPE_SNMPv3, HOST_AVAILABLE_TRUE,
			ITEM_TYPE_IPMI, HOST_AVAILABLE_TRUE,
			ITEM_STATUS_ACTIVE,
			SERVER_STATUS_KEY,
			HOST_STATUS_MONITORED);

	while (NULL != (row = DBfetch(result)))
	{
		if (tr_num == tr_alloc)
		{
			tr_alloc += 64;
			tr = zbx_realloc(tr, tr_alloc * sizeof(DB_TRIGGER_UPDATE));
		}

		tr_last = &tr[tr_num++];

		ZBX_STR2UINT64(tr_last->triggerid, row[0]);
		tr_last->type = (unsigned char)atoi(row[1]);
		tr_last->value = atoi(row[2]);
		tr_last->new_value = TRIGGER_VALUE_UNKNOWN;
		tr_last->error = row[3];
		tr_last->lastchange = now;

		if (SUCCEED == DBget_trigger_update_sql(&sql, &sql_alloc, &sql_offset, tr_last->triggerid,
				tr_last->type, tr_last->value, tr_last->error, tr_last->new_value, reason,
				tr_last->lastchange, &tr_last->add_event))
		{
			zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, 3, ";\n");
		}

		DBexecute_overflowed_sql(&sql, &sql_alloc, &sql_offset);
	}
	DBfree_result(result);

#ifdef HAVE_ORACLE
	zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, 6, "end;\n");
#endif

	if (sql_offset > 16)	/* In ORACLE always present begin..end; */
		DBexecute("%s", sql);

	zbx_free(sql);

	if (0 != tr_num)
	{
		for (tr_last = &tr[0]; 0 != tr_num; tr_num--, tr_last++)
		{
			if (1 != tr_last->add_event)
				continue;

			process_event(0, EVENT_SOURCE_TRIGGERS, EVENT_OBJECT_TRIGGER, tr_last->triggerid,
					tr_last->lastchange, tr_last->new_value, 0, 0);
		}
	}

	zbx_free(tr);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
Esempio n. 23
0
main()
{
   INT status, size, trans, run_number;
   char host_name[256], str[32];
   INT event_id, request_id;
   DWORD last_time;
   BOOL via_callback;

   /* get parameters */

   printf("ID of event to request: ");
   ss_gets(str, 32);
   event_id = atoi(str);

   printf("Host to connect: ");
   ss_gets(host_name, 256);

   printf("Get all events (0/1): ");
   ss_gets(str, 32);
   all_flag = atoi(str);

   printf("Receive via callback ([y]/n): ");
   ss_gets(str, 32);
   via_callback = str[0] != 'n';

   /* connect to experiment */
   status = cm_connect_experiment(host_name, "",
                                  all_flag ? "Power Consumer" : "Consumer", NULL);
   if (status != CM_SUCCESS)
      return 1;

   /* open the "system" buffer, 1M size */
   bm_open_buffer("SYSTEM", EVENT_BUFFER_SIZE, &hBufEvent);

   /* set the buffer cache size */
   bm_set_cache_size(hBufEvent, 100000, 0);

   /* place a request for a specific event id */
   bm_request_event(hBufEvent, (WORD) event_id, TRIGGER_ALL,
                    all_flag ? GET_ALL : GET_SOME, &request_id,
                    via_callback ? process_event : NULL);

   /* place a request for system messages */
   cm_msg_register(process_message);

   /* place a request for transition notification */
   cm_register_transition(TR_START, via_callback? transition : NULL);

   last_time = 0;

   do {
      if (via_callback)
         status = cm_yield(1000);
      else {
         /* receive event "manually" and call receive_event */
         size = sizeof(event_buffer);
         status = bm_receive_event(hBufEvent, event_buffer, &size, ASYNC);
         if (status == BM_SUCCESS)
            process_event(hBufEvent, request_id, (EVENT_HEADER *) event_buffer,
                          (void *) (((EVENT_HEADER *) event_buffer) + 1));

         /* receive transitions "manually" */
         if (cm_query_transition(&trans, &run_number, NULL))
            transition(run_number, NULL);

         /* call yield once every 100 ms */
         if (ss_millitime() - last_time > 100) {
            last_time = ss_millitime();
            status = cm_yield(0);
         }
      }

   } while (status != RPC_SHUTDOWN && status != SS_ABORT);

   cm_disconnect_experiment();

   return 1;
}
Esempio n. 24
0
int main(int argc, char *argv[]) {
        Server server;
        int r = EXIT_FAILURE, n;

        if (getppid() != 1) {
                log_error("This program should be invoked by init only.");
                return EXIT_FAILURE;
        }

        if (argc > 1) {
                log_error("This program does not take arguments.");
                return EXIT_FAILURE;
        }

        log_set_target(LOG_TARGET_KMSG);
        log_parse_environment();
        log_open();

        if ((n = sd_listen_fds(true)) < 0) {
                log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
                return EXIT_FAILURE;
        }

        if (n <= 0 || n > SERVER_FD_MAX) {
                log_error("No or too many file descriptors passed.");
                return EXIT_FAILURE;
        }

        if (server_init(&server, (unsigned) n) < 0)
                return EXIT_FAILURE;

        log_debug("systemd-kmsg-syslogd running as pid %lu", (unsigned long) getpid());

        sd_notify(false,
                  "READY=1\n"
                  "STATUS=Processing messages...");

        for (;;) {
                struct epoll_event event;
                int k;

                if ((k = epoll_wait(server.epoll_fd, &event, 1, -1)) < 0) {

                        if (errno == EINTR)
                                continue;

                        log_error("epoll_wait() failed: %m");
                        goto fail;
                }

                if (k <= 0)
                        break;

                if ((k = process_event(&server, &event)) < 0)
                        goto fail;

                if (k == 0)
                        break;
        }

        r = EXIT_SUCCESS;

        log_debug("systemd-kmsg-syslogd stopped as pid %lu", (unsigned long) getpid());

fail:
        sd_notify(false,
                  "STATUS=Shutting down...");

        server_done(&server);

        return r;
}
Esempio n. 25
0
static void translation_test()
{
  int dpi;
  int dz;
  double mul;
  double exp;

  GE_Event mouse_evt = { };

  s_mouse_cal* mc = cal_get_mouse(current_mouse, current_conf);

  if(!mc->dzx || !mc->mx || !mc->ex)
  {
    return;
  }

  dpi = mc->dpi;
  dz = *mc->dzx;
  mul = *mc->mx;
  exp = *mc->ex;

  if (dpi <= 0)
  {
    return;
  }

  e_controller_type ctype = adapter_get(cal_get_controller(current_mouse))->ctype;

  if(ctype == C_TYPE_NONE)
  {
    return;
  }

  if (dots <= 0)
  {
    dots = distance * dpi;
  }

  if(delay > 0)
  {
    delay--;
    return;
  }

  mouse_evt.motion.xrel = direction * step;
  mouse_evt.motion.which = current_mouse;
  mouse_evt.type = GE_MOUSEMOTION;
  process_event(&mouse_evt);

  dots -= step;

  if (dots <= 0)
  {
    delay = DURATION / gimx_params.refresh_period;
    step *= 2;
    direction *= -1;
    if (direction > 0)
    {
      if ((dz - mul + mul * pow(step * 2 * gimx_params.frequency_scale, exp)) * controller_get_axis_scale(ctype, rel_axis_2) > controller_get_mean_unsigned(ctype, rel_axis_2))
      {
        step = 1;
        distance = 0.1;
      }
      else
      {
        distance = distance * 3;
      }
    }
  }
}
Esempio n. 26
0
File: arq.c Progetto: javi101190/ace
void receive_frame(arq* a, int16_t size, uint8_t* data) {
  process_event(a, RECEIVED_FRAME, size, data);
}
Esempio n. 27
0
int main(int argc, char * const argv[])
{
    int option_index;
    char command[1024];

    /* Initialize default strings */
    strcpy(vmlinux, "--no-vmlinux");
    strcpy(kernel_range, "");

    while (1) {
        int c = getopt_long(argc, argv, "", long_options, &option_index);
        if (c == -1) {
            break;
        }
        switch (c) {
            case 0:
                break;
            /* --event */
            case 'e':   
                if (num_events == MAX_EVENTS) {
                    fprintf(stderr, "More than %d events specified\n",
                            MAX_EVENTS);
                    exit(1);
                }
                if (process_event(optarg)) {
                    exit(1);
                }
                break;
            /* --vmlinux */
            case 'v':
                sprintf(vmlinux, "-k %s", optarg);
                break;
            /* --kernel-range */
            case 'r':
                sprintf(kernel_range, "-r %s", optarg);
                break;
            /* --shutdown */
            case 'h': {
                int pid = read_num(OP_DATA_DIR"/lock");
                if (pid >= 0) {
                    kill(pid, SIGKILL);
                }   
                setup_session_dir();
                break;
            }
            /* --status */
            case 't':
                do_status();
                break;
            default:
                usage();
                exit(1);
        }
    }
    verbose("list_events = %d\n", list_events);
    verbose("setup = %d\n", setup);

    if (list_events) {
        do_list_events();
    }

    if (quick) {
        process_event("CPU_CYCLES");
        setup = 1;
    }

    if (reset) {
        do_reset();
    }

    if (show_usage) {
        usage();
    }

    if (setup) {
        if (do_setup()) {
            fprintf(stderr, "do_setup failed");
            exit(1);
        }
    }

    if (num_events != 0) {
        int i;

        strcpy(command, "oprofiled --session-dir="OP_DATA_DIR);

#if !defined(WITH_ARM_V7_A)
        /* Since counter #3 can only handle CPU_CYCLES, check and shuffle the 
         * order a bit so that the maximal number of events can be profiled
         * simultaneously
         */
        if (num_events == 3) {
            for (i = 0; i < num_events; i++) {
                int event_idx = selected_events[i];

                if (event_info[event_idx].id == 0xff) {
                    break;
                }
            }

            /* No CPU_CYCLES is found */
            if (i == 3) {
                fprintf(stderr, "You can only specify three events if one of "
                                "them is CPU_CYCLES\n");
                exit(1);
            }
            /* Swap CPU_CYCLES to counter #2 (starting from #0)*/
            else if (i != 2) {
                int temp;

                temp = selected_events[2];
                selected_events[2] = selected_events[i];
                selected_events[i] = temp;

                temp = selected_counts[2];
                selected_counts[2] = selected_counts[i];
                selected_counts[i] = temp;
            }
        }
#endif


        /* Configure the counters and enable them */
        for (i = 0; i < num_events; i++) {
            int event_idx = selected_events[i];
            int setup_result = 0;

            if (i == 0) {
                snprintf(command+strlen(command), 1024 - strlen(command), 
                         " --events=");
            }
            else {
                snprintf(command+strlen(command), 1024 - strlen(command), 
                         ",");
            }
            /* Compose name:id:count:unit_mask:kernel:user, something like
             * --events=CYCLES_DATA_STALL:2:0:200000:0:1:1,....
             */
            snprintf(command+strlen(command), 1024 - strlen(command), 
                     "%s:%d:%d:%d:0:1:1",
                     event_info[event_idx].name,
                     event_info[event_idx].id,
                     i,
                     selected_counts[i]);

            setup_result |= echo_dev("1", 0, "user", i);
            setup_result |= echo_dev("1", 0, "kernel", i);
            setup_result |= echo_dev("0", 0, "unit_mask", i);
            setup_result |= echo_dev("1", 0, "enabled", i);
            setup_result |= echo_dev(NULL, selected_counts[i], "count", i);
            setup_result |= echo_dev(NULL, event_info[event_idx].id, 
                                     "event", i);
            if (setup_result) {
                fprintf(stderr, "Counter configuration failed for %s\n",
                        event_info[event_idx].name);
                fprintf(stderr, "Did you do \"opcontrol --setup\" first?\n");
                exit(1);
            }
        }

        /* Disable the unused counters */
        for (i = num_events; i < MAX_EVENTS; i++) {
            echo_dev("0", 0, "enabled", i);
        }

        snprintf(command+strlen(command), 1024 - strlen(command), " %s",
                 vmlinux);
        if (kernel_range[0]) {
            snprintf(command+strlen(command), 1024 - strlen(command), " %s",
                     kernel_range);
        }
        verbose("command: %s\n", command);
        system(command);
    }

    if (start) {
        echo_dev("1", 0, "enable", -1);
    }

    if (stop) {
        echo_dev("1", 0, "dump", -1);
        echo_dev("0", 0, "enable", -1);
    }
}
Esempio n. 28
0
File: arq.c Progetto: javi101190/ace
void timeout(arq* a) {
  process_event(a, TIMEOUT, 0, NULL);
}
Esempio n. 29
0
void process_iod_events(struct npool *nsp, struct niod *nsi, int ev) {
  int i = 0;
  /* store addresses of the pointers to the first elements of each kind instead
   * of storing the values, as a connect can add a read for instance */
  gh_lnode_t **start_elems[] = {
    &nsi->first_connect,
    &nsi->first_read,
    &nsi->first_write,
#if HAVE_PCAP
    &nsi->first_pcap_read,
#endif
    NULL
  };
  gh_list_t *evlists[] = {
    &nsp->connect_events,
    &nsp->read_events,
    &nsp->write_events,
#if HAVE_PCAP
    &nsp->pcap_read_events,
#endif
    NULL
  };

  assert(nsp == nsi->nsp);
  nsock_log_debug_all("Processing events on IOD %lu (ev=%d)", nsi->id, ev);

  /* We keep the events separate because we want to handle them in the
   * order: connect => read => write => timer for several reasons:
   *
   *  1) Makes sure we have gone through all the net i/o events before
   *     a timer expires (would be a shame to timeout after the data was
   *     available but before we delivered the events
   *
   *  2) The connect() results often lead to a read or write that can be
   *     processed in the same cycle.  In the same way, read() often
   *     leads to write().
   */
  for (i = 0; evlists[i] != NULL; i++) {
    gh_lnode_t *current, *next, *last;

    /* for each list, get the last event and don't look past it as an event
     * could add another event in the same list and so on... */
    last = gh_list_last_elem(evlists[i]);

    for (current = *start_elems[i];
         current != NULL && gh_lnode_prev(current) != last;
         current = next) {
      struct nevent *nse;

#if HAVE_PCAP
      if (evlists[i] == &nsi->nsp->pcap_read_events)
        nse = lnode_nevent2(current);
      else
#endif
        nse = lnode_nevent(current);

      /* events are grouped by IOD. Break if we're done with the events for the
       * current IOD */
      if (nse->iod != nsi)
        break;

      process_event(nsp, evlists[i], nse, ev);
      next = gh_lnode_next(current);

      if (nse->event_done) {
        /* event is done, remove it from the event list and update IOD pointers
         * to the first events of each kind */
        update_first_events(nse);
        gh_list_remove(evlists[i], current);
        gh_list_append(&nsp->free_events, &nse->nodeq_io);

        if (nse->timeout.tv_sec)
          gh_heap_remove(&nsp->expirables, &nse->expire);
      }
    }
  }
}
Esempio n. 30
0
int main(int argc, char *argv[]) {
        Server server;
        int r;

        /* if (getppid() != 1) { */
        /*         log_error("This program should be invoked by init only."); */
        /*         return EXIT_FAILURE; */
        /* } */

        if (argc > 1) {
                log_error("This program does not take arguments.");
                return EXIT_FAILURE;
        }

        log_set_target(LOG_TARGET_SAFE);
        log_set_facility(LOG_SYSLOG);
        log_parse_environment();
        log_open();

        umask(0022);

        r = server_init(&server);
        if (r < 0)
                goto finish;

        server_vacuum(&server);
        server_flush_to_var(&server);
        server_flush_dev_kmsg(&server);

        log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
        server_driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");

        sd_notify(false,
                  "READY=1\n"
                  "STATUS=Processing requests...");

        for (;;) {
                struct epoll_event event;
                int t = -1;
                usec_t n;

                n = now(CLOCK_REALTIME);

                if (server.max_retention_usec > 0 && server.oldest_file_usec > 0) {

                        /* The retention time is reached, so let's vacuum! */
                        if (server.oldest_file_usec + server.max_retention_usec < n) {
                                log_info("Retention time reached.");
                                server_rotate(&server);
                                server_vacuum(&server);
                                continue;
                        }

                        /* Calculate when to rotate the next time */
                        t = (int) ((server.oldest_file_usec + server.max_retention_usec - n + USEC_PER_MSEC - 1) / USEC_PER_MSEC);
                        log_info("Sleeping for %i ms", t);
                }

#ifdef HAVE_GCRYPT
                if (server.system_journal) {
                        usec_t u;

                        if (journal_file_next_evolve_usec(server.system_journal, &u)) {
                                if (n >= u)
                                        t = 0;
                                else
                                        t = MIN(t, (int) ((u - n + USEC_PER_MSEC - 1) / USEC_PER_MSEC));
                        }
                }
#endif

                r = epoll_wait(server.epoll_fd, &event, 1, t);
                if (r < 0) {

                        if (errno == EINTR)
                                continue;

                        log_error("epoll_wait() failed: %m");
                        r = -errno;
                        goto finish;
                }

                if (r > 0) {
                        r = process_event(&server, &event);
                        if (r < 0)
                                goto finish;
                        else if (r == 0)
                                break;
                }

                server_maybe_append_tags(&server);
                server_maybe_warn_forward_syslog_missed(&server);
        }

        log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
        server_driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");

finish:
        sd_notify(false,
                  "STATUS=Shutting down...");

        server_done(&server);

        return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}