Beispiel #1
0
EventPtr
insert_event1(EventPtr list,EventPtr q)
{
    EventPtr p = list;
    int time = q->time;
    if (!p) {
	return q;
    } 
    if (p->time > time) {
	q->next = p; return q;
    } else if (p->time == time) {
	free_event(q);
	return list;
    }
    if (!p->next) {
	p->next = q; return p;
    } 
    while(p->next && p->next->time <= time) {
	if (p->next->time == time) {
	    free_event(q);
	    return list;
	}
	p = p->next;
    }
    q->next = p->next;
    p->next = q;
    return list;
}
Beispiel #2
0
KHMEXP void KHMAPI
kherr_del_last_event(void)
{
    kherr_context * c;
    kherr_event * e;
    DWORD tid;

    c = peek_context();

    if(!IS_KHERR_CTX(c))
        return;

    tid = GetCurrentThreadId();

    EnterCriticalSection(&cs_error);
    e = QBOTTOM(c);
    while (e != NULL && e->thread_id != tid)
        e = QPREV(e);

    if(IS_KHERR_EVENT(e)) {
        QDEL(c, e);
        if(c->err_event == e) {
            pick_err_event(c);
        }
        free_event(e);
    }
    LeaveCriticalSection(&cs_error);
}
Beispiel #3
0
void CNet::DealSendEvent(struct iocp_event * pEvent) {
    if (ERROR_SUCCESS == pEvent->nerron) {
        CConnection * pCConnection = (CConnection *) (pEvent->p);
        pCConnection->stream.out(pEvent->ioBytes);
        s32 nSize = pCConnection->stream.size();
        if (0 == nSize) {
            if (pCConnection->bShutdown) {
                SafeShutdwon(pEvent, CSD_SEND);
            } else {
                free_event(pEvent);
            }
            CAutoLock(&(pCConnection->sdlock));
            pCConnection->nSDTags = pCConnection->nSDTags | CSD_SEND;
        } else {
            s32 err;
            pEvent->wbuf.buf = (char *)pCConnection->stream.buff();
            pEvent->wbuf.len = nSize;
            if (ERROR_NO_ERROR != async_send(pEvent, &err, pEvent->p)) {
                SafeShutdwon(pEvent, CSD_SEND);
            }
        }
    } else {
        SafeShutdwon(pEvent, CSD_SEND);
    }
}
Beispiel #4
0
static int event(ot_event_type t, ot_op* op) {
    event_type = t;

    free_event();
    event_op = ot_dup_op(op);

    return 0;
}
/* Append a new subscription event to the subscription event queue and schedule a main loop event */
void pa_subscription_post(pa_core *c, pa_subscription_event_type_t t, uint32_t idx) {
    pa_subscription_event *e;
    pa_assert(c);

    /* No need for queuing subscriptions of no one is listening */
    if (!c->subscriptions)
        return;

    if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) != PA_SUBSCRIPTION_EVENT_NEW) {
        pa_subscription_event *i, *n;

        /* Check for duplicates */
        for (i = c->subscription_event_last; i; i = n) {
            n = i->prev;

            /* not the same object type */
            if (((t ^ i->type) & PA_SUBSCRIPTION_EVENT_FACILITY_MASK))
                continue;

            /* not the same object */
            if (i->index != idx)
                continue;

            if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) {
                /* This object is being removed, hence there is no
                 * point in keeping the old events regarding this
                 * entry in the queue. */

                free_event(i);
                pa_log_debug("Dropped redundant event due to remove event.");
                continue;
            }

            if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_CHANGE) {
                /* This object has changed. If a "new" or "change" event for
                 * this object is still in the queue we can exit. */

                pa_log_debug("Dropped redundant event due to change event.");
                return;
            }
        }
    }

    e = pa_xnew(pa_subscription_event, 1);
    e->core = c;
    e->type = t;
    e->index = idx;

    PA_LLIST_INSERT_AFTER(pa_subscription_event, c->subscription_event_queue, c->subscription_event_last, e);
    c->subscription_event_last = e;

#ifdef DEBUG
    dump_event("Queued", e);
#endif

    sched_event(c);
}
Beispiel #6
0
extern int
del_event(char *name)
{
    tcvp_event_type_t *e;

    if(!tchash_delete(event_types, name, -1, &e))
        free_event(e);

    return 0;
}
Beispiel #7
0
/* Assumes that the context has been deleted from all relevant
   lists */
static void
free_context(kherr_context * c)
{
    kherr_context * ch;
    kherr_event * e;

    assert(IS_KHERR_CTX(c));

#ifdef DEBUG_CONTEXT
    if (IsDebuggerPresent())
        kherr_debug_printf(L"Freeing context 0x%x\n", c);
#endif

    EnterCriticalSection(&cs_error);

    if (c->desc_event)
        free_event(c->desc_event);
    c->desc_event = NULL;

    TPOPCHILD(c, &ch);
    while(ch) {
        free_context(ch);
        TPOPCHILD(c, &ch);
    }
    QGET(c, &e);
    while(e) {
        free_event(e);
        QGET(c, &e);
    }

    c->serial = 0;

    LPUSH(&ctx_free_list,c);
    LeaveCriticalSection(&cs_error);

#ifdef DEBUG_CONTEXT
    if (IsDebuggerPresent())
        kherr_debug_printf(L"Done with context 0x%x\n", c);
#endif
}
Beispiel #8
0
results server_tests() {
    RUN_TEST(server_receive_fires_event_when_parent_cannot_be_found);
    RUN_TEST(server_receive_fires_event_when_append_error_occurs);
    RUN_TEST(server_receive_fires_event_when_xform_error_occurs);
    RUN_TEST(server_receive_fires_event_when_a_decode_error_occurs);
    RUN_TEST(server_receive_when_op_has_parent_and_doc_is_empty);
    RUN_TEST(server_receive_when_empty_doc_is_opened);

    free_sent();
    free_event();

    return (results){passed, failed};
}
/* Free all subscription objects */
void pa_subscription_free_all(pa_core *c) {
    pa_assert(c);

    while (c->subscriptions)
        free_subscription(c->subscriptions);

    while (c->subscription_event_queue)
        free_event(c->subscription_event_queue);

    if (c->subscription_defer_event) {
        c->mainloop->defer_free(c->subscription_defer_event);
        c->subscription_defer_event = NULL;
    }
}
Beispiel #10
0
/**
 * @brief Run the destroy an event, whatever the date
 * @param event an event to run
 *
 * If the event is periodic, it is rescheduled an not destroyed.
 */
void event_run(struct event_t * event)
{
   printf_debug(DEBUG_EVENT, " running ev %p at %f\n", event, event->date);
 
   event->run(event->data);

   if (event->type &EVENT_PERIODIC) {
      event->date += event->period;
      motSim_scheduleEvent(event, event->date);
   } else {
      free_event(event);
   }

   printf_debug(DEBUG_EVENT, " end of ev %p at %f\n", event, event->date);
}
Beispiel #11
0
void core::curl_handler::connection_context::update(curl_socket_t _socket, int _action)
{
    socket_ = _socket;

    if (event_)
        free_event();

    auto kind = EV_PERSIST;
    if (_action & CURL_POLL_IN)
        kind |= EV_READ;
    if (_action & CURL_POLL_OUT)
        kind |= EV_WRITE;

    event_ = event_new(curl_handler_->event_base_, socket_, kind, event_callback, this);
    event_add(event_, NULL);
}
Beispiel #12
0
/*
 * ===  FUNCTION  ======================================================================
 *         Name:  pop_event
 *  Description:  pop a timer event from event linked list.
 * =====================================================================================
 */
static void pop_event ( struct stim_event *event )
{
  if(event_list.head == event){
    event_list.head = NULL;
    event_list.tail = NULL;
  } else if (event_list.tail == event){
    event_list.tail = event->prev;
		event_list.tail->next = NULL;
  }else {
    event->prev->next = event->next;
    event->next->prev = event->prev;
  }

  free_event(event);

  event_list.count--;
}		/* -----  end of static function stim_pop_delay_event  ----- */
void USkookumScriptListener::deinitialize()
  {
  // Kill any events that are still around
  while (has_event())
    {
    free_event(pop_event(), true);
    }

  // Forget the coroutine we keep track of
  m_coro_p.null();

  // Unregister from delegate list if any
  if (m_unregister_callback_p && m_obj_p.IsValid())
    {
    (*m_unregister_callback_p)(m_obj_p.Get(), this);
    }
  }
