Пример #1
0
static int k_any(Ihandle *ih, int c)
{
  switch(c)
  {
  case K_m:
    IupSetGlobal("PARENTDIALOG", "_MAIN_DIALOG_TEST_");
    IupMessage("IupMessage Test", "Message Text\nSecond Line.");
    IupSetGlobal("PARENTDIALOG", NULL);
    break;
  case K_e:
    new_message("ERROR", NULL);
    break;
  case K_i:
    new_message("INFORMATION", NULL);
    break;
  case K_w:
    new_message("WARNING", "OKCANCEL");
    break;
  case K_q:
    new_message("QUESTION", "YESNO");
    break;
  case K_c:
    new_color();
    break;
  case K_f:
    new_font();
    break;
  case K_o:
    new_file("OPEN", 0);
    break;
  case K_O:
    new_file("OPEN", 1);
    break;
  case K_G:
    new_file("OPEN", 2);
    break;
  case K_s:
    new_file("SAVE", 0);
    break;
  case K_d:
    new_file("DIR", 0);
    break;
  case K_a:
    new_alarm();
    break;
  case K_g:
    new_getfile();
    break;
  case K_t:
    new_gettext();
    break;
  case K_l:
    new_list();
    break;
  case K_ESC:
    IupDestroy(ih);
    return IUP_IGNORE;
  }
  return IUP_DEFAULT;
}
Пример #2
0
static void handle_error_msg(struct compiler *c, char *str)
{
	int i, len;

	for (i = 0; str[i]; i++) {
		if (str[i] == '\n') {
			str[i] = 0;
			break;
		}
		if (str[i] == '\t')
			str[i] = ' ';
	}
	len = i;
	if (len == 0)
		return;

	for (i = 0; i < c->error_formats.count; i++) {
		const struct error_format *p = c->error_formats.ptrs[i];
		PTR_ARRAY(m);

		if (!regexp_exec_sub(&p->re, str, len, &m, 0))
			continue;
		if (!p->ignore) {
			struct message *msg = new_message(m.ptrs[p->msg_idx]);
			msg->file = p->file_idx < 0 ? NULL : xstrdup(m.ptrs[p->file_idx]);
			msg->u.location.line = p->line_idx < 0 ? 0 : atoi(m.ptrs[p->line_idx]);
			msg->u.location.column = p->column_idx < 0 ? 0 : atoi(m.ptrs[p->column_idx]);
			add_message(msg);
		}
		ptr_array_free(&m);
		return;
	}
	add_message(new_message(str));
}
void network_multiplexer_acceptclient_net(t_player *player,
					  t_client *client)
{
  char buffer[256];
  t_log_message msg;

  bzero(buffer, 256);
  player->client = client;
  g_core.network->max_fd = (g_core.network->max_fd <= client->sock[TCP]) ?
    (client->sock[TCP] + 1) : g_core.network->max_fd;
  FD_SET(client->sock[TCP], &g_core.network->fdset);
  FD_SET(client->sock[TCP], &g_core.network->wfdset);
  sprintf(buffer, "{%d} Connection of client on %s", client->sock[TCP],
	  client->get_host(client));
  init_logging_message(&msg, "Network", buffer, INFORMATION);
  network_logging(g_core.network->log, &msg);
  g_core.network->list_client->push_front(g_core.network->list_client, player);
  if (client->sock[TCP] >= (int)g_core.network->array_player_size)
    {
      g_core.network->array_player_size *= 2;
      g_core.network->array_player = realloc(g_core.network->array_player,
					     sizeof(t_player *) *
					     g_core.network->array_player_size);
    }
  g_core.network->array_player[client->sock[TCP]] = player;
  g_core.network->send_queue->push_back(g_core.network->send_queue,
					new_message(client->sock[TCP], "BIENVENUE\n"));
}
Пример #4
0
// A handler for the /ajax/send_message endpoint.
static void ajax_send_message(struct mg_connection *conn,
                              const struct mg_request_info *request_info) {
  struct message *message;
  struct session *session;
  char text[sizeof(message->text) - 1];
  int is_jsonp;

  mg_printf(conn, "%s", ajax_reply_start);
  is_jsonp = handle_jsonp(conn, request_info);

  get_qsvar(request_info, "text", text, sizeof(text));
  if (text[0] != '\0') {
    // We have a message to store. Write-lock the ringbuffer,
    // grab the next message and copy data into it.
    pthread_rwlock_wrlock(&rwlock);
    message = new_message();
    // TODO(lsm): JSON-encode all text strings
    session = get_session(conn);
    assert(session != NULL);
    my_strlcpy(message->text, text, sizeof(text));
    my_strlcpy(message->user, session->user, sizeof(message->user));
    pthread_rwlock_unlock(&rwlock);
  }

  mg_printf(conn, "%s", text[0] == '\0' ? "false" : "true");

  if (is_jsonp) {
    mg_printf(conn, "%s", ")");
  }
}
Пример #5
0
int new_reply(Router *router, Message *m, int toolid, MessageStatus st, 
              MessageMode mode, int reqrepid, int pattern_id, MessageDestroy_fptr fptr)
{
    int ret=0;
   
    ret=new_message(router,m,toolid,st,mode,pattern_id,fptr);
    
    if(-1 != ret)
    {
        RequestTool rt;        
        pthread_mutex_lock(&router->bindings_mutex);
        
        rt.reqrepid=reqrepid;
        if (!Glist_search(&router->request_tool_list,&rt,(void *)compare_reqrepid_func))
            ret=-1; // ERROR No request pending for this reply.
        else
        {
            m->type=REPLY;
            m->reqrepid=reqrepid;
            ret=0; // SUCCESS
        }
        pthread_mutex_unlock(&router->bindings_mutex);
    }
    return ret;
}
Пример #6
0
Файл: pg.c Проект: xrg/pg_top
PGconn *
connect_to_db(char *conninfo)
{
	static int	refresh = 0;
	PGconn	   *pgconn = NULL;

	pgconn = PQconnectdb(conninfo);
	if (PQstatus(pgconn) != CONNECTION_OK)
	{
		refresh = 1;
		new_message(MT_standout | MT_delayed, " %s", PQerrorMessage(pgconn));

		PQfinish(pgconn);
		return NULL;
	}
	else
	{
		/*
		 * FIXME: I don't know how expensive this is but I don't know how to
		 * get the header text to redisplay when it gets wipe out by the
		 * above's susequent new_message() calls.  The number of running
		 * processes seems to printed a litle funny when it is 0 too.
		 */
		if (refresh == 1)
		{
			reset_display();
			refresh = 0;
		}
	}
	return pgconn;
}
Пример #7
0
// La función de entrada de un thread siempre debe tener este prototipo
// pero esto no impide recibir argumentos "complejos" y devolver cualquier tipo 
// de resultado
void* client_thread (void* ptr) {
	struct client_arg* arg;
	int i;
	message_t* msg;
	
	arg = (struct client_arg*) ptr;
	fprintf(logfile,"NEW client of type %d with period %d \n",arg->m_type, arg->period);
	
	for (i=0;i<arg->n_messages; i++) {
		if (  ( msg=new_message(arg->m_type ) )  == NULL ) {
			fprintf(stderr,"Error when creating  message\n");
		pthread_exit(NULL);
		}
		
		// Post message to mailbox
		mbox_post( arg->mbox, msg);
		
		
		// Wait for server to finish the work
		sys_sem_wait(msg->op_completed);
		
		
		// We can process and free the message
		process_answer(msg);
		free_message(msg);
		
		// Sleep for period seconds before the next message
		sleep(arg->period);
		
	}
	return NULL;
}
Пример #8
0
static void* handle_receive(void* qp)
{
	qpos_t* pointer = (qpos_t*)qp;
	if (pointer)
	{
		char buf[MESSAGE_LIMIT];
	    int n;
	    size_t pos, used = 0;
	    char skip = 0;
		struct pollfd poller;
	    poller.fd = *pointer->cfd;
	    poller.events = POLLRDNORM;
	    int loop = 1;
	    while(loop) 
	    { 
	        poll(&poller, 1, INFTIM);
	        if (poller.revents & POLLRDNORM)
	        {
	        	n = read(poller.fd, buf + used, MESSAGE_LIMIT - used);
	        	if (n <= 0) break;
	        	used += n;
	        	pos = 0;
	        	while (pos < used) 
	        	{
		        	for (; pos < used && buf[pos] != '\n'; pos++);
		        	if (pos < used) 
		        	{
			            if (skip) 
			            {
			                skip = 0;
			            } else 
			            {
			            	new_message(buf, pos + 1);
			            }
			            used -= (pos + 1);
			            memmove(buf, buf + pos + 1, used);
			        } 
			        else if (pos == MESSAGE_LIMIT) 
			        {
			            skip = 1;
			            used = 0;
			        }
			    }
	        }
	        pthread_rwlock_rdlock(&global_lock);
	        if (pointer->pos == QUEUE_BACKLOG) loop = 0;
	        pthread_rwlock_unlock(&global_lock);
	    }
	    printf("HR: someone disconnected\n");
	    pthread_rwlock_wrlock(&global_lock);
	    pointer->pos = QUEUE_BACKLOG;
	    pthread_rwlock_unlock(&global_lock);
	}
	return NULL;
}
Пример #9
0
static void send_server_message(const char *fmt, ...) {
  va_list ap;
  struct message *message;

  pthread_rwlock_wrlock(&rwlock);
  message = new_message();
  message->user[0] = '\0';  // Empty user indicates server message
  va_start(ap, fmt);
  vsnprintf(message->text, sizeof(message->text), fmt, ap);
  va_end(ap);

  pthread_rwlock_unlock(&rwlock);
}
Пример #10
0
int new_notification(Router *router, Message *m, int toolid, MessageStatus st, 
                     MessageMode mode, int pattern_id, MessageDestroy_fptr fptr)
{
    int ret=0;
    
    ret=new_message(router,m,toolid,st,mode,pattern_id,fptr);
    if(-1 != ret)
    {
        m->type=NOTIFICATION;
        m->reqrepid=-1;
        ret=0; // SUCCESS
    }
    return ret;
}
Пример #11
0
/**
 * @brief Callback called from control thread.
 *
 * This function is a callback called from control thread to change some parameters of
 * compression.
 *
 * @param[in] receiver pointer to the compress module
 * @param[in] msg      message passed to callback
 * @returns            response to the message
 */