Beispiel #14
0
/* this function is called upon unloading of the mex-file */
void exitFun(void) {
	int verbose = 1;
	int rc;
  
	if (verbose) {
		printf("Entering exitFun() routine\n");
	}

    /* tell the tcpserver thread to stop */
    pthread_mutex_lock(&mutexstatus);
    if (tcpserverStatus) {
            pthread_mutex_unlock(&mutexstatus);
            mexPrintf("requesting cancelation of tcpserver thread\n");
            pthread_cancel(tcpserverThread);
            pthread_join(tcpserverThread, NULL);
    }
    else {
            pthread_mutex_unlock(&mutexstatus);
    }

	/* free the memory that is used for the header, data and events */
	free_event();
	free_data();
	free_header();

	/* clean up host/address/socket list and close open sockets */
	while (firstHostPortSock != NULL) {
		host_port_sock_list_item_t *hpsli = firstHostPortSock;

		if (hpsli->sock > 0) {
			if (verbose) {
				printf("Closing socket and ");
			}
			close_connection(hpsli->sock);
		}
		if (verbose) {
			printf("cleaning up list entry %s:%i\n",hpsli->hostname, hpsli->port);
		}
		FREE(hpsli->hostname);

		firstHostPortSock = hpsli->next;
		free(hpsli);
	}
	return;
}
Beispiel #15
0
int read_smag(struct dev_input *inp)
{
	/*need to return 1 if we fill in inp or 0 if no events */
	struct smag_event *ev;

	input.rbuf_sz = smag_read(dev_fd, input.rbuf, MAXREADSIZE);
	if(input.rbuf_sz > 0) {
		read_copy();
	}
	ev = input.evhead;
	if(ev) {
		input.evhead = input.evhead->next;

		*inp = ev->data;
		free_event(ev);
		return 1;
	}
	return 0;
}
Beispiel #16
0
    int socket_callback(CURL* _easy_handle, curl_socket_t _socket, int _what, void* _curl_handler_ptr, void* _connection_ptr)
    {
        const auto handler = static_cast<curl_handler*>(_curl_handler_ptr);

        const auto connection = static_cast<curl_handler::connection_context*>(_connection_ptr);

        if (_what == CURL_POLL_REMOVE)
        {
            connection->free_event();
        }
        else if (connection == NULL)
        {
            add_socket(_socket, _easy_handle, _what, handler);
        }
        else
        {
            connection->update(_socket, _what);
        }

        return 0;
    }
Beispiel #17
0
    /** 异步连接 */
    error_code async_connect(const char * pStrIP, s32 nPort, OUT s32 * pnError, void * pData) {
        struct epoll_event e;
        struct cepoll_event * pEvent = NULL;
        s32 s = socket(AF_INET, SOCK_STREAM, 0);
        errno = 0;
        if (-1 == fcntl(s, F_SETFL, fcntl(s, F_GETFL) | O_NONBLOCK)) {
            RETURN_RES(ERROR_FCNTL);
        }

        pEvent = malloc_event();
        if (NULL == pEvent) {
            //assert(false);
            ECHO_ERROR("%s", "get cepoll_event error");
            RETURN_RES(ERROR_MALLOC_EVENT);
        }
        pEvent->s = s;
        pEvent->p = pData;
        pEvent->event = EVENT_ASYNC_CONNECT;


        e.events = EPOLLOUT | EPOLLET;
        e.data.ptr = pEvent;
        epoll_ctl(s_epfd, EPOLL_CTL_ADD, s, &e);

        if((pEvent->remote.sin_addr.s_addr = inet_addr(pStrIP)) == INADDR_NONE) {
            free_event(pEvent);
            RETURN_RES(ERROR_IP_FORMAT);
        }

        *pnError = connect(s, (struct sockaddr*)&pEvent->remote, sizeof(pEvent->remote));
        /*
        getsockopt(socket_fd, SOL_SOCKET, SO_ERROR, &error, (socklen_t *)&len);
        if( !error )
        {
        //OK
        }
        */
        *pnError = 100;
        return ERROR_CODE_MAX;
    }
Beispiel #18
0
/** Free the memory the user occupies.
    @param user The user we free. */
void
free_user(User *user)
{
#ifdef DEBUG
    printf("free_user\n");
#endif

    gint i, j;

    free_gchar_ptr(user->name);
    free_g_string(&user->sponsor.name);
    free_gchar_ptr(user->mmatches_file);
    free_live_game(&user->live_game);
    free_option_list(&user->options, FALSE);

    for(i=0; i<user->events->len; i++)
        free_event(&g_array_index(user->events, Event, i));
    free_g_array(&user->events);

    for(i=0; i<user->history->len; i++)
    {
        free_gchar_ptr(g_array_index(user->history,
                                     UserHistory, i).team_name);
        for(j=0; j<3; j++)
            free_gchar_ptr(g_array_index(user->history,
                                         UserHistory, i).string[j]);
    }

    free_g_array(&user->history);

    free_mmatches(&user->mmatches, FALSE);

    free_player_array(&user->youth_academy.players);

    free_g_array(&user->bets[0]);
    free_g_array(&user->bets[1]);
    g_array_free(user->default_team, TRUE);
}
Beispiel #19
0
/* Deferred callback for dispatching subscription events */
static void defer_cb(pa_mainloop_api *m, pa_defer_event *de, void *userdata) {
    pa_core *c = userdata;
    pa_subscription *s;

    pa_assert(c->mainloop == m);
    pa_assert(c);
    pa_assert(c->subscription_defer_event == de);

    c->mainloop->defer_enable(c->subscription_defer_event, 0);

    /* Dispatch queued events */

    while (c->subscription_event_queue) {
        pa_subscription_event *e = c->subscription_event_queue;

        for (s = c->subscriptions; s; s = s->next) {

            if (!s->dead && pa_subscription_match_flags(s->mask, e->type))
                s->callback(c, e->type, e->index, s->userdata);
        }

#ifdef DEBUG
        dump_event("Dispatched", e);
#endif
        free_event(e);
    }

    /* Remove dead subscriptions */

    s = c->subscriptions;
    while (s) {
        pa_subscription *n = s->next;
        if (s->dead)
            free_subscription(s);
        s = n;
    }
}
Beispiel #20
0
core::curl_handler::connection_context::~connection_context()
{
    free_event();
    event_free(timeout_event_);
}
static ssize_t hone_read(struct file *file, char __user *buffer,
		size_t length, loff_t *offset)
{
	struct hone_reader *reader = file->private_data;
	size_t n, copied = 0;

	if (!length)
		return 0;

	do {
		while (!reader->offset && reader_will_block(reader)) {
			if (file->f_flags & O_NONBLOCK)
				return -EAGAIN;
			if (wait_event_interruptible(reader->event_wait_queue,
						!reader_will_block(reader)))
				return -EINTR;
		}

		if (file->f_flags & O_NONBLOCK) {
			if (down_trylock(&reader->sem))
				return -EAGAIN;
		} else if (down_interruptible(&reader->sem)) {
			return -EINTR;
		}

		while (copied < length) {
			if (!reader->offset) {
				int flags;
				struct hone_event *event;
				void (*free_event)(struct hone_event *);

				flags = atomic_read(&reader->flags);
				if (flags & READER_TAIL) {
					atomic_clear_mask(READER_TAIL, &reader->flags);
					event = &tail_event;
					free_event = NULL;
				} else if (flags & READER_FINISH) {
					if (!copied)
						atomic_clear_mask(READER_FINISH, &reader->flags);
					up(&reader->sem);
					return copied;
				} else if (flags & READER_HEAD) {
					atomic_clear_mask(READER_HEAD, &reader->flags);
					event = &head_event;
					free_event = NULL;
				} else if (flags & READER_INIT) {
					atomic_clear_mask(READER_INIT, &reader->flags);
					add_initial_events(reader);
					continue;
				} else if (reader->event) {
					if ((event = reader->event))
						reader->event = event->next;
					free_event = free_hone_event;
				} else {
					event = ring_pop(&reader->ringbuf);
					free_event = put_hone_event;
				}

				if (!event)
					break;
				reader->length = reader->format(&devinfo, &reader->info,
						event, reader->buf, READ_BUFFER_SIZE);
				inc_stats_counter(&reader->info.delivered, event->type);
				if (free_event)
					free_event(event);
			}
			n = min(reader->length - reader->offset, length - copied);
			if (copy_to_user(buffer + copied, reader->buf + reader->offset, n)) {
				up(&reader->sem);
				return -EFAULT;
			}
			copied += n;
			reader->offset += n;
			if (reader->offset >= reader->length)
				reader->offset = 0;
		}
		up(&reader->sem);
	} while (!copied);
	return copied;
}
Beispiel #22
0
/*
 * Frees a hdr_field structure,
 * WARNING: it frees only parsed (and not name.s, body.s)
 */
void clean_hdr_field(struct hdr_field* hf)
{
	if (hf->parsed){
		switch(hf->type){
		case HDR_VIA_T:
			free_via_list(hf->parsed);
			hf->parsed = NULL;
			break;

		case HDR_TO_T:
			free_to(hf->parsed);
			hf->parsed = NULL;
			break;

		case HDR_FROM_T:
			free_to(hf->parsed);
			hf->parsed = NULL;
			break;

		case HDR_CSEQ_T:
			free_cseq(hf->parsed);
			hf->parsed = NULL;
			break;

		case HDR_CALLID_T:
			break;

		case HDR_CONTACT_T:
			free_contact((contact_body_t**)(void*)(&(hf->parsed)));
			break;

		case HDR_MAXFORWARDS_T:
			break;

		case HDR_ROUTE_T:
			free_rr((rr_t**)(void*)(&hf->parsed));
			break;

		case HDR_RECORDROUTE_T:
			free_rr((rr_t**)(void*)(&hf->parsed));
			break;

		case HDR_PATH_T:
			free_rr((rr_t**)(void*)(&hf->parsed));
			break;

		case HDR_CONTENTTYPE_T:
			free_contenttype((content_t**)(void*)(&hf->parsed));
			break;

		case HDR_CONTENTLENGTH_T:
			break;

		case HDR_AUTHORIZATION_T:
			free_credentials((auth_body_t**)(void*)(&(hf->parsed)));
			break;

		case HDR_EXPIRES_T:
			free_expires((exp_body_t**)(void*)(&(hf->parsed)));
			break;

		case HDR_PROXYAUTH_T:
			free_credentials((auth_body_t**)(void*)(&(hf->parsed)));
			break;

		case HDR_SUPPORTED_T:
			free_supported((struct supported_body**)(void*)(&(hf->parsed)));
			break;

		case HDR_PROXYREQUIRE_T:
			break;

		case HDR_UNSUPPORTED_T:
			break;

		case HDR_ALLOW_T:
			free_allow((struct allow_body**)(void*)(&(hf->parsed)));
			break;

		case HDR_EVENT_T:
			free_event((event_t**)(void*)(&(hf->parsed)));
			break;

		case HDR_ACCEPT_T:
			pkg_free(hf->parsed);
			hf->parsed = NULL;
			break;

		case HDR_ACCEPTLANGUAGE_T:
			break;
			
		case HDR_ORGANIZATION_T:
			break;
			
		case HDR_PRIORITY_T:
			break;

		case HDR_SUBJECT_T:
			break;

		case HDR_USERAGENT_T:
			break;

		case HDR_ACCEPTDISPOSITION_T:
			break;

		case HDR_CONTENTDISPOSITION_T:
			free_disposition( ((struct disposition**)(void*)(&hf->parsed)) );
			break;

		case HDR_DIVERSION_T:
			free_to(hf->parsed);
			hf->parsed = NULL;
			break;

		case HDR_RPID_T:
			free_to(hf->parsed);
			hf->parsed = NULL;
			break;

		case HDR_REFER_TO_T:
			free_to(hf->parsed);
			hf->parsed = NULL;
			break;

		case HDR_SESSION_EXPIRES_T:
			free_session_expires((struct session_expires*)hf->parsed );
			hf->parsed = NULL;
			break;

		case HDR_MIN_SE_T:
			break;

		case HDR_MIN_EXPIRES_T:
			break;

		case HDR_PPI_T:
			free_to(hf->parsed);
			hf->parsed = NULL;
			break;

		case HDR_PAI_T:
			free_to(hf->parsed);
			hf->parsed = NULL;
			break;

		case HDR_PRIVACY_T:
			break;

		case HDR_RETRY_AFTER_T:
			break;

		case HDR_CALL_INFO_T:
			free_call_info(hf->parsed);
			hf->parsed = NULL;
			break;

		case HDR_WWW_AUTHENTICATE_T:
		case HDR_PROXY_AUTHENTICATE_T:
			free_authenticate((struct authenticate_body *)hf->parsed);
			hf->parsed = NULL;
			break;

		default:
			LM_CRIT("unknown header type %d\n", hf->type);
			break;
		}
	}
}
Beispiel #23
0
/* 
 * Frees a hdr_field structure,
 * WARNING: it frees only parsed (and not name.s, body.s)
 */