static struct response *compress_change_callback(struct module *receiver, struct message *msg)
{
    struct msg_change_compress_data *data =
        (struct msg_change_compress_data *) msg;
    compress_state_proxy *proxy = receiver->priv_data;

    /* In this case we are only changing some parameter of compression.
     * This means that we pass the parameter to compress driver. */
    if(data->what == CHANGE_PARAMS) {
        platform_spin_lock(&proxy->spin);
        struct response *resp = NULL;
        for(unsigned int i = 0; i < proxy->ptr->state_count; ++i) {
            if(resp) {
                resp->deleter(resp);
            }
            struct msg_change_compress_data *tmp_data =
                (struct msg_change_compress_data *)
                new_message(sizeof(struct msg_change_compress_data));
            tmp_data->what = data->what;
            strncpy(tmp_data->config_string, data->config_string,
                    sizeof(tmp_data->config_string) - 1);
            resp = send_message_to_receiver(proxy->ptr->state[i],
                                            (struct message *) tmp_data);
        }
        platform_spin_unlock(&proxy->spin);

        free_message(msg);

        return resp;
    } else {
        struct compress_state_real *new_state;
        char config[1024];
        strncpy(config, data->config_string, sizeof(config));

        int ret = compress_init_real(&proxy->mod, config, &new_state);
        if(ret == 0) {
            struct compress_state_real *old = proxy->ptr;
            platform_spin_lock(&proxy->spin);
            proxy->ptr = new_state;
            platform_spin_unlock(&proxy->spin);
            compress_done_real(old);

            return new_response(RESPONSE_OK, NULL);
        }

        return new_response(RESPONSE_INT_SERV_ERR, NULL);
    }
}
Пример #12
0
int new_request(Router *router, Message *m, int toolid, MessageStatus st, 
                MessageMode mode, int pattern_id, MessageDestroy_fptr fptr)
{
    int ret=0;
    
    ret=new_message(router,m,toolid,st,mode,pattern_id,fptr);
    if(-1 != ret)
    {
        m->type=REQUEST;
        pthread_mutex_lock(&router->bindings_mutex);
        m->reqrepid=router->request_reply_counter++;
        pthread_mutex_unlock(&router->bindings_mutex);
        ret=0; // SUCCESS
    }
    return ret;
}
Пример #13
0
void NLog::append_to_log(LogMessage::Type type, bool fromServer,
                       const QString & message)
{
  QString header = "[ %1 ][ %2 ] ";
  QString msg;

  header = header.arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
  header = header.arg(fromServer ? "Server" : "Client");

  msg = message;
  msg.replace('\n', QString("\n%1").arg(header));
  msg.prepend(header);

  emit new_message(msg, type);

  if(type == LogMessage::EXCEPTION)
    emit new_exception(message);
}
Пример #14
0
int main(int argc, char *argv[])
{
  (void) argc;
  (void) argv;
  ssize_t res;
  
  if(!new_message(&msg)){
    res = write(STDERR_FILENO, cant_alloc_msg, sizeof(cant_alloc_msg));
    (void) res;
    return 1;
  }

  if(!init_speech()){
    res = write(STDERR_FILENO, cant_init_msg, sizeof(cant_init_msg));
    (void) res;
    return 1;
  }
  res = write(STDOUT_FILENO, "\0", 1);
  if(res < 0){
    //would write problem message, but we can't send anyway
    return 1;
  }

  while(1){
    if(!read_message(STDIN_FILENO, msg)){
      res = write(STDERR_FILENO, cant_read_msg, sizeof(cant_read_msg));
      (void) res;
      break;
    }
    say(str_from_msg(msg));
    while(!spoken(0.0f)){
      usleep(200000);
    }
    res = write(STDOUT_FILENO, "\0", 1);
    if(res < 0){
      //would write problem message, but we can't send anyway
      break;
    }
  }
  
  close_speech();
  cleanup_speech();
  return 0;
}
Пример #15
0
static int
mbox_quick_get_message (mu_mailbox_t mailbox, mu_message_qid_t qid,
			mu_message_t *pmsg)
{
  int status;
  mbox_data_t mud = mailbox->data;
  mbox_message_t mum;
  mu_off_t offset;
  
  if (mailbox == NULL || qid2off (qid, &offset)
      || !(mailbox->flags & MU_STREAM_QACCESS))
    return EINVAL;

  if (mud->messages_count == 0)
    {
      status = mbox_scan1 (mailbox, offset, 0);
      if (status != 0)
	return status;
      if (mud->messages_count == 0)
	return MU_ERR_NOENT;
    }

  /* Quick access mode retrieves only one message */
  mum = mud->umessages[0]; 

  /* Check if we already have it and verify if it is the right one. */
  if (mum->message)
    {
      char *vqid;
      status = mu_message_get_qid (mum->message, &vqid);
      if (status)
	return status;
      status = strcmp (qid, vqid);
      free (vqid);
      if (status)
	return MU_ERR_EXISTS;
      if (pmsg)
	*pmsg = mum->message;
      return 0;
    }

  return new_message (mailbox, mum, pmsg);
}
Пример #16
0
static int
mbox_get_message (mu_mailbox_t mailbox, size_t msgno, mu_message_t *pmsg)
{
  int status;
  mbox_data_t mud = mailbox->data;
  mbox_message_t mum;

  /* Sanity checks.  */
  if (pmsg == NULL)
    return MU_ERR_OUT_PTR_NULL;
  if (mud == NULL)
    return EINVAL;

  /* If we did not start a scanning yet do it now.  */
  if (mud->messages_count == 0)
    {
      status = mbox_scan0 (mailbox, 1, NULL, 0);
      if (status != 0)
	return status;
    }

  /* Second sanity: check the message number.  */
  if (!(mud->messages_count > 0
	&& msgno > 0
	&& msgno <= mud->messages_count))
    return EINVAL;

  mum = mud->umessages[msgno - 1];

  /* Check if we already have it.  */
  if (mum->message)
    {
      if (pmsg)
	*pmsg = mum->message;
      return 0;
    }

  MU_DEBUG2 (mailbox->debug, MU_DEBUG_TRACE1, "mbox_get_message (%s, %lu)\n",
	     mud->name, (unsigned long) msgno);

  return new_message (mailbox, mum, pmsg);
}
Пример #17
0
ExprPtr IoBlock::call(ArgList args, std::size_t num_args)
{
    if (!empty())
    {
        char const* errorPoint = "before eval";
        IoMessage* m;
        try
        {
            m = new_message(io_target, "IoBlock");
            errorPoint = "while adding args";

            for (int i = 0; i < num_args; ++i)
                add_arg(m, args[i]);

            errorPoint = "on activate";
            IoObject* io_obj = activate(m);
            errorPoint = "create IoObjectExpr";

            TypeIndex from_type = FromIoTypeInfo::create_index(get_type_name(io_obj));
            if (type_system->has_type(from_type))
                return create_expr(io_obj, from_type);
            else
                return Term<IoObject*>::create(io_obj);
        }
        catch (Iocaste::ScriptException const& exc)
        {
            // TODO:  assoc addn'l info w/exp.
            throw;
        }
        // TODO:  Create LikeMagic exception object.
        catch (std::exception const& e)
        {
            throw Iocaste::IoStateError(io_block, std::string() + "Error in IoBlock " + errorPoint + ": " + e.what(), m);
        }
    }
    else
    {
        throw std::logic_error("Tried to eval an empty block.");
    }
}
Пример #18
0
int shutdown_server() {
	message_t* msg;

	serv_up = 0;
	
	// Create NONE message
	if (  ( msg=new_message(NONE ) )  == NULL ) {
		fprintf(logfile,"Error when creating NONE message\n");
		return -1;
	}
	
	// Post it  message to mailbox
	mbox_post( mbox, msg);

	// Wait for server to finish the work
	counting_sem_wait(msg->op_completed);
	
	// Ignore answer
	if (msg != NULL) free_message(msg);
	
	return 0;
}
Пример #19
0
static void
socket_message(struct skynet_context *ctx, struct package *P, const struct skynet_socket_message * smsg) {
	switch (smsg->type) {
	case SKYNET_SOCKET_TYPE_CONNECT:
		if (P->init == 0 && smsg->id == P->fd) {
			skynet_send(ctx, 0, P->manager, PTYPE_TEXT, 0, "SUCC", 4);
			P->init = 1;
		}
		break;
	case SKYNET_SOCKET_TYPE_CLOSE:
	case SKYNET_SOCKET_TYPE_ERROR:
		if (P->init == 0 && smsg->id == P->fd) {
			skynet_send(ctx, 0, P->manager, PTYPE_TEXT, 0, "FAIL", 4);
			P->init = 1;
		}
		if (smsg->id != P->fd) {
			skynet_error(ctx, "Invalid fd (%d), should be (%d)", smsg->id, P->fd);
		} else {
			// todo: log when SKYNET_SOCKET_TYPE_ERROR
			response(ctx, P);
			service_exit(ctx, P);
		}
		break;
	case SKYNET_SOCKET_TYPE_DATA:
		new_message(P, (const uint8_t *)smsg->buffer, smsg->ud);
		skynet_free(smsg->buffer);
		response(ctx, P);
		break;
	case SKYNET_SOCKET_TYPE_WARNING:
		skynet_error(ctx, "Overload on %d", P->fd);
		break;
	default:
		// ignore
		break;
	}
}
Пример #20
0
	void Environment::run(RunningContext *context)
	{
		const Instruction &ins = m_ipos;
		m_context = context;
		if (!context)
		{
			m_running = false;
		} else if (!m_running)
		{
			clear_vstore();
			TRACE_PRINTF(TRACE_VM, TRACE_INFO, "Entering running state with %p\n", context);
			m_running = true;
			const SourcePos *last_pos = NULL; // used for debug output below.
			const Instruction *ipos;
			while (m_context && (ipos = m_context->next()))
			{
				size_t output = -1;
				size_t expected = -1;
#				define CHECK_STACK(in, out) TRACE_OUT(TRACE_VM, TRACE_SPAM) {\
					assert(m_context->stack_count() >= (size_t)(in)); \
					if ((out) != -1) { assert((long)(expected = m_context->stack_count() - (size_t)(in) + (size_t)(out)) >= 0); } \
					tprintf("Stack info: before(%d), in(%d), out(%d), expected(%d)\n", (int)m_context->stack_count(), (int)(in), (int)(out), (int)expected); \
					output = (out); \
				}

				m_ipos = *ipos;

				TRACE_DO(TRACE_VM, TRACE_INFO) {
					const SourcePos &pos = m_context->m_instructions->source_pos(ipos);
					if (!last_pos || *last_pos != pos)
						tprintf("Source Position: %s:%d:%d (%s)\n", pos.file.c_str(), (int)pos.line_num, (int)pos.column, pos.annotation.c_str());
					last_pos = &pos;
				}
				TRACE_OUT(TRACE_VM, TRACE_SPAM) {
					tprintf("Instruction: %s@%d\n",
						inspect(ins).c_str(),
						(int)(ipos - &*m_context->instructions().begin())
						);
					tprintf("Stack: %d deep", (int)m_context->stack_count());

					const Value *it;
					for (it = m_context->stack_begin(); it != m_context->stack_pos(); it++)
					{
						tprintf("\n   %s", inspect(*it).c_str());
					}
					tprintf(" <--\n");
				}

				switch(ins.instruction)
				{
				case NOP:
					CHECK_STACK(0, 0);
					break;
				case DEBUGGER:
					CHECK_STACK(0, 0);
					{
						String *action = ptr<String>(ins.arg1);
						if (*action == "interrupt")
						{
							DO_DEBUG __asm__("int3");
						} else if (*action == "trace_enable") {
							trace_mute = false;
						} else if (*action == "trace_disable") {
							trace_mute = true;
						}
					}
					break;

				case POP:
					CHECK_STACK(1, 0);
					m_context->pop();
					break;
				case PUSH:
					CHECK_STACK(0, 1);
					m_context->push(ins.arg1);
					break;
				case SWAP: {
					CHECK_STACK(2, 2);
					Value tmp1 = m_context->top();
					m_context->pop();
					Value tmp2 = m_context->top();
					m_context->pop();
					m_context->push(tmp1);
					m_context->push(tmp2);
					}
					break;
				case DUP_TOP:
					CHECK_STACK(1, 2);
					m_context->push(m_context->top());
					break;

				case IS: {
					CHECK_STACK(1, 1);
					Value res = bvalue(ins.arg1 == m_context->top());
					m_context->pop();
					m_context->push(res);
					}
					break;
				case IS_EQ: {
					CHECK_STACK(2, 1);
					Value first = m_context->top();
					m_context->pop();
					Value second = m_context->top();
					m_context->pop();
					m_context->push(bvalue(first == second));
					}
					break;
				case IS_NOT: {
					CHECK_STACK(1, 1);
					Value res = bvalue(ins.arg1 != m_context->top());
					m_context->pop();
					m_context->push(res);
					}
					break;
				case IS_NOT_EQ:{
					CHECK_STACK(2, 1);
					Value first = m_context->top();
					m_context->pop();
					Value second = m_context->top();
					m_context->pop();
					m_context->push(bvalue(first != second));
					}
					break;
				case JMP:
					CHECK_STACK(0, 0);

					GC::safe_point();

					m_context->jump(ins.cache.machine_num);
					break;
				case JMP_IF:
					CHECK_STACK(1, 0);

					GC::safe_point();

					if (is_truthy(m_context->top()))
						m_context->jump(ins.cache.machine_num);
					m_context->pop();
					break;
				case JMP_IF_NOT:
					CHECK_STACK(1, 0);

					GC::safe_point();

					if (!is_truthy(m_context->top()))
						m_context->jump(ins.cache.machine_num);
					m_context->pop();
					break;

				case LEXICAL_CLEAN_SCOPE: {
					CHECK_STACK(0, 0);
					VariableFrame *frame = new_variable_frame(m_context->m_instructions);
					m_context->new_scope(frame);
					}
					break;
				case LEXICAL_LINKED_SCOPE: {
					CHECK_STACK(0, 0);
					VariableFrame *frame = new_variable_frame(m_context->m_instructions);
					frame->link_frame(m_context->m_lexicalvars);
					m_context->new_scope(frame);
					}
					break;
				case FRAME_GET: {
					CHECK_STACK(0, 1);
					size_t frameid = (size_t)ins.cache.machine_num;
					TRACE_PRINTF(TRACE_VM, TRACE_SPAM, "Getting frame var %s (%d)\n", ptr<String>(ins.arg1)->c_str(), (int)frameid);
					m_context->push(m_context->get_framevar(frameid));
					}
					break;
				case FRAME_SET: {
					CHECK_STACK(1, 0);
					size_t frameid = (size_t)ins.cache.machine_num;
					TRACE_PRINTF(TRACE_VM, TRACE_SPAM, "Setting frame var %s (%d) to: %s\n", ptr<String>(ins.arg1)->c_str(), (int)frameid, inspect(m_context->top()).c_str());
					m_context->set_framevar(frameid, m_context->top());
					m_context->pop();
					}
					break;
				case LOCAL_GET: {
					CHECK_STACK(0, 1);
					size_t localid = (size_t)ins.cache.machine_num;
					TRACE_PRINTF(TRACE_VM, TRACE_SPAM, "Getting local var %s (%d)\n", ptr<String>(ins.arg1)->c_str(), (int)localid);
					m_context->push(m_context->get_localvar(localid));
					}
					break;
				case LOCAL_SET: {
					CHECK_STACK(1, 0);
					size_t localid = (size_t)ins.cache.machine_num;
					TRACE_PRINTF(TRACE_VM, TRACE_SPAM, "Setting local var %s (%d) to: %s\n", ptr<String>(ins.arg1)->c_str(), (int)localid, inspect(m_context->top()).c_str());
					m_context->set_localvar(localid, m_context->top());
					m_context->pop();
					}
					break;
				case LEXICAL_GET: {
					CHECK_STACK(0, 1);
					size_t depth = ins.arg1.machine_num;
					size_t localid = (size_t)ins.cache.machine_num;
					TRACE_PRINTF(TRACE_VM, TRACE_SPAM, "lexical_get %u@%u: %i\n", (unsigned)localid, (unsigned)depth, type(m_context->get_lexicalvar(localid, depth)));
					if (depth == 0)
						m_context->push(m_context->get_lexicalvar(localid));
					else
						m_context->push(m_context->get_lexicalvar(localid, depth));
					}
					break;
				case LEXICAL_SET: {
					CHECK_STACK(1, 0);
					size_t depth = ins.arg1.machine_num;
					size_t localid = (size_t)ins.cache.machine_num;
					TRACE_PRINTF(TRACE_VM, TRACE_SPAM, "lexical_set %u@%u: %i\n", (unsigned)localid, (unsigned)depth, type(m_context->top()));
					if (depth == 0)
						m_context->set_lexicalvar(localid, m_context->top());
					else
						m_context->set_lexicalvar(localid, depth, m_context->top());
					m_context->pop();
					}
					break;

				case CHANNEL_NEW: {
					CHECK_STACK(0, 1);
					const Value &octx = vstore(value(m_context));
					RunnableContext *nctx = new_context(octx);
					nctx->jump(ins.cache.machine_num);
					m_context->push(value(nctx));
					clear_vstore();
					}
					break;
				case CHANNEL_SPECIAL:
					CHECK_STACK(0, 1);
					m_context->push(special_channel(*ptr<String>(ins.arg1)));
					break;
				case CHANNEL_SEND: {
					CHECK_STACK(3, -1);

					GC::safe_point();

					const Value &val = vstore(m_context->top()); m_context->pop();
					const Value &ret = vstore(m_context->top()); m_context->pop();
					const Value &channel = vstore(m_context->top()); m_context->pop();

					// A context that's been channel_sended from should never be returned to,
					// so invalidate it.
					m_context->invalidate();
					channel_send(this, channel, val, ret);
					clear_vstore();
					}
					break;
				case CHANNEL_CALL:{
					CHECK_STACK(2, -1);

					GC::safe_point();

					const Value &val = vstore(m_context->top()); m_context->pop();
					const Value &channel = vstore(m_context->top()); m_context->pop();
					const Value &ret = vstore(value(m_context));

					channel_send(this, channel, val, ret);
					clear_vstore();
					}
					break;
				case CHANNEL_RET:{
					CHECK_STACK(2, -1);
					const Value &val = vstore(m_context->top()); m_context->pop();
					const Value &channel = vstore(m_context->top()); m_context->pop();

					// A context that's been channel_reted from should never be returned to,
					// so invalidate it.
					m_context->invalidate();
					channel_send(this, channel, val, value(&no_return_ctx));
					clear_vstore();
					}
					break;

				case MESSAGE_NEW: {
					long long id = ins.cache.machine_num;
					long long sysarg_count = ins.arg2.machine_num, sysarg_counter = sysarg_count - 1;
					long long arg_count = ins.arg3.machine_num, arg_counter = arg_count - 1;
					CHECK_STACK(sysarg_count + arg_count, 1);

					Message *msg = new_message(id, sysarg_count, arg_count);

					while (arg_count > 0 && arg_counter >= 0)
					{
						msg->args()[arg_counter] = m_context->top();
						m_context->pop();
						--arg_counter;
					}
					while (sysarg_count > 0 && sysarg_counter >= 0)
					{
						msg->sysargs()[sysarg_counter] = m_context->top();
						m_context->pop();
						--sysarg_counter;
					}

					m_context->push(value(msg));
					}
					break;
				case MESSAGE_SPLAT: {
					CHECK_STACK(2, 1);
					const Tuple &tuple = *ptr<Tuple>(m_context->top()); m_context->pop();
					const Message &msg = *ptr<Message>(m_context->top()); m_context->pop();

					Message *nmsg = new_message(msg.m_id, msg.sysarg_count(), msg.arg_count() + tuple.size());
					std::copy(msg.sysargs(), msg.sysargs_end(), nmsg->sysargs());
					std::copy(msg.args(), msg.args_end(), nmsg->args());
					std::copy(tuple.begin(), tuple.end(), nmsg->args() + msg.arg_count());
					m_context->push(value(nmsg));
					}
					break;
				case MESSAGE_ADD: {
					long long count = ins.arg1.machine_num, counter = 0;
					CHECK_STACK(1 + count, 1);
					const Message &msg = *ptr<Message>(*(m_context->stack_pos() - 1 - count));

					Message *nmsg = new_message(msg.m_id, msg.sysarg_count(), msg.arg_count() + count);
					std::copy(msg.sysargs(), msg.sysargs_end(), nmsg->sysargs());
					std::copy(msg.args(), msg.args_end(), nmsg->args());

					Message::iterator out = nmsg->args() + msg.arg_count();
					while (count > 0 && counter < count)
					{
						*out++ = m_context->top();
						m_context->pop();
						++counter;
					}
					m_context->pop(); // this is the message we pulled directly off the stack before.

					m_context->push(value(nmsg));
					}
					break;
				case MESSAGE_COUNT:
					CHECK_STACK(1, 2);
					m_context->push(value((long long)ptr<Message>(m_context->top())->arg_count()));
					break;
				case MESSAGE_IS:
					CHECK_STACK(1, 2);
					m_context->push(bvalue(ptr<Message>(m_context->top())->m_id == (uint64_t)ins.cache.machine_num));
					break;
				case MESSAGE_IS_PROTO:
					CHECK_STACK(1, 2);
					m_context->push(bvalue(ptr<Message>(m_context->top())->protocol_id() == (uint64_t)ins.cache.machine_num));
					break;
				case MESSAGE_ID:
					{
					CHECK_STACK(1, 2);
					Message *msg = ptr<Message>(m_context->top());
					m_context->push(value((long long)msg->m_id));
					}
					break;
				case MESSAGE_SPLIT_ID:
					{
					CHECK_STACK(1, 3);
					Message *msg = ptr<Message>(m_context->top());
					m_context->push(value((long long)msg->message_id()));
					m_context->push(value((long long)msg->protocol_id()));
					}
					break;
				case MESSAGE_CHECK:
					CHECK_STACK(1, 1);
					if (!is(m_context->top(), MESSAGE))
					{
						m_context->pop();
						m_context->push(False);
					}
					break;
				case MESSAGE_FORWARD: {
					CHECK_STACK(1, 1);

					long long id = ins.cache.machine_num;
					const Message &msg = *ptr<Message>(m_context->top());
					Message *nmsg = new_message(id, msg.sysarg_count(), msg.arg_count() + 1);
					std::copy(msg.sysargs(), msg.sysargs_end(), nmsg->sysargs());
					nmsg->args()[0] = value(new_string(msg.name()));
					std::copy(msg.args(), msg.args_end(), nmsg->args() + 1);
					m_context->pop();
					m_context->push(value(nmsg));
					break;
				}
				case MESSAGE_SYS_PREFIX: {
					long long count = ins.arg1.machine_num, counter = 0;
					CHECK_STACK(1 + count, 1);

					const Value *sdata = m_context->stack_pos() - 1 - count;
					const Message &msg = *ptr<Message>(*sdata++);
					Message *nmsg = new_message(msg.m_id, msg.sysarg_count() + count, msg.arg_count());
					Message::iterator to = nmsg->sysargs();
					while (counter++ < count)
					{
						*to++ = *sdata++;
					}
					std::copy(msg.sysargs(), msg.sysargs_end(), to);
					std::copy(msg.args(), msg.args_end(), nmsg->args());
					while (--counter != 0)
					{
						m_context->pop();
					}
					m_context->pop(); // message we read off stack before.
					m_context->push(value(nmsg));
					break;
				}
				case MESSAGE_SYS_UNPACK: {
					long long count = ins.arg1.machine_num, pos = count - 1;
					CHECK_STACK(1, 1 + count);

					const Message *msg = ptr<Message>(m_context->top());
					Message::const_iterator args = msg->sysargs();
					long long len = (long long)msg->sysarg_count();

					while (pos >= 0)
					{
						if (pos >= len)
							m_context->push(Undef);
						else
							m_context->push(args[pos]);

						pos -= 1;
					}
					}
					break;
				case MESSAGE_UNPACK: {
					long long first_count = ins.arg1.machine_num, first_counter = 0;
					long long splat = ins.arg2.machine_num;
					long long last_count = ins.arg3.machine_num, last_counter = 0;
					CHECK_STACK(1, 1 + first_count + last_count + (splat?1:0));

					const Message *msg = ptr<Message>(m_context->top());
					Message::const_iterator args = msg->args();
					long long len = (long long)msg->arg_count(), pos = len - 1;

					while (last_counter < last_count && pos >= first_count)
					{
						if (pos >= len)
							m_context->push(Nil);
						else
							m_context->push(args[pos]);

						pos -= 1;
						last_counter += 1;
					}

					if (splat != 0)
					{
						if (pos >= first_count)
						{
							Tuple *splat_tuple = new_tuple(pos - first_count + 1);
							Tuple::iterator out = splat_tuple->end();
							while (pos >= first_count)
							{
								--out;
								*out = args[pos];
								pos -= 1;
							}
							m_context->push(value(splat_tuple));
						} else {
							m_context->push(value(new_tuple(0)));
						}
					}

					pos = first_count - 1;

					while (first_counter < first_count && pos >= 0)
					{
						if (pos >= len)
							m_context->push(Nil);
						else
							m_context->push(args[pos]);

						pos -= 1;
						first_counter += 1;
					}
					}
					break;

				case STRING_COERCE: {
					const Value &coerce = ins.arg1;
					const Value &val = vstore(m_context->top());
					if (is(val, STRING))
					{
						CHECK_STACK(1, 2);
						// push a nil like we called the method.
						m_context->push(Nil);
					} else {
						CHECK_STACK(1, -1);
						m_context->pop();
						channel_send(this, val, value(new_message(coerce)), value(m_context));
					}
					}
					clear_vstore();
					break;

				case STRING_NEW: {
					long long count = ins.arg1.machine_num, counter = 0;
					CHECK_STACK(count, 1);
					const Value *sp = m_context->stack_pos() - 1;
					size_t len = 0;
					while (count > 0 && counter < count)
					{
						assert(is(sp[-counter], STRING));
						len += ptr<String>(sp[-counter])->length();
						++counter;
					}
					String *res = new_string(len);
					String::iterator out = res->begin();
					counter = 0;
					while (count > 0 && counter < count)
					{
						const String *val = ptr<String>(m_context->top());
						out = std::copy(val->begin(), val->end(), out);
						m_context->pop();
						++counter;
					}
					m_context->push(value(res));
					}
					break;

				case TUPLE_NEW: {
					long long count = ins.arg1.machine_num, counter = 0;
					CHECK_STACK(count, 1);
					Tuple *tuple = new_tuple(count);
					Tuple::iterator out = tuple->begin();
					while (count > 0 && counter < count)
					{
						*out++ = m_context->top();
						m_context->pop();
						++counter;
					}
					m_context->push(value(tuple));
					}
					break;
				case TUPLE_SPLAT: {
					CHECK_STACK(2, 1);
					const Tuple *tuple2 = ptr<Tuple>(m_context->top()); m_context->pop();
					const Tuple *tuple1 = ptr<Tuple>(m_context->top()); m_context->pop();
					Tuple *tuple = join_tuple(tuple1, tuple2);
					m_context->push(value(tuple));
					}
					break;
				case TUPLE_UNPACK: {
					long long first_count = ins.arg1.machine_num, first_counter = 0;
					long long splat = ins.arg2.machine_num;
					long long last_count = ins.arg3.machine_num, last_counter = 0;
					CHECK_STACK(1, 1 + first_count + last_count + (splat?1:0));

					const Tuple &tuple = *ptr<Tuple>(m_context->top());
					long long len = tuple.size(), pos = tuple.size() - 1;
					while (last_counter < last_count && pos >= first_count)
					{
						if (pos >= len)
							m_context->push(Nil);
						else
							m_context->push(tuple[pos]);

						pos -= 1;
						last_counter += 1;
					}

					if (splat != 0)
					{
						if (pos >= first_count)
						{
							Tuple *splat_tuple = new_tuple(pos - first_count + 1);
							Tuple::iterator out = splat_tuple->end();
							while (pos >= first_count)
							{
								--out;
								*out = tuple[pos];
								pos -= 1;
							}
							m_context->push(value(splat_tuple));
						} else {
							m_context->push(value(new_tuple(0)));
						}
					}

					pos = first_count - 1;

					while (first_counter < first_count && pos >= 0)
					{
						if (pos >= len)
							m_context->push(Nil);
						else
							m_context->push(tuple[pos]);

						pos -= 1;
						first_counter += 1;
					}
					}
					break;
				default:
					printf("Panic! Unknown instruction %d\n", ins.instruction);
					exit(1);
				}

				TRACE_OUT(TRACE_VM, TRACE_SPAM) {
					tprintf("Output: %d", (int)output);
					if ((long)output > 0)
					{
						const Value *it = std::max(
							m_context->stack_begin(), m_context->stack_pos() - output);
						for (; it != m_context->stack_pos(); it++)
						{
							tprintf("\n   %s", inspect(*it).c_str());
						}
					}
					tprintf(" <--\n");
					tprintf("----------------\n");
				}
Пример #21
0
int main(int argc, char *argv[])
{
	int errn;
	string *str;
	int complete = -1;
	int i;
	long ans;
	long logintimeout = 20;
	char *s;
	char *password;
	char *username;

	if(argc < 4)
	{
		fprintf(stderr, "Usage: %s user password connecstring\n", argv[0]);
		exit(1);
	}

	if((mes = new_message(0)) == NULL)
	{
		fprintf(stderr, "%s: Cannot open message queue\n", argv[0]);
		exit(1);
	}


	/*
	 * I believe a fork duplicates malloced stuff, I am in the poo if it does not :-)
	 */
	errn = fork();

	if(errn == -1)
	{
		fprintf(stderr, "%s: Cannot fork child process\n", argv[0]);
		exit(1);
	}
	else if(errn)
	{
/*
 * This is the parent - which behaves like clien
 */

		/*
		 * Initially just a status message is snt back, zero string length 
		 *
		 * Still needs a string to put it into
		 */


		str = new_string();
		
		if(message_receive(mes, str, &complete, MES_SERVER_TO_CLIENT) < 0)
		{
			fprintf(stderr, "%s: %s\n", argv[0], string_s(str));
			message_destroy(mes);
			message_delete(mes);
			string_delete(str);
			exit(1);
		}
		else
		{
			printf("%d\n",message_id(mes)) ;
			message_delete(mes);
			string_delete(str);
			exit(0);
		}
	}
/*
 * All parents have exited now
 */

/*
 * This is all a child
 */

	/*
	 * I think I need to do this here...
	 * I do not fully understand why, it just works!
	 * otherwise shell parent hangs!
	 */

	setsid();
	if(fork()) exit(0);
	close(0);
	close(1);
	close(2);

	/*
	 * We are in daemon mode now
	 */

	/*
	 * open the database
	 */

	str = new_string();

	for(i=3;i<argc;i++)
	{
		string_cat(str, argv[i]);
		if(i < argc - 1) string_cat_c(str, ' ');
	}

	username = strdup(argv[1]);
	password = strdup(argv[2]);

	wipe(argv[2]);
	wipe(argv[1]);

	ans = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &(env));
	if((ans != SQL_SUCCESS) && (ans != SQL_SUCCESS_WITH_INFO))
	{
		message_status(mes, 127, "ODBC: Cannot allocate environment handle\n", MES_SERVER_TO_CLIENT);
		message_delete(mes);
		free(username);
		free(password);
		exit(1);
	}

	ans = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 

	if ((ans != SQL_SUCCESS) && (ans != SQL_SUCCESS_WITH_INFO))
	{
		SQLFreeHandle(SQL_HANDLE_ENV, env);
		message_status(mes, 127, "ODBC: Cannot set environment handle attributes\n", MES_SERVER_TO_CLIENT);
		message_delete(mes);
		exit(1);
	}

	/* 2. allocate connection handle, set timeout */

	ans = SQLAllocHandle(SQL_HANDLE_DBC, env, &(hdbc)); 

	if ((ans != SQL_SUCCESS) && (ans != SQL_SUCCESS_WITH_INFO))
	{
		SQLFreeHandle(SQL_HANDLE_ENV, env);
		message_status(mes, 127, "ODBC: Cannot allocate database handle\n", MES_SERVER_TO_CLIENT);
		message_delete(mes);
		free(username);
		free(password);
		exit(1);
	}

	/*
 	 * TODO - Parameterize ODBC_TIMEOUT as environment variable
	 */

	s = getenv("ODBC_TIMEOUT");
	if(s != NULL)
	{
		if(*s)
		{
			logintimeout = atol(s);
		}
	}

	SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (SQLPOINTER)logintimeout, 0);

	/* 3. Connect to the datasource  */

	ans = SQLConnect(hdbc, (SQLCHAR*) string_s(str), SQL_NTS,
                                     (SQLCHAR*) username, SQL_NTS,
                                     (SQLCHAR*) password, SQL_NTS);

	if ((ans != SQL_SUCCESS) && (ans != SQL_SUCCESS_WITH_INFO))
	{
		message_status(mes, 127, "ODBC: Cannot connect to database\n", MES_SERVER_TO_CLIENT);
		message_delete(mes);
/*
		SQLGetDiagRec(SQL_HANDLE_DBC, V_OD_hdbc,1, 
		              V_OD_stat, &V_OD_err,V_OD_msg,100,&V_OD_mlen);
		printf("%s (%d)\n",V_OD_msg,V_OD_err);
 */
		SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
		SQLFreeHandle(SQL_HANDLE_ENV, env);
		free(username);
		free(password);
		exit(1);
	}


	/*
	 * Transmit to parent that we are hunky dory
	 */

	message_status(mes, 0, "", MES_SERVER_TO_CLIENT);

	/*
	 * We are open for business - Lets go
 	 */

	mainloop();

	/*
	 * At the end, tidy up
	 */

	SQLDisconnect(hdbc);
	SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
	SQLFreeHandle(SQL_HANDLE_ENV, env);

	message_destroy(mes);
	message_delete(mes);

	free(username);
	free(password);

	exit(0);
}
Пример #22
0
static void
load_rss(cups_array_t *rss,		/* I - RSS messages */
         const char   *filename)	/* I - File to load */
{
  FILE		*fp;			/* File pointer */
  char		line[4096],		/* Line from file */
		*subject,		/* Subject */
		*text,			/* Text */
		*link_url,		/* Link URL */
		*start,			/* Start of element */
		*end;			/* End of element */
  time_t	event_time;		/* Event time */
  int		sequence_number;	/* Sequence number */
  int		in_item;		/* In an item */
  _cups_rss_t	*msg;			/* New message */


  if ((fp = fopen(filename, "r")) == NULL)
  {
    if (errno != ENOENT)
      fprintf(stderr, "ERROR: Unable to open %s: %s\n", filename,
              strerror(errno));

    return;
  }

  subject         = NULL;
  text            = NULL;
  link_url        = NULL;
  event_time      = 0;
  sequence_number = 0;
  in_item         = 0;

  while (fgets(line, sizeof(line), fp))
  {
    if (strstr(line, "<item>"))
      in_item = 1;
    else if (strstr(line, "</item>") && in_item)
    {
      if (subject && text)
      {
        msg = new_message(sequence_number, subject, text, link_url,
	                  event_time);

        if (msg)
	  cupsArrayAdd(rss, msg);

      }
      else
      {
        if (subject)
	  free(subject);

	if (text)
	  free(text);

	if (link_url)
	  free(link_url);
      }

      subject         = NULL;
      text            = NULL;
      link_url        = NULL;
      event_time      = 0;
      sequence_number = 0;
      in_item         = 0;
    }
    else if (!in_item)
      continue;
    else if ((start = strstr(line, "<title>")) != NULL)
    {
      start += 7;
      if ((end = strstr(start, "</title>")) != NULL)
      {
        *end    = '\0';
	subject = strdup(start);
      }
    }
    else if ((start = strstr(line, "<description>")) != NULL)
    {
      start += 13;
      if ((end = strstr(start, "</description>")) != NULL)
      {
        *end = '\0';
	text = strdup(start);
      }
    }
    else if ((start = strstr(line, "<link>")) != NULL)
    {
      start += 6;
      if ((end = strstr(start, "</link>")) != NULL)
      {
        *end     = '\0';
	link_url = strdup(start);
      }
    }
    else if ((start = strstr(line, "<pubDate>")) != NULL)
    {
      start += 9;
      if ((end = strstr(start, "</pubDate>")) != NULL)
      {
        *end       = '\0';
	event_time = httpGetDateTime(start);
      }
    }
    else if ((start = strstr(line, "<guid>")) != NULL)
      sequence_number = atoi(start + 6);
  }

  if (subject)
    free(subject);

  if (text)
    free(text);

  if (link_url)
    free(link_url);

  fclose(fp);
}
Пример #23
0
int main(int argc, char *argv[])
{
	int errn;
	string *str;
	int complete = -1;
	int i;

	if(argc < 2)
	{
		fprintf(stderr, "Usage: %s connecstring\n", argv[0]);
		exit(1);
	}

	if((mes = new_message(0)) == NULL)
	{
		fprintf(stderr, "%s: Cannot open message queue\n", argv[0]);
		exit(1);
	}


	/*
	 * I believe a fork duplicates malloced stuff, I am in the poo if it does not :-)
	 */
	errn = fork();

	if(errn == -1)
	{
		fprintf(stderr, "%s: Cannot fork child process\n", argv[0]);
		exit(1);
	}
	else if(errn)
	{
/*
 * This is the parent - which behaves like clien
 */

		/*
		 * Initially just a status message is snt back, zero string length 
		 *
		 * Still needs a string to put it into
		 */


		str = new_string();
		
		if(message_receive(mes, str, &complete, MES_SERVER_TO_CLIENT) < 0)
		{
			fprintf(stderr, "%s: %s\n", argv[0], string_s(str));
			message_destroy(mes);
			message_delete(mes);
			string_delete(str);
			exit(1);
		}
		else
		{
			printf("%d\n",message_id(mes)) ;
			message_delete(mes);
			string_delete(str);
			exit(0);
		}
	}
/*
 * All parents have exited now
 */

/*
 * This is all a child
 */

	/*
	 * I think I need to do this here...
	 * I do not fully understand why, it just works!
	 * otherwise shell parent hangs!
	 */

	setsid();
	if(fork()) exit(0);
	close(0);
	close(1);
	close(2);

	/*
	 * We are in daemon mode now
	 */

	/*
	 * open the database
	 */

	str = new_string();

	for(i=1;i<argc;i++)
	{
		string_cat(str, argv[i]);
		if((!strncasecmp(argv[i], "password", 8))
		 || (!strncasecmp(argv[i], "user", 4))
		 || (!strncasecmp(argv[i], "useriname", 8)))
			wipe(argv[i]);
		if(i < argc - 1) string_cat_c(str, ' ');
	}

	sqldb = PQconnectdb(string_s(str));
	string_delete(str);

	if(sqldb == NULL)
	{
		message_status(mes, 127, "Error allocating connection\n", MES_SERVER_TO_CLIENT);
		message_delete(mes);
		exit(1);
	}
	if (PQstatus(sqldb) != CONNECTION_OK)
	{
		char ws[64];
		snprintf(ws, 63, "Error opening postgres %s/%s\n", PQhost(sqldb), PQdb(sqldb));
		ws[63] = 0;
		message_status(mes, 127, ws, MES_SERVER_TO_CLIENT);
		PQfinish(sqldb);
		message_delete(mes);
		exit(1);
	}

	/*
	 * Transmit to parent that we are hunky dory
	 */

	message_status(mes, 0, "", MES_SERVER_TO_CLIENT);

	/*
	 * We are open for business - Lets go
 	 */

	mainloop();

	/*
	 * At the end, tidy up
	 */

	PQfinish(sqldb);
	message_destroy(mes);
	message_delete(mes);
	exit(0);
}
Пример #24
0
int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line arguments */
     char *argv[])			/* I - Command-line arguments */
{
  int		i;			/* Looping var */
  ipp_t		*event;			/* Event from scheduler */
  ipp_state_t	state;			/* IPP event state */
  char		scheme[32],		/* URI scheme ("rss") */
		username[256],		/* Username for remote RSS */
		host[1024],		/* Hostname for remote RSS */
		resource[1024],		/* RSS file */
		*options;		/* Options */
  int		port,			/* Port number for remote RSS */
		max_events;		/* Maximum number of events */
  http_t	*http;			/* Connection to remote server */
  http_status_t	status;			/* HTTP GET/PUT status code */
  char		filename[1024],		/* Local filename */
		newname[1024];		/* filename.N */
  cups_lang_t	*language;		/* Language information */
  ipp_attribute_t *printer_up_time,	/* Timestamp on event */
		*notify_sequence_number,/* Sequence number */
		*notify_printer_uri;	/* Printer URI */
  char		*subject,		/* Subject for notification message */
		*text,			/* Text for notification message */
		link_url[1024],		/* Link to printer */
		link_scheme[32],	/* Scheme for link */
		link_username[256],	/* Username for link */
		link_host[1024],	/* Host for link */
		link_resource[1024];	/* Resource for link */
  int		link_port;		/* Link port */
  cups_array_t	*rss;			/* RSS message array */
  _cups_rss_t	*msg;			/* RSS message */
  char		baseurl[1024];		/* Base URL */
  fd_set	input;			/* Input set for select() */
  struct timeval timeout;		/* Timeout for select() */
  int		changed;		/* Has the RSS data changed? */
  int		exit_status;		/* Exit status */


  fprintf(stderr, "DEBUG: argc=%d\n", argc);
  for (i = 0; i < argc; i ++)
    fprintf(stderr, "DEBUG: argv[%d]=\"%s\"\n", i, argv[i]);

 /*
  * See whether we are publishing this RSS feed locally or remotely...
  */

  if (httpSeparateURI(HTTP_URI_CODING_ALL, argv[1], scheme, sizeof(scheme),
                      username, sizeof(username), host, sizeof(host), &port,
		      resource, sizeof(resource)) < HTTP_URI_OK)
  {
    fprintf(stderr, "ERROR: Bad RSS URI \"%s\"!\n", argv[1]);
    return (1);
  }

  max_events = 20;

  if ((options = strchr(resource, '?')) != NULL)
  {
    *options++ = '\0';

    if (!strncmp(options, "max_events=", 11))
    {
      max_events = atoi(options + 11);

      if (max_events <= 0)
        max_events = 20;
    }
  }

  rss = cupsArrayNew((cups_array_func_t)compare_rss, NULL);

  if (host[0])
  {
   /*
    * Remote feed, see if we can get the current file...
    */

    int	fd;				/* Temporary file */


    if ((rss_password = strchr(username, ':')) != NULL)
      *rss_password++ = '\0';

    cupsSetPasswordCB(password_cb);
    cupsSetUser(username);

    if ((fd = cupsTempFd(filename, sizeof(filename))) < 0)
    {
      fprintf(stderr, "ERROR: Unable to create temporary file: %s\n",
              strerror(errno));

      return (1);
    }

    if ((http = httpConnect(host, port)) == NULL)
    {
      fprintf(stderr, "ERROR: Unable to connect to %s on port %d: %s\n",
              host, port, strerror(errno));

      close(fd);
      unlink(filename);

      return (1);
    }

    status = cupsGetFd(http, resource, fd);

    close(fd);

    if (status != HTTP_OK && status != HTTP_NOT_FOUND)
    {
      fprintf(stderr, "ERROR: Unable to GET %s from %s on port %d: %d %s\n",
	      resource, host, port, status, httpStatus(status));

      httpClose(http);
      unlink(filename);

      return (1);
    }

    strlcpy(newname, filename, sizeof(newname));

    httpAssembleURI(HTTP_URI_CODING_ALL, baseurl, sizeof(baseurl), "http",
                    NULL, host, port, resource);
  }
  else
  {
    const char	*cachedir,		/* CUPS_CACHEDIR */
		*server_name,		/* SERVER_NAME */
		*server_port;		/* SERVER_PORT */


    http = NULL;

    if ((cachedir = getenv("CUPS_CACHEDIR")) == NULL)
      cachedir = CUPS_CACHEDIR;

    if ((server_name = getenv("SERVER_NAME")) == NULL)
      server_name = "localhost";

    if ((server_port = getenv("SERVER_PORT")) == NULL)
      server_port = "631";

    snprintf(filename, sizeof(filename), "%s/rss%s", cachedir, resource);
    snprintf(newname, sizeof(newname), "%s.N", filename);

    httpAssembleURIf(HTTP_URI_CODING_ALL, baseurl, sizeof(baseurl), "http",
                     NULL, server_name, atoi(server_port), "/rss%s", resource);
  }

 /*
  * Load the previous RSS file, if any...
  */

  load_rss(rss, filename);

  changed = cupsArrayCount(rss) == 0;

 /*
  * Localize for the user's chosen language...
  */

  language = cupsLangDefault();

 /*
  * Read events and update the RSS file until we are out of events.
  */

  for (exit_status = 0, event = NULL;;)
  {
    if (changed)
    {
     /*
      * Save the messages to the file again, uploading as needed...
      */

      if (save_rss(rss, newname, baseurl))
      {
	if (http)
	{
	 /*
          * Upload the RSS file...
	  */

          if ((status = cupsPutFile(http, resource, filename)) != HTTP_CREATED)
            fprintf(stderr, "ERROR: Unable to PUT %s from %s on port %d: %d %s\n",
	            resource, host, port, status, httpStatus(status));
	}
	else
	{
	 /*
          * Move the new RSS file over top the old one...
	  */

          if (rename(newname, filename))
            fprintf(stderr, "ERROR: Unable to rename %s to %s: %s\n",
	            newname, filename, strerror(errno));
	}

	changed = 0;
      }
    }

   /*
    * Wait up to 30 seconds for an event...
    */

    timeout.tv_sec  = 30;
    timeout.tv_usec = 0;

    FD_ZERO(&input);
    FD_SET(0, &input);

    if (select(1, &input, NULL, NULL, &timeout) < 0)
      continue;
    else if (!FD_ISSET(0, &input))
    {
      fprintf(stderr, "DEBUG: %s is bored, exiting...\n", argv[1]);
      break;
    }

   /*
    * Read the next event...
    */

    event = ippNew();
    while ((state = ippReadFile(0, event)) != IPP_DATA)
    {
      if (state <= IPP_IDLE)
        break;
    }

    if (state == IPP_ERROR)
      fputs("DEBUG: ippReadFile() returned IPP_ERROR!\n", stderr);

    if (state <= IPP_IDLE)
      break;

   /*
    * Collect the info from the event...
    */

    printer_up_time        = ippFindAttribute(event, "printer-up-time",
                                              IPP_TAG_INTEGER);
    notify_sequence_number = ippFindAttribute(event, "notify-sequence-number",
                                	      IPP_TAG_INTEGER);
    notify_printer_uri     = ippFindAttribute(event, "notify-printer-uri",
                                	      IPP_TAG_URI);
    subject                = cupsNotifySubject(language, event);
    text                   = cupsNotifyText(language, event);

    if (printer_up_time && notify_sequence_number && subject && text)
    {
     /*
      * Create a new RSS message...
      */

      if (notify_printer_uri)
      {
        httpSeparateURI(HTTP_URI_CODING_ALL,
	                notify_printer_uri->values[0].string.text,
			link_scheme, sizeof(link_scheme),
                        link_username, sizeof(link_username),
			link_host, sizeof(link_host), &link_port,
		        link_resource, sizeof(link_resource));
        httpAssembleURI(HTTP_URI_CODING_ALL, link_url, sizeof(link_url),
	                "http", link_username, link_host, link_port,
			link_resource);
      }

      msg = new_message(notify_sequence_number->values[0].integer,
                        xml_escape(subject), xml_escape(text),
			notify_printer_uri ? xml_escape(link_url) : NULL,
			printer_up_time->values[0].integer);

      if (!msg)
      {
        fprintf(stderr, "ERROR: Unable to create message: %s\n",
	        strerror(errno));
        exit_status = 1;
	break;
      }

     /*
      * Add it to the array...
      */

      cupsArrayAdd(rss, msg);

      changed = 1;

     /*
      * Trim the array as needed...
      */

      while (cupsArrayCount(rss) > max_events)
      {
        msg = cupsArrayFirst(rss);

	cupsArrayRemove(rss, msg);

	delete_message(msg);
      }
    }

    if (subject)
      free(subject);

    if (text)
      free(text);

    ippDelete(event);
    event = NULL;
  }

 /*
  * We only get here when idle or error...
  */

  ippDelete(event);

  if (http)
  {
    unlink(filename);
    httpClose(http);
  }

  return (exit_status);
}
/* virtual */
void LLPluginProcessChild::receivePluginMessage(const std::string &message)
{
	LL_DEBUGS("Plugin") << "Received from plugin: " << message << LL_ENDL;
	
	if(mBlockingRequest)
	{
		// 
		LL_ERRS("Plugin") << "Can't send a message while already waiting on a blocking request -- aborting!" << LL_ENDL;
	}
	
	// Incoming message from the plugin instance
	bool passMessage = true;

	// FIXME: how should we handle queueing here?
	
	// Intercept certain base messages (responses to ones sent by this class)
	{
		// Decode this message
		LLPluginMessage parsed;
		parsed.parse(message);
		
		if(parsed.hasValue("blocking_request"))
		{
			mBlockingRequest = true;
		}

		std::string message_class = parsed.getClass();
		if(message_class == "base")
		{
			std::string message_name = parsed.getName();
			if(message_name == "init_response")
			{
				// The plugin has finished initializing.
				setState(STATE_RUNNING);

				// Don't pass this message up to the parent
				passMessage = false;
				
				LLPluginMessage new_message(LLPLUGIN_MESSAGE_CLASS_INTERNAL, "load_plugin_response");
				LLSD versions = parsed.getValueLLSD("versions");
				new_message.setValueLLSD("versions", versions);
				
				if(parsed.hasValue("plugin_version"))
				{
					std::string plugin_version = parsed.getValue("plugin_version");
					new_message.setValueLLSD("plugin_version", plugin_version);
				}

				// Let the parent know it's loaded and initialized.
				sendMessageToParent(new_message);
			}
			else if(message_name == "shm_remove_response")
			{
				// Don't pass this message up to the parent
				passMessage = false;

				std::string name = parsed.getValue("name");
				sharedMemoryRegionsType::iterator iter = mSharedMemoryRegions.find(name);				
				if(iter != mSharedMemoryRegions.end())
				{
					// detach the shared memory region
					iter->second->detach();
					
					// and remove it from our map
					mSharedMemoryRegions.erase(iter);
					
					// Finally, send the response to the parent.
					LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_INTERNAL, "shm_remove_response");
					message.setValue("name", name);
					sendMessageToParent(message);
				}
				else
				{
					LL_WARNS("Plugin") << "shm_remove_response for unknown memory segment!" << LL_ENDL;
				}
			}
		}
		else if (message_class == LLPLUGIN_MESSAGE_CLASS_INTERNAL)
		{
			bool flush = false;
			std::string message_name = parsed.getName();
			if(message_name == "shutdown")
			{
				// The plugin is finished.
				setState(STATE_UNLOADING);
				flush = true;
			}
			else if (message_name == "flush")
			{
				flush = true;
				passMessage = false;
			}
			if (flush)
			{
				flushMessages();
			}
		}
	}
	
	if(passMessage)
	{
		LL_DEBUGS("Plugin") << "Passing through to parent: " << message << LL_ENDL;
		writeMessageRaw(message);
	}
	
	while(mBlockingRequest)
	{
		// The plugin wants to block and wait for a response to this message.
		sleep(mSleepTime);	// this will pump the message pipe and process messages

		if(mBlockingResponseReceived || mSocketError != APR_SUCCESS || (mMessagePipe == NULL))
		{
			// Response has been received, or we've hit an error state.  Stop waiting.
			mBlockingRequest = false;
			mBlockingResponseReceived = false;
		}
	}
}
Пример #26
0
int main(int argc, char *argv[])
{
	int errn;
	string *str;
	int complete = -1;
	int i;

	
	char *sqlname[] = {
		"_dummy",
		"host",
		"user",
		"password",
		"dbname",
		"port",
		"socket",
		"flag"
	};

	sqlarg *sarg;


	/*
	 * Username and password may be in the connection string
	 */

	long flag = 0;
	unsigned int port = 0;

	MYSQL *tdb;

	if(argc < 2)
	{
		fprintf(stderr, "Usage: %s connecstring\n", argv[0]);
		exit(1);
	}

	if((mes = new_message(0)) == NULL)
	{
		fprintf(stderr, "%s: Cannot open message queue\n", argv[0]);
		exit(1);
	}


	/*
	 * I believe a fork duplicates malloced stuff, I am in the poo if it does not :-)
	 */
	errn = fork();

	if(errn == -1)
	{
		fprintf(stderr, "%s: Cannot fork child process\n", argv[0]);
		exit(1);
	}
	else if(errn)
	{
/*
 * This is the parent - which behaves like clien
 */

		/*
		 * Initially just a status message is snt back, zero string length 
		 *
		 * Still needs a string to put it into
		 */


		str = new_string();
		
		if(message_receive(mes, str, &complete, MES_SERVER_TO_CLIENT) < 0)
		{
			fprintf(stderr, "%s: %s\n", argv[0], string_s(str));
			message_destroy(mes);
			message_delete(mes);
			string_delete(str);
			exit(1);
		}
		else
		{
			printf("%d\n",message_id(mes)) ;
			message_delete(mes);
			string_delete(str);
			exit(0);
		}
	}
/*
 * All parents have exited now
 */

/*
 * This is all a child
 */

	/*
	 * I think I need to do this here...
	 * I do not fully understand why, it just works!
	 * otherwise shell parent hangs!
	 */

	setsid();
	if(fork()) exit(0);
	close(0);
	close(1);
	close(2);

	/*
	 * We are in daemon mode now
	 */

	/*
	 * open the database
	 */

	str = new_string();

	for(i=1;i<argc;i++)
	{
		string_cat(str, argv[i]);
		if((!strncasecmp(argv[i], "password", 8))
		 || (!strncasecmp(argv[i], "user", 4))
		 || (!strncasecmp(argv[i], "username", 8)))
			wipe(argv[i]);
		if(i < argc - 1) string_cat_c(str, ' ');
	}

	sarg = new_sqlarg(sqlname, string_s(str), SMYSQL_PARAMETERS);

	string_delete(str);

	if(sarg == NULL)
	{
		message_status(mes, 127, "Error allocating string parameters\n", MES_SERVER_TO_CLIENT);
		message_delete(mes);
		exit(1);
	}

	if(sqlargi(sarg, SMYSQL_PORT) != NULL) port = atoi(sqlargi(sarg, SMYSQL_PORT));
	if(sqlargi(sarg, SMYSQL_FLAG) != NULL) flag = atol(sqlargi(sarg, SMYSQL_FLAG));


	sqldb = mysql_init(NULL);
	if(sqldb == NULL)
	{
		message_status(mes, 127, "Error allocating connection\n", MES_SERVER_TO_CLIENT);
		sqlarg_delete(sarg);
		message_delete(mes);
		exit(1);
	}

	tdb = mysql_real_connect(sqldb, sqlargi(sarg, SMYSQL_HOST), sqlargi(sarg, SMYSQL_USER), sqlargi(sarg, SMYSQL_PASSWORD),
					  sqlargi(sarg, SMYSQL_DBNAME), port, sqlargi(sarg, SMYSQL_SOCKET), flag);

	sqlarg_delete(sarg);

	

	if(tdb == NULL)
	{
		char ws[128];
		snprintf(ws, 127, "Error opening mysql: %s\n", mysql_error(sqldb));
		ws[127] = 0;
		message_status(mes, 127, ws, MES_SERVER_TO_CLIENT);
		mysql_close(sqldb);
		message_delete(mes);
		exit(1);
	}

	/*
	 * Transmit to parent that we are hunky dory
	 */

	message_status(mes, 0, "", MES_SERVER_TO_CLIENT);

	/*
	 * We are open for business - Lets go
 	 */

	mainloop();

	/*
	 * At the end, tidy up
	 */

	mysql_close(sqldb);
	message_destroy(mes);
	message_delete(mes);
	exit(0);
}
Пример #27
0
/* virtual */ 
void LLPluginProcessChild::receivePluginMessage(const std::string &message)
{
	LL_DEBUGS("Plugin") << "Received from plugin: " << message << LL_ENDL;

	// Incoming message from the plugin instance
	bool passMessage = true;

	// FIXME: how should we handle queueing here?
	
	// Intercept certain base messages (responses to ones sent by this class)
	{
		// Decode this message
		LLPluginMessage parsed;
		parsed.parse(message);
		std::string message_class = parsed.getClass();
		if(message_class == "base")
		{
			std::string message_name = parsed.getName();
			if(message_name == "init_response")
			{
				// The plugin has finished initializing.
				setState(STATE_RUNNING);

				// Don't pass this message up to the parent
				passMessage = false;
				
				LLPluginMessage new_message(LLPLUGIN_MESSAGE_CLASS_INTERNAL, "load_plugin_response");
				LLSD versions = parsed.getValueLLSD("versions");
				new_message.setValueLLSD("versions", versions);
				
				if(parsed.hasValue("plugin_version"))
				{
					std::string plugin_version = parsed.getValue("plugin_version");
					new_message.setValueLLSD("plugin_version", plugin_version);
				}

				// Let the parent know it's loaded and initialized.
				sendMessageToParent(new_message);
			}
			else if(message_name == "shm_remove_response")
			{
				// Don't pass this message up to the parent
				passMessage = false;

				std::string name = parsed.getValue("name");
				sharedMemoryRegionsType::iterator iter = mSharedMemoryRegions.find(name);				
				if(iter != mSharedMemoryRegions.end())
				{
					// detach the shared memory region
					iter->second->detach();
					
					// and remove it from our map
					mSharedMemoryRegions.erase(iter);
					
					// Finally, send the response to the parent.
					LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_INTERNAL, "shm_remove_response");
					message.setValue("name", name);
					sendMessageToParent(message);
				}
				else
				{
					LL_WARNS("Plugin") << "shm_remove_response for unknown memory segment!" << LL_ENDL;
				}
			}
		}
	}
	
	if(passMessage)
	{
		LL_DEBUGS("Plugin") << "Passing through to parent: " << message << LL_ENDL;
		writeMessageRaw(message);
	}
}