void clean_hdr_field(struct hdr_field* hf)
{
	if (hf->parsed){
		switch(hf->type){
		case HDR_VIA:
			free_via_list(hf->parsed);
			break;

		case HDR_TO:
			free_to(hf->parsed);
			break;

		case HDR_FROM:
			free_to(hf->parsed);
			break;

		case HDR_CSEQ:
			free_cseq(hf->parsed);
			break;

		case HDR_CALLID:
			break;

		case HDR_CONTACT:
			free_contact((contact_body_t**)(&(hf->parsed)));
			break;

		case HDR_MAXFORWARDS:
			break;

		case HDR_ROUTE:
			free_rr((rr_t**)(&hf->parsed));
			break;

		case HDR_RECORDROUTE:
			free_rr((rr_t**)(&hf->parsed));
			break;

		case HDR_CONTENTTYPE:
			break;

		case HDR_CONTENTLENGTH:
			break;

		case HDR_AUTHORIZATION:
			free_credentials((auth_body_t**)(&(hf->parsed)));
			break;

		case HDR_EXPIRES:
			free_expires((exp_body_t**)(&(hf->parsed)));
			break;

		case HDR_PROXYAUTH:
			free_credentials((auth_body_t**)(&(hf->parsed)));
			break;

		case HDR_SUPPORTED:
			break;

		case HDR_PROXYREQUIRE:
			break;

		case HDR_UNSUPPORTED:
			break;

		case HDR_ALLOW:
			break;

		case HDR_EVENT:
			free_event((event_t**)(&(hf->parsed)));
			break;

		case HDR_ACCEPT:
			pkg_free(hf->parsed);
			break;

		case HDR_ACCEPTLANGUAGE:
			break;
			
		case HDR_ORGANIZATION:
			break;
			
		case HDR_PRIORITY:
			break;

		case HDR_SUBJECT:
			break;

		case HDR_USERAGENT:
			break;

		case HDR_ACCEPTDISPOSITION:
			break;

		case HDR_CONTENTDISPOSITION:
			free_disposition( ((struct disposition**)(&hf->parsed)) );
			break;

		default:
			LOG(L_CRIT, "BUG: clean_hdr_field: unknown header type %d\n",
			    hf->type);
			break;
		}
	}
}
Beispiel #24
0
/* Should NOT be called with cs_error held */
KHMEXP kherr_event * KHMAPI
kherr_report(enum kherr_severity severity,
             const wchar_t * short_desc,
             const wchar_t * facility,
             const wchar_t * location,
             const wchar_t * long_desc,
             const wchar_t * suggestion,
             khm_int32 facility_id,
             enum kherr_suggestion suggestion_id,
             kherr_param p1,
             kherr_param p2,
             kherr_param p3,
             kherr_param p4,
             khm_int32 flags
#ifdef _WIN32
             ,HMODULE  h_module
#endif
             )
{
    kherr_context * c;
    kherr_event * e;

    e = get_empty_event();

    e->thread_id = GetCurrentThreadId();
    e->time_ticks = GetTickCount();
    GetSystemTimeAsFileTime(&e->time_ft);

    e->severity = severity;
    e->short_desc = short_desc;
    e->facility = facility;
    e->location = location;
    e->long_desc = long_desc;
    e->suggestion = suggestion;
    e->facility_id = facility_id;
    e->suggestion_id = suggestion_id;
    e->p1 = p1;
    e->p2 = p2;
    e->p3 = p3;
    e->p4 = p4;
    e->flags = flags;
#ifdef _WIN32
    e->h_module = h_module;
#endif

    /* sanity check */
    if (!IS_POW2(flags & KHERR_RFMASK_SHORT_DESC) ||
	!IS_POW2(flags & KHERR_RFMASK_LONG_DESC) ||
	!IS_POW2(flags & KHERR_RFMASK_SUGGEST))
    {
        /* the reason why we are doing it this way is because p1..p4,
           the descriptions and the suggestion may contain allocations
           that has to be freed. */
#ifdef DEBUG
	assert(FALSE);
#else
	if (IsDebuggerPresent())
	    DebugBreak();
#endif
        free_event(e);
        e = NULL;
    } else {
	EnterCriticalSection(&cs_error);
	c = peek_context();
	if(c) {
	    add_event(c,e);
	} else {
	    free_event(e);
	    e = NULL;
	}
	LeaveCriticalSection(&cs_error);
    }

    return e;
}
Beispiel #25
0
/*
  this is where it all happens...
*/
int main_loop(void) {
	fd_set readset, writeset;
#ifdef HAVE_PSELECT
	struct timespec tv;
	sigset_t omask, block_mask;
	time_t next_event;
#else
	struct timeval tv;
#endif
	int r, maxfd;
	time_t last_ping_check, last_config_check, last_graph_dump;
	event_t *event;

	last_ping_check = now;
	last_config_check = now;
	last_graph_dump = now;
	
	srand(now);

#ifdef HAVE_PSELECT
	if(lookup_config(config_tree, "GraphDumpFile"))
		graph_dump = true;
	/* Block SIGHUP & SIGALRM */
	sigemptyset(&block_mask);
	sigaddset(&block_mask, SIGHUP);
	sigaddset(&block_mask, SIGALRM);
	sigprocmask(SIG_BLOCK, &block_mask, &omask);
#endif

	running = true;

	while(running) {
#ifdef HAVE_PSELECT
		next_event = last_ping_check + pingtimeout;
		if(graph_dump && next_event > last_graph_dump + 60)
			next_event = last_graph_dump + 60;

		if((event = peek_next_event()) && next_event > event->time)
			next_event = event->time;

		if(next_event <= now)
			tv.tv_sec = 0;
		else
			tv.tv_sec = next_event - now;
		tv.tv_nsec = 0;
#else
		tv.tv_sec = 1;
		tv.tv_usec = 0;
#endif

		maxfd = build_fdset(&readset, &writeset);

#ifdef HAVE_MINGW
		LeaveCriticalSection(&mutex);
#endif
#ifdef HAVE_PSELECT
		r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
#else
		r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
#endif
		now = time(NULL);
#ifdef HAVE_MINGW
		EnterCriticalSection(&mutex);
#endif

		if(r < 0) {
			if(!sockwouldblock(sockerrno)) {
				logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
				dump_connections();
				return 1;
			}
		}

		if(r > 0)
			check_network_activity(&readset, &writeset);

		if(do_purge) {
			purge();
			do_purge = false;
		}

		/* Let's check if everybody is still alive */

		if(last_ping_check + pingtimeout <= now) {
			check_dead_connections();
			last_ping_check = now;

			if(routing_mode == RMODE_SWITCH)
				age_subnets();

			age_past_requests();

			/* Should we regenerate our key? */

			if(keyexpires <= now) {
				avl_node_t *node;
				node_t *n;

				ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");

				for(node = node_tree->head; node; node = node->next) {
					n = node->data;
					if(n->inkey) {
						free(n->inkey);
						n->inkey = NULL;
					}
				}

				send_key_changed();
				keyexpires = now + keylifetime;
			}

			/* Detect ADD_EDGE/DEL_EDGE storms that are caused when
			 * two tinc daemons with the same name are on the VPN.
			 * If so, sleep a while. If this happens multiple times
			 * in a row, sleep longer. */

			if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
				logger(LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
				usleep(sleeptime * 1000000LL);
				sleeptime *= 2;
				if(sleeptime < 0)
					sleeptime = 3600;
			} else {
				sleeptime /= 2;
				if(sleeptime < 10)
					sleeptime = 10;
			}

			contradicting_add_edge = 0;
			contradicting_del_edge = 0;
		}

		if(sigalrm) {
			avl_node_t *node;
			logger(LOG_INFO, "Flushing event queue");
			expire_events();
			for(node = connection_tree->head; node; node = node->next) {
				connection_t *c = node->data;
				if(c->status.active)
					send_ping(c);
			}
			sigalrm = false;
		}

		while((event = get_expired_event())) {
			event->handler(event->data);
			free_event(event);
		}

		if(sighup) {
			connection_t *c;
			avl_node_t *node, *next;
			char *fname;
			struct stat s;
			
			sighup = false;

			reopenlogger();
			
			/* Reread our own configuration file */

			exit_configuration(&config_tree);
			init_configuration(&config_tree);

			if(!read_server_config()) {
				logger(LOG_ERR, "Unable to reread configuration file, exitting.");
				return 1;
			}

			/* Cancel non-active outgoing connections */

			for(node = connection_tree->head; node; node = next) {
				next = node->next;
				c = node->data;

				c->outgoing = NULL;

				if(c->status.connecting) {
					terminate_connection(c, false);
					connection_del(c);
				}
			}

			/* Wipe list of outgoing connections */

			for(list_node_t *node = outgoing_list->head; node; node = node->next) {
				outgoing_t *outgoing = node->data;

				if(outgoing->event)
					event_del(outgoing->event);
			}

			list_delete_list(outgoing_list);

			/* Close connections to hosts that have a changed or deleted host config file */
			
			for(node = connection_tree->head; node; node = node->next) {
				c = node->data;
				
				xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
				if(stat(fname, &s) || s.st_mtime > last_config_check)
					terminate_connection(c, c->status.active);
				free(fname);
			}

			last_config_check = now;

			/* If StrictSubnet is set, expire deleted Subnets and read new ones in */

			if(strictsubnets) {
				subnet_t *subnet;

				for(node = subnet_tree->head; node; node = node->next) {
					subnet = node->data;
					subnet->expires = 1;
				}

				load_all_subnets();

				for(node = subnet_tree->head; node; node = next) {
					next = node->next;
					subnet = node->data;
					if(subnet->expires == 1) {
						send_del_subnet(everyone, subnet);
						if(subnet->owner->status.reachable)
							subnet_update(subnet->owner, subnet, false);
						subnet_del(subnet->owner, subnet);
					} else if(subnet->expires == -1) {
						subnet->expires = 0;
					} else {
						send_add_subnet(everyone, subnet);
						if(subnet->owner->status.reachable)
							subnet_update(subnet->owner, subnet, true);
					}
				}
			}

			/* Try to make outgoing connections */
			
			try_outgoing_connections();
		}
		
		/* Dump graph if wanted every 60 seconds*/

		if(last_graph_dump + 60 <= now) {
			dump_graph();
			last_graph_dump = now;
		}
	}

#ifdef HAVE_PSELECT
	/* Restore SIGHUP & SIGALARM mask */
	sigprocmask(SIG_SETMASK, &omask, NULL);
#endif

	return 0;
}
void send_channel_event(EVT_HANDLE evt, os_channel *channel)
{
    DWORD buffer_length = 0;
    PEVT_VARIANT properties_values = NULL;
    DWORD count = 0;
    EVT_HANDLE context = NULL;
    os_event event = {0};
    char final_msg[OS_MAXSTR];
    int result = 0;

    if ((context = EvtCreateRenderContext(count, NULL, EvtRenderContextSystem)) == NULL) {
        log2file(
            "%s: ERROR: Could not EvtCreateRenderContext() for (%s) which returned (%lu)",
            ARGV0,
            channel->evt_log,
            GetLastError());
        goto cleanup;
    }

    /* Make initial call to determine buffer size necessary */
    result = EvtRender(context,
                       evt,
                       EvtRenderEventValues,
                       0,
                       NULL,
                       &buffer_length,
                       &count);
    if (result != FALSE || GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
        log2file(
            "%s: ERROR: Could not EvtRender() to determine buffer size for (%s) which returned (%lu)",
            ARGV0,
            channel->evt_log,
            GetLastError());
        goto cleanup;
    }

    if ((properties_values = malloc(buffer_length)) == NULL) {
        log2file(
            "%s: ERROR: Could not malloc() memory to process event (%s) which returned [(%d)-(%s)]",
            ARGV0,
            channel->evt_log,
            errno,
            strerror(errno));
        goto cleanup;
    }

    if (!EvtRender(context,
                   evt,
                   EvtRenderEventValues,
                   buffer_length,
                   properties_values,
                   &buffer_length,
                   &count)) {
        log2file(
            "%s: ERROR: Could not EvtRender() for (%s) which returned (%lu)",
            ARGV0,
            channel->evt_log,
            GetLastError());
        goto cleanup;
    }

    event.name = get_property_value(&properties_values[EvtSystemChannel]);
    event.id = properties_values[EvtSystemEventID].UInt16Val;
    event.source = get_property_value(&properties_values[EvtSystemProviderName]);
    event.uid = properties_values[EvtSystemUserID].Type == EvtVarTypeNull ? NULL : properties_values[EvtSystemUserID].SidVal;
    event.computer = get_property_value(&properties_values[EvtSystemComputer]);
    event.time_created = properties_values[EvtSystemTimeCreated].FileTimeVal;
    event.keywords = properties_values[EvtSystemKeywords].Type == EvtVarTypeNull ? 0 : properties_values[EvtSystemKeywords].UInt64Val;
    event.level = properties_values[EvtSystemLevel].Type == EvtVarTypeNull ? -1 : properties_values[EvtSystemLevel].ByteVal;

    switch (event.level) {
        case WINEVENT_CRITICAL:
            event.category = "CRITICAL";
            break;
        case WINEVENT_ERROR:
            event.category = "ERROR";
            break;
        case WINEVENT_WARNING:
            event.category = "WARNING";
            break;
        case WINEVENT_INFORMATION:
            event.category = "INFORMATION";
            break;
        case WINEVENT_VERBOSE:
            event.category = "DEBUG";
            break;
        case WINEVENT_AUDIT:
            if (event.keywords & WINEVENT_AUDIT_FAILURE) {
                event.category = "AUDIT_FAILURE";
                break;
            } else if (event.keywords & WINEVENT_AUDIT_SUCCESS) {
                event.category = "AUDIT_SUCCESS";
                break;
            }
        default:
            event.category = "Unknown";
            break;
    }

    if ((event.timestamp = WinEvtTimeToString(event.time_created)) == NULL) {
        log2file(
            "%s: ERROR: Could not convert timestamp for (%s)",
            ARGV0,
            channel->evt_log);
        goto cleanup;
    }

    /* Determine user and domain */
    get_username_and_domain(&event);

    /* Get event log message */
    if ((event.message = get_message(evt, properties_values[EvtSystemProviderName].StringVal, EvtFormatMessageEvent)) == NULL) {
        log2file(
            "%s: ERROR: Could not get message for (%s)",
            ARGV0,
            channel->evt_log);
    } else {
        /* Format message */
        win_format_event_string(event.message);
    }

    snprintf(
        final_msg,
        sizeof(final_msg),
        "%s WinEvtLog: %s: %s(%d): %s: %s: %s: %s: %s",
        event.timestamp,
        event.name,
        event.category,
        event.id,
        event.source && strlen(event.source) ? event.source : "no source",
        event.user && strlen(event.user) ? event.user : "******",
        event.domain && strlen(event.domain) ? event.domain : "no domain",
        event.computer && strlen(event.computer) ? event.computer : "no computer",
        event.message && strlen(event.message) ? event.message : "(no message)"
    );

    if (SendMSG(logr_queue, final_msg, "WinEvtLog", LOCALFILE_MQ) < 0) {
        merror(QUEUE_SEND, ARGV0);
    }

    if (channel->bookmark_enabled) {
        update_bookmark(evt, channel);
    }

cleanup:
    free(properties_values);
    free_event(&event);

    if (context != NULL) {
        EvtClose(context);
    }

    return;
}
Beispiel #27
0
static PyObject * csolve_solve_episode(PyObject * self, PyObject * args)
{
  PyObject * physics_obj;
  PyObject * sta_list_obj;
  PyObject * det_list_obj;

  /* note: the physics object and the in_episode object are borrowed references
   * for the lifetime of this function call
   */
  if (!PyArg_ParseTuple(args, "OOO", &physics_obj, &sta_list_obj,
                        &det_list_obj))
    return NULL;

  Physics_t * physics = read_physics(physics_obj);

  int num_sta;
  Station_t * sta_list = read_sta_list(sta_list_obj, &num_sta);

  int num_det;
  Detection_t * det_list = read_det_list(det_list_obj, &num_det);

  /* initialize some cached values in the detections */
  init_det_list(physics, num_sta, sta_list, num_det, det_list);
  
  /* allocate a boolean list indicating if a detection number is to be skipped
   * initially this list is all False (because calloc clears memory to 0) */
  int * skip_detnums = (int *)calloc(num_det,  sizeof(int));

  PyObject * events_list_obj = PyList_New(0);
  PyObject * assocs_list_obj = PyList_New(0);

  while (1)
  {
    Event_t * event = find_best_remaining_event(physics, num_sta, sta_list,
                                                num_det, det_list,
                                                skip_detnums);

    if (NULL == event)
      break;

#ifdef VERBOSE
    print_event(event, num_sta);
    printf("\n");
#endif

    PyObject * event_obj = make_event_obj(event);

    PyList_Append(events_list_obj, event_obj);
    Py_DECREF(event_obj);

    PyObject * assoc_obj = make_assoc_obj(event, num_sta);

    PyList_Append(assocs_list_obj, assoc_obj);
    Py_DECREF(assoc_obj);
    
    free_event(event);
  }

  free(skip_detnums);
  
  free_physics(physics);

  free_sta_list(sta_list);

  free_det_list(det_list);

  /* we are stealing references to the events_list and assocs_list_obj
   * below by using "N" hence we don't need to DECREF them */
  return Py_BuildValue("NN", events_list_obj, assocs_list_obj);
}
Beispiel #28
0
static Event_t * find_best_remaining_event(const Physics_t * physics,
                                           int num_sta,
                                           const Station_t * sta_list,
                                           int num_det,
                                           const Detection_t * det_list,
                                           int * skip_detnums)
/*
  Finds a single event that best explains detections with the highest
  overall loglikelihood ratio. We are ignoring prior information and
  mis-detection probability in this version.

  This returns an event object with a list of detection numbers associated to
  it.

  The boolean array skip_detnums is updated to reflect the detections
  associated with the returned event object.
*/
{
  Event_t * best_event = NULL;
  
  /* The perturbation that we will apply to the slowness and azimuth
   * depend on the percentiles of their relevant distributions. Here
   * we first compute those percentiles between 10% and 90% */
  double PERCENTILES[NUMPERTURB];
  int percidx;
  for (percidx=0; percidx<NUMPERTURB; percidx++)
  {
    PERCENTILES[percidx] = .1 + percidx * (.9 - .1) / (NUMPERTURB-1);
  }
  
  /* go through each detection and invert it to get a suitable candidate */
  int inv_detidx;
  for (inv_detidx=0; inv_detidx < num_det; inv_detidx++)
  {
    const Detection_t * inv_det = det_list + inv_detidx;
    int staidx = inv_det->staidx;

#ifdef VERYVERBOSE
    printf("detidx %d noise log-likelihood %lf\n", inv_detidx,
           inv_det->noise_loglike);
#endif

    int sloidx;
    for (sloidx=0; sloidx<NUMPERTURB; sloidx++)
    {
      double delslow = laplace_ppf(PERCENTILES[sloidx], physics->mu_s[staidx],
                                   physics->theta_s[staidx]);
        
      int azidx;
      for (azidx=0; azidx<NUMPERTURB; azidx++)
      {
        double delaz = laplace_ppf(PERCENTILES[azidx], physics->mu_z[staidx],
                                   physics->theta_z[staidx]);
        
        Event_t * event = invert_detection(physics, num_sta, sta_list,
                                           inv_det, delslow, delaz);

        /* find the best set of detections for this event */
        find_best_detections(physics, num_sta, sta_list, num_det, det_list,
                             skip_detnums, event);

#ifdef VERYVERBOSE        
        printf("Inverted Event: ");
        print_event(event, num_sta);
        printf("\n");
#endif

        if ((event->sum_llratio > LLRATIO_THRESHOLD)
            && ((NULL == best_event) 
                || (event->sum_llratio > best_event->sum_llratio)))
        {
          if (NULL != best_event)
            free_event(best_event);
          
          best_event = event;
        }
        
        else
          free_event(event);
      }
    }
    
  }

  /* update skip_detnums with the detections of this best event */
  if (NULL != best_event)
  {
    int staidx;
    for (staidx=0; staidx < num_sta; staidx++)
    {
      if (best_event->sta_det[staidx] >= 0)
      {
        int detidx = best_event->sta_det[staidx];

        assert(detidx < num_det);
        
        skip_detnums[detidx] = 1;
      }
    }
  }
  
  return best_event;
}
Beispiel #29
0
/***************************************************************************** 
 * this function handles the direct memory access to the buffer
 * and copies objects to and from memory
 *****************************************************************************/
int dmarequest(const message_t *request, message_t **response_ptr) {
  unsigned int offset;
  /*
     int blockrequest = 0;
     */
  int verbose = 0;

  /* these are used for blocking the read requests */
  struct timeval tp;
  struct timespec ts;

  /* use a local variable for datasel (in GET_DAT) */
  datasel_t datasel;

  /* these are for typecasting */
  headerdef_t    *headerdef;
  datadef_t      *datadef;
  eventdef_t     *eventdef;
  eventsel_t     *eventsel;

  /* this will hold the response */
  message_t *response;
  response      = (message_t*)malloc(sizeof(message_t));

  /* check for "out of memory" problems */
  if (response == NULL) {
    *response_ptr = NULL;
    return -1;
  }
  response->def = (messagedef_t*)malloc(sizeof(messagedef_t));

  /* check for "out of memory" problems */
  if (response->def == NULL) {
    *response_ptr = NULL;
    free(response);
    return -1;
  }
  response->buf = NULL;
  /* the response should be passed to the calling function, where it should be freed */
  *response_ptr = response;

  if (verbose>1) print_request(request->def);

  switch (request->def->command) {

    case PUT_HDR:
      if (verbose>1) fprintf(stderr, "dmarequest: PUT_HDR\n");
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexdata);
      pthread_mutex_lock(&mutexevent);

      headerdef = (headerdef_t*)request->buf;
      if (verbose>1) print_headerdef(headerdef);

      /* delete the old header, data and events */
      free_header();
      free_data();
      free_event();

      /* store the header and re-initialize */
      header      = (header_t*)malloc(sizeof(header_t));
      DIE_BAD_MALLOC(header);
      header->def = (headerdef_t*)malloc(sizeof(headerdef_t));
      DIE_BAD_MALLOC(header->def);
      header->buf = malloc(headerdef->bufsize);
      DIE_BAD_MALLOC(header->buf);
      memcpy(header->def, request->buf, sizeof(headerdef_t));
      memcpy(header->buf, (char*)request->buf+sizeof(headerdef_t), headerdef->bufsize);
      header->def->nsamples = 0;
      header->def->nevents  = 0;

      init_data();
      init_event();

      response->def->version = VERSION;
      response->def->bufsize = 0;
      /* check whether memory could indeed be allocated */
      if (data!= NULL && data->buf != NULL && data->def != NULL) {
        response->def->command = PUT_OK;
      } else {
        /* let's at least tell the client that something's wrong */
        response->def->command = PUT_ERR;	
      }

      pthread_mutex_unlock(&mutexevent);
      pthread_mutex_unlock(&mutexdata);
      pthread_mutex_unlock(&mutexheader);
      break;

    case PUT_DAT:
      if (verbose>1) fprintf(stderr, "dmarequest: PUT_DAT\n");
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexdata);

      datadef = (datadef_t*)request->buf;
      if (verbose>1) print_datadef(datadef);
      if (verbose>2) print_buf(request->buf, request->def->bufsize);

      response->def->version = VERSION;
      response->def->bufsize = 0;
      if (request->def->bufsize < sizeof(datadef_t))
        response->def->command = PUT_ERR;
      else if (header==NULL || data==NULL)
        response->def->command = PUT_ERR;
      else if (header->def->nchans != datadef->nchans)
        response->def->command = PUT_ERR;
      else if (header->def->data_type != datadef->data_type)
        response->def->command = PUT_ERR;
      else if (datadef->nsamples > current_max_num_sample)
        response->def->command = PUT_ERR;
      else {
        unsigned int i;
        unsigned int wordsize = wordsize_from_type(header->def->data_type);
        unsigned int datasize = wordsize * datadef->nsamples * datadef->nchans;

        response->def->command = PUT_OK;

        if (wordsize == 0) {
          fprintf(stderr, "dmarequest: unsupported data type (%d)\n", datadef->data_type);
          response->def->command = PUT_ERR;
        } else if (datasize > datadef->bufsize || (datadef->bufsize + sizeof(datadef_t)) > request->def->bufsize) {
          fprintf(stderr, "dmarequest: invalid size definitions in PUT_DAT request\n");
          response->def->command = PUT_ERR;
        } else {

          /* record the time at which the data was received */
          if (clock_gettime(CLOCK_REALTIME, &putdat_clock) != 0) {
            perror("clock_gettime");
            return -1;
          }

          /* number of bytes per sample (all channels) is given by wordsize x number of channels */
          unsigned int chansize = wordsize * data->def->nchans;
          /* request_data points to actual data samples within the request, use char* for convenience */
          const char *request_data = (const char *) request->buf + sizeof(datadef_t);
          char *buffer_data = (char *)data->buf;

          for (i=0; i<datadef->nsamples; i++) {
            memcpy(buffer_data+(thissample*chansize), request_data+(i*chansize), chansize);
            header->def->nsamples++;
            thissample++;
            thissample = WRAP(thissample, current_max_num_sample);
          }
          /* Signal possibly waiting threads that we have received data */
          pthread_cond_broadcast(&getData_cond);
        }
      }

      pthread_mutex_unlock(&mutexdata);
      pthread_mutex_unlock(&mutexheader);
      break;

    case PUT_EVT:
      if (verbose>1) fprintf(stderr, "dmarequest: PUT_EVT\n");
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexevent);

      /* record the time at which the event was received */
      if (clock_gettime(CLOCK_REALTIME, &putevt_clock) != 0) {
        perror("clock_gettime");
        return -1;
      }

      /* Give an error message if there is no header, or if the given event array is defined badly */
      if (header==NULL || event==NULL || check_event_array(request->def->bufsize, request->buf) < 0) {
        response->def->version = VERSION;
        response->def->command = PUT_ERR;
        response->def->bufsize = 0;
      }
      else {	/* go over all events and store them one by one */
        response->def->version = VERSION;
        response->def->command = PUT_OK;
        response->def->bufsize = 0;

        offset = 0; /* this represents the offset of the event in the buffer */
        while (offset<request->def->bufsize) {
          FREE(event[thisevent].def);
          FREE(event[thisevent].buf);

          eventdef = (eventdef_t*)((char*)request->buf+offset);
          if (verbose>1) print_eventdef(eventdef);

          event[thisevent].def = (eventdef_t*)malloc(sizeof(eventdef_t));
          DIE_BAD_MALLOC(event[thisevent].def);
          memcpy(event[thisevent].def, (char*)request->buf+offset, sizeof(eventdef_t));

          if (event[thisevent].def->sample == EVENT_AUTO_SAMPLE) {
            /* automatically convert event->def->sample to current sample number */
            /* make some fine adjustment of the assigned sample number */
            double adjust = (putevt_clock.tv_sec - putdat_clock.tv_sec) + (double)(putevt_clock.tv_nsec - putdat_clock.tv_nsec) / 1000000000L;
            event[thisevent].def->sample = header->def->nsamples + (int)(header->def->fsample*adjust);
          }

          offset += sizeof(eventdef_t);
          event[thisevent].buf = malloc(eventdef->bufsize);
          DIE_BAD_MALLOC(event[thisevent].buf);
          memcpy(event[thisevent].buf, (char*)request->buf+offset, eventdef->bufsize);
          offset += eventdef->bufsize;
          if (verbose>1) print_eventdef(event[thisevent].def);
          thisevent++;
          thisevent = WRAP(thisevent, MAXNUMEVENT);
          header->def->nevents++;
        }
      }

      pthread_mutex_unlock(&mutexevent);
      pthread_mutex_unlock(&mutexheader);
      break;

    case GET_HDR:
      if (verbose>1) fprintf(stderr, "dmarequest: GET_HDR\n");
      if (header==NULL) {
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
        break;
      }

      pthread_mutex_lock(&mutexheader);

      response->def->version = VERSION;
      response->def->command = GET_OK;
      response->def->bufsize = 0;
      response->def->bufsize = append(&response->buf, response->def->bufsize, header->def, sizeof(headerdef_t));
      response->def->bufsize = append(&response->buf, response->def->bufsize, header->buf, header->def->bufsize);

      pthread_mutex_unlock(&mutexheader);
      break;

    case GET_DAT:
      if (verbose>1) fprintf(stderr, "dmarequest: GET_DAT\n");
      if (header==NULL || data==NULL) {
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
        break;
      }

      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexdata);

      if (request->def->bufsize) {
        /* the selection has been specified */
        memcpy(&datasel, request->buf, sizeof(datasel_t));
        /* If endsample is -1 read the buffer to the end */
        if(datasel.endsample == -1)
        {
          datasel.endsample = header->def->nsamples - 1;
        }
      }
      else {
        /* determine a valid selection */
        if (header->def->nsamples>current_max_num_sample) {
          /* the ringbuffer is completely full */
          datasel.begsample = header->def->nsamples - current_max_num_sample;
          datasel.endsample = header->def->nsamples - 1;
        }
        else {
          /* the ringbuffer is not yet completely full */
          datasel.begsample = 0;
          datasel.endsample = header->def->nsamples - 1;
        }
      }

      /*

      // if the read should block...
      if(blockrequest == 1)
      {
      // check whether data is available
      while((datasel.begsample >= (datasel.endsample+1)) || (datasel.endsample > header->def->nsamples - 1))
      {
      // if not unlock all mutexes
      pthread_mutex_unlock(&mutexdata);
      pthread_mutex_unlock(&mutexheader);

      // wait for the condition to be signaled
      pthread_mutex_lock(&getData_mutex);
      gettimeofday(&tp, NULL);
      ts.tv_sec = tp.tv_sec;
      ts.tv_nsec = tp.tv_usec * 1000;
      ts.tv_sec += 1;
      pthread_cond_timedwait(&getData_cond, &getData_mutex, &ts);
      pthread_mutex_unlock(&getData_mutex);

      // Lock the mutexes again
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexdata);
      if(datasel.begsample == (datasel.endsample+1))
      datasel.endsample = header->def->nsamples - 1;
      }
      }
      */

      if (verbose>1) print_headerdef(header->def);
      if (verbose>1) print_datasel(&datasel);

      if (datasel.begsample < 0 || datasel.endsample < 0) {
        fprintf(stderr, "dmarequest: err1\n");
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else if (datasel.begsample >= header->def->nsamples || datasel.endsample >= header->def->nsamples) {
        fprintf(stderr, "dmarequest: err2\n");
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else if ((header->def->nsamples - datasel.begsample) > current_max_num_sample) {
        fprintf(stderr, "dmarequest: err3\n");
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else {
        unsigned int wordsize = wordsize_from_type(data->def->data_type);
        if (wordsize==0) {
          fprintf(stderr, "dmarequest: unsupported data type (%d)\n", data->def->data_type);
          response->def->version = VERSION;
          response->def->command = GET_ERR;
          response->def->bufsize = 0;
        }  else {
          unsigned int n;
          response->def->version = VERSION;
          response->def->command = GET_OK;
          response->def->bufsize = 0;

          /* determine the number of samples to return */
          n = datasel.endsample - datasel.begsample + 1;

          response->buf = malloc(sizeof(datadef_t) + n*data->def->nchans*wordsize);
          if (response->buf == NULL) {
            /* not enough space for copying data into response */
            fprintf(stderr, "dmarequest: out of memory\n");
            response->def->command = GET_ERR;
          } 
          else {
            /* number of bytes per sample (all channels) */
            unsigned int chansize = data->def->nchans * wordsize;

            /* convenience pointer to start of actual data in response */
            char *resp_data = ((char *) response->buf) + sizeof(datadef_t);

            /* this is the location of begsample within the ringbuffer */
            unsigned int start_index = 	WRAP(datasel.begsample, current_max_num_sample);

            /* have datadef point into the freshly allocated response buffer and directly
               fill in the information */
            datadef = (datadef_t *) response->buf;
            datadef->nchans    = data->def->nchans;
            datadef->data_type = data->def->data_type;
            datadef->nsamples  = n;
            datadef->bufsize   = n*chansize;

            response->def->bufsize = sizeof(datadef_t) + datadef->bufsize;

            if (start_index + n <= current_max_num_sample) {
              /* we can copy everything in one go */
              memcpy(resp_data, (char*)(data->buf) + start_index*chansize, n*chansize);
            } else {
              /* need to wrap around at current_max_num_sample */
              unsigned int na = current_max_num_sample - start_index;
              unsigned int nb = n - na;

              memcpy(resp_data, (char*)(data->buf) + start_index*chansize, na*chansize);
              memcpy(resp_data + na*chansize, (char*)(data->buf), nb*chansize);

              /* printf("Wrapped around!\n"); */
            }
          }
        }
      }

      pthread_mutex_unlock(&mutexdata);
      pthread_mutex_unlock(&mutexheader);
      break;

    case GET_EVT:
      if (verbose>1) fprintf(stderr, "dmarequest: GET_EVT\n");
      if (header==NULL || event==NULL || header->def->nevents==0) {
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
        break;
      }

      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexevent);

      eventsel = (eventsel_t*)malloc(sizeof(eventsel_t));
      DIE_BAD_MALLOC(eventsel);

      /* determine the selection */
      if (request->def->bufsize) {
        /* the selection has been specified */
        memcpy(eventsel, request->buf, sizeof(eventsel_t));
      }
      else {
        /* determine a valid selection */
        if (header->def->nevents>MAXNUMEVENT) {
          /* the ringbuffer is completely full */
          eventsel->begevent = header->def->nevents - MAXNUMEVENT;
          eventsel->endevent = header->def->nevents - 1;
        }
        else {
          /* the ringbuffer is not yet completely full */
          eventsel->begevent = 0;
          eventsel->endevent = header->def->nevents - 1;
        }
      }

      if (verbose>1) print_headerdef(header->def);
      if (verbose>1) print_eventsel(eventsel);

      if (eventsel==NULL) {
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else if (eventsel->begevent < 0 || eventsel->endevent < 0) {
        fprintf(stderr, "dmarequest: err1\n");
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else if (eventsel->begevent >= header->def->nevents || eventsel->endevent >= header->def->nevents) {
        fprintf(stderr, "dmarequest: err2\n");
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else if ((header->def->nevents-eventsel->begevent) > MAXNUMEVENT) {
        fprintf(stderr, "dmarequest: err3\n");
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else {
        unsigned int j,n;

        response->def->version = VERSION;
        response->def->command = GET_OK;
        response->def->bufsize = 0;

        /* determine the number of events to return */
        n = eventsel->endevent - eventsel->begevent + 1;

        for (j=0; j<n; j++) {
          if (verbose>1) print_eventdef(event[WRAP(eventsel->begevent+j, MAXNUMEVENT)].def);
          response->def->bufsize = append(&response->buf, response->def->bufsize, event[WRAP(eventsel->begevent+j, MAXNUMEVENT)].def, sizeof(eventdef_t));
          response->def->bufsize = append(&response->buf, response->def->bufsize, event[WRAP(eventsel->begevent+j, MAXNUMEVENT)].buf, event[WRAP(eventsel->begevent+j, MAXNUMEVENT)].def->bufsize);
        }
      }

      FREE(eventsel);
      pthread_mutex_unlock(&mutexevent);
      pthread_mutex_unlock(&mutexheader);
      break;

    case FLUSH_HDR:
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexdata);
      pthread_mutex_lock(&mutexevent);
      if (header) {
        free_header();
        free_data();
        free_event();
        response->def->version = VERSION;
        response->def->command = FLUSH_OK;
        response->def->bufsize = 0;
      }
      else {
        response->def->version = VERSION;
        response->def->command = FLUSH_ERR;
        response->def->bufsize = 0;
      }
      pthread_mutex_unlock(&mutexevent);
      pthread_mutex_unlock(&mutexdata);
      pthread_mutex_unlock(&mutexheader);
      break;

    case FLUSH_DAT:
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexdata);
      if (header && data) {
        header->def->nsamples = thissample = 0;
        response->def->version = VERSION;
        response->def->command = FLUSH_OK;
        response->def->bufsize = 0;
      }
      else {
        response->def->version = VERSION;
        response->def->command = FLUSH_ERR;
        response->def->bufsize = 0;
      }
      pthread_mutex_unlock(&mutexdata);
      pthread_mutex_unlock(&mutexheader);
      break;

    case FLUSH_EVT:
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexevent);
      if (header && event) {
        unsigned int i;

        header->def->nevents = thisevent = 0;
        for (i=0; i<MAXNUMEVENT; i++) {
          FREE(event[i].def);
          FREE(event[i].buf);
        }
        response->def->version = VERSION;
        response->def->command = FLUSH_OK;
        response->def->bufsize = 0;
      }
      else {
        response->def->version = VERSION;
        response->def->command = FLUSH_ERR;
        response->def->bufsize = 0;
      }
      pthread_mutex_unlock(&mutexevent);
      pthread_mutex_unlock(&mutexheader);
      break;

    case WAIT_DAT:
      /* SK: This request means that the client wants to wait until
         MORE than waitdef_t.threshold.nsamples samples OR 
         MORE THAN waitdef_t.threshold.nevents events 
         are in the buffer, BUT 
         only for the time given in waitdef_t.milliseconds. 
         The response is just the number of samples and events 
         in the buffer as described by samples_events_t.
         */
      response->def->version = VERSION;
      if (header==NULL || request->def->bufsize!=sizeof(waitdef_t)) {
        response->def->command = WAIT_ERR;
        response->def->bufsize = 0;
      } else {
        int waiterr;
        waitdef_t *wd = (waitdef_t *) request->buf;
        samples_events_t *nret = malloc(sizeof(samples_events_t));
        UINT32_T nsmp, nevt;

        if (nret == NULL) {
          /* highly unlikely, but we cannot allocate a sample_event_t - return an error */
          response->def->command = WAIT_ERR;
          response->def->bufsize = 0;
          break;
        }
        /* Let response->buf point to the new sample_event_t structure */
        response->def->command = WAIT_OK;
        response->def->bufsize = sizeof(samples_events_t);
        response->buf = nret;

        /* get current number of samples */
        pthread_mutex_lock(&mutexheader);
        nsmp = header->def->nsamples;
        nevt = header->def->nevents;
        pthread_mutex_unlock(&mutexheader);

        if (wd->milliseconds == 0 || nsmp > wd->threshold.nsamples || nevt > wd->threshold.nevents) {
          /* the client doesn't want to wait, or
             we're already above the threshold: 
             return immediately */
          nret->nsamples = nsmp;
          nret->nevents = nevt;
          break;
        }
        gettimeofday(&tp, NULL);
        ts.tv_sec = tp.tv_sec + (wd->milliseconds/1000);
        ts.tv_nsec = 1000 * (tp.tv_usec + (wd->milliseconds % 1000)*1000);
        while (ts.tv_nsec >= 1000000000) {
          ts.tv_sec++;
          ts.tv_nsec-=1000000000;
        }

        /* FIXME: The getData condition variable is only triggered by incoming data, not events */
        do {
          pthread_mutex_lock(&getData_mutex);
          waiterr = pthread_cond_timedwait(&getData_cond, &getData_mutex, &ts);
          pthread_mutex_unlock(&getData_mutex);

          /* get current number of samples */
          pthread_mutex_lock(&mutexheader);
          nsmp = header->def->nsamples;
          nevt = header->def->nevents;
          pthread_mutex_unlock(&mutexheader);
        } while (nsmp <= wd->threshold.nsamples && nevt <= wd->threshold.nevents && waiterr==0);
        nret->nsamples = nsmp;
        nret->nevents = nevt;				
      }
      break;
    default:
      fprintf(stderr, "dmarequest: unknown command\n");
  }

  if (verbose>0) fprintf(stderr, "dmarequest: thissample = %u, thisevent = %u\n", thissample, thisevent);

  /* everything went fine */
  return 0;
}
Beispiel #30
0
/** Frees a hdr_field structure.
 * WARNING: it frees only parsed (and not name.s, body.s)
 */
void clean_hdr_field(struct hdr_field* const hf)
{
	void** h_parsed;

	if (hf->parsed){
		h_parsed=&hf->parsed; /* strict aliasing warnings workarround */
		switch(hf->type){
		/* headers with pkg alloc for parsed structure (alphabetic order) */
		case HDR_ACCEPT_T:
			pkg_free(hf->parsed);
			break;

		case HDR_ALLOW_T:
			free_allow_header(hf);
			break;

		case HDR_AUTHORIZATION_T:
			free_credentials((auth_body_t**)h_parsed);
			break;

		case HDR_CONTACT_T:
			free_contact((contact_body_t**)h_parsed);
			break;

		case HDR_CONTENTDISPOSITION_T:
			free_disposition( ((struct disposition**)h_parsed));
			break;

		case HDR_CSEQ_T:
			free_cseq(hf->parsed);
			break;

		case HDR_DATE_T:
			free_date(hf->parsed);
			break;

		case HDR_DIVERSION_T:
			free_to(hf->parsed);
			break;

		case HDR_EVENT_T:
			free_event((event_t**)h_parsed);
			break;

		case HDR_EXPIRES_T:
			free_expires((exp_body_t**)h_parsed);
			break;

		case HDR_FROM_T:
			free_to(hf->parsed);
			break;

		case HDR_IDENTITY_INFO_T:
			free_identityinfo(hf->parsed);
			break;

		case HDR_IDENTITY_T:
			free_identity(hf->parsed);
			break;

		case HDR_PAI_T:
			free_pai_ppi_body(hf->parsed);
			break;

		case HDR_PPI_T:
			free_pai_ppi_body(hf->parsed);
			break;

		case HDR_PROXYAUTH_T:
			free_credentials((auth_body_t**)h_parsed);
			break;

		case HDR_RECORDROUTE_T:
			free_rr((rr_t**)h_parsed);
			break;

		case HDR_REFER_TO_T:
			free_to(hf->parsed);
			break;

		case HDR_ROUTE_T:
			free_rr((rr_t**)h_parsed);
			break;

		case HDR_RPID_T:
			free_to(hf->parsed);
			break;

		case HDR_SESSIONEXPIRES_T:
			hdr_free_parsed(h_parsed);
			break;

		case HDR_SIPIFMATCH_T:
			free_sipifmatch((str **)h_parsed);
			break;

		case HDR_SUBSCRIPTION_STATE_T:
			free_subscription_state((subscription_state_t**)h_parsed);
			break;

		case HDR_SUPPORTED_T:
			hdr_free_parsed(h_parsed);
			break;

		case HDR_TO_T:
			free_to(hf->parsed);
			break;

		case HDR_VIA_T:
			free_via_list(hf->parsed);
			break;

		/* headers with no alloc for parsed structure */
		case HDR_CALLID_T:
		case HDR_MAXFORWARDS_T:
		case HDR_CONTENTTYPE_T:
		case HDR_CONTENTLENGTH_T:
		case HDR_RETRY_AFTER_T:
		case HDR_REQUIRE_T:
		case HDR_PROXYREQUIRE_T:
		case HDR_UNSUPPORTED_T:
		case HDR_ACCEPTLANGUAGE_T:
		case HDR_ORGANIZATION_T:
		case HDR_PRIORITY_T:
		case HDR_SUBJECT_T:
		case HDR_USERAGENT_T:
		case HDR_SERVER_T:
		case HDR_MIN_SE_T:
		case HDR_ACCEPTCONTACT_T:
		case HDR_ALLOWEVENTS_T:
		case HDR_CONTENTENCODING_T:
		case HDR_REFERREDBY_T:
		case HDR_REJECTCONTACT_T:
		case HDR_REQUESTDISPOSITION_T:
		case HDR_WWW_AUTHENTICATE_T:
		case HDR_PROXY_AUTHENTICATE_T:
		case HDR_PATH_T:
		case HDR_PRIVACY_T:
		case HDR_REASON_T:
			break;

		default:
			LOG(L_CRIT, "BUG: clean_hdr_field: unknown header type %d\n",
			    hf->type);
			break;
		}
	}
}