Пример #1
0
static int l_siplua_moduleFunc(lua_State *L)
{
  struct sipapi_object *o;
  const char *func;
  int n, nargs;
  cmd_export_t *exp_func_struct;
  action_elem_t elems[MAX_ACTION_ELEMS];
  const char *s, *msg;
  char *str;
  int i;
  struct action *act;
  int retval;

  o = luaL_checkudata(L, 1, "siplua.api");
  func = luaL_checkstring(L, 2);
  n = lua_gettop(L);
  nargs = n - 2;
  if (n - 1 > MAX_ACTION_ELEMS)
    return luaL_error(L, "function '%s' called with too many arguments [%d > %d]",
	       func, nargs, MAX_ACTION_ELEMS - 1);
  exp_func_struct = find_cmd_export_t((char *)func, nargs, 0);
  if (!exp_func_struct)
    {
      return luaL_error(L, "function '%s' called, but not available.");
    }
  elems[0].type = CMD_ST;
  elems[0].u.data = exp_func_struct;
  memset(&elems[1], '\0', nargs * sizeof(action_elem_t));
  for (i = 0; i < nargs; ++i)
    {
      s = lua_tostring(L, 3 + i);
      if (!s)
	{
	  siplua_moduleFunc_free(func, exp_func_struct, elems, nargs);
	  msg = lua_pushfstring(L, "%s expected, got %s",
				lua_typename(L, LUA_TSTRING), luaL_typename(L, 3 + i));
	  return luaL_argerror(L, 3 + i, msg);
	}
      str = pkg_malloc(strlen(s) + 1);
      if (!str)
	{
	  siplua_moduleFunc_free(func, exp_func_struct, elems, nargs);
	  return luaL_error(L, "Not enough memory");
	}
      strcpy(str, s);
      /* We should maybe try STR_ST and elems[].u.str.{s,len} */
      elems[i + 1].type = STRING_ST;
      elems[i + 1].u.data = str; /* elems[].u.string */
    }
  act = mk_action(MODULE_T, n - 2 + 1, elems, 0);
  if (!act)
    {
      siplua_moduleFunc_free(func, exp_func_struct, elems, nargs);
      return luaL_error(L, "action structure could not be created. Error.");
    }
/*   siplua_log(L_DBG, "fixup/%p free_fixup/%p", */
/* 	     exp_func_struct->fixup, */
/* 	     exp_func_struct->free_fixup); */
  if (exp_func_struct->fixup)
    {
      if (!siplua_unsafemodfnc && !exp_func_struct->free_fixup)
	{
	  siplua_moduleFunc_free(func, exp_func_struct, act->elem, nargs);
	  return luaL_error(L, "Module function '%s' is unsafe. Call is refused.\n", func);
	}
      if (nargs == 0)
	{
	  retval = exp_func_struct->fixup(0, 0);
	  if (retval < 0)
	    {
	      siplua_moduleFunc_free(func, exp_func_struct, act->elem, nargs);
	      return luaL_error(L, "Error in fixup (0)\n");
	    }
	}
      for (i = 0; i < nargs; ++i)
	{
	  retval = exp_func_struct->fixup(&act->elem[i + 1].u.data, i + 1);
	  if (retval < 0)
	    {
	      siplua_moduleFunc_free(func, exp_func_struct, act->elem, nargs);
	      return luaL_error(L, "Error in fixup (%d)\n", i + 1);
	    }
	  act->elem[i + 1].type = MODFIXUP_ST;
	}
    }
  retval = do_action(act, o->msg);
  siplua_moduleFunc_free(func, exp_func_struct, act->elem, nargs);
  pkg_free(act);
  lua_pushinteger(L, retval);
  return 1;
}
Пример #2
0
/* State machine to do the calling and hangup procedure */
static void process_event(struct cardstate *cs, struct event_t *ev)
{
	struct bc_state *bcs;
	char *p_command = NULL;
	struct reply_t *rep;
	int rcode;
	int genresp = 0;
	int resp_code = RSP_ERROR;
	int sendcid;
	struct at_state_t *at_state;
	int index;
	int curact;
	unsigned long flags;

	if (ev->cid >= 0) {
		at_state = at_state_from_cid(cs, ev->cid);
		if (!at_state) {
			gig_dbg(DEBUG_EVENT, "event %d for invalid cid %d",
				ev->type, ev->cid);
			gigaset_add_event(cs, &cs->at_state, RSP_WRONG_CID,
					  NULL, 0, NULL);
			return;
		}
	} else {
		at_state = ev->at_state;
		if (at_state_invalid(cs, at_state)) {
			gig_dbg(DEBUG_EVENT, "event for invalid at_state %p",
				at_state);
			return;
		}
	}

	gig_dbg(DEBUG_EVENT, "connection state %d, event %d",
		at_state->ConState, ev->type);

	bcs = at_state->bcs;
	sendcid = at_state->cid;

	/* Setting the pointer to the dial array */
	rep = at_state->replystruct;

	spin_lock_irqsave(&cs->lock, flags);
	if (ev->type == EV_TIMEOUT) {
		if (ev->parameter != at_state->timer_index
		    || !at_state->timer_active) {
			ev->type = RSP_NONE; /* old timeout */
			gig_dbg(DEBUG_EVENT, "old timeout");
		} else if (!at_state->waiting)
			gig_dbg(DEBUG_EVENT, "timeout occurred");
		else
			gig_dbg(DEBUG_EVENT, "stopped waiting");
	}
	spin_unlock_irqrestore(&cs->lock, flags);

	/* if the response belongs to a variable in at_state->int_var[VAR_XXXX]
	   or at_state->str_var[STR_XXXX], set it */
	if (ev->type >= RSP_VAR && ev->type < RSP_VAR + VAR_NUM) {
		index = ev->type - RSP_VAR;
		at_state->int_var[index] = ev->parameter;
	} else if (ev->type >= RSP_STR && ev->type < RSP_STR + STR_NUM) {
		index = ev->type - RSP_STR;
		kfree(at_state->str_var[index]);
		at_state->str_var[index] = ev->ptr;
		ev->ptr = NULL; /* prevent process_events() from
				   deallocating ptr */
	}

	if (ev->type == EV_TIMEOUT || ev->type == RSP_STRING)
		at_state->getstring = 0;

	/* Search row in dial array which matches modem response and current
	   constate */
	for (;; rep++) {
		rcode = rep->resp_code;
		if (rcode == RSP_LAST) {
			/* found nothing...*/
			dev_warn(cs->dev, "%s: rcode=RSP_LAST: "
				 "resp_code %d in ConState %d!\n",
				 __func__, ev->type, at_state->ConState);
			return;
		}
		if ((rcode == RSP_ANY || rcode == ev->type)
		    && ((int) at_state->ConState >= rep->min_ConState)
		    && (rep->max_ConState < 0
			|| (int) at_state->ConState <= rep->max_ConState)
		    && (rep->parameter < 0 || rep->parameter == ev->parameter))
			break;
	}

	p_command = rep->command;

	at_state->waiting = 0;
	for (curact = 0; curact < MAXACT; ++curact) {
		/* The row tells us what we should do  ..
		 */
		do_action(rep->action[curact], cs, bcs, &at_state, &p_command,
			  &genresp, &resp_code, ev);
		if (!at_state)
			break; /* may be freed after disconnect */
	}

	if (at_state) {
		/* Jump to the next con-state regarding the array */
		if (rep->new_ConState >= 0)
			at_state->ConState = rep->new_ConState;

		if (genresp) {
			spin_lock_irqsave(&cs->lock, flags);
			at_state->timer_expires = 0;
			at_state->timer_active = 0;
			spin_unlock_irqrestore(&cs->lock, flags);
			gigaset_add_event(cs, at_state, resp_code,
					  NULL, 0, NULL);
		} else {
			/* Send command to modem if not NULL... */
			if (p_command) {
				if (cs->connected)
					send_command(cs, p_command,
						     sendcid, cs->dle,
						     GFP_ATOMIC);
				else
					gigaset_add_event(cs, at_state,
							  RSP_NODEV,
							  NULL, 0, NULL);
			}

			spin_lock_irqsave(&cs->lock, flags);
			if (!rep->timeout) {
				at_state->timer_expires = 0;
				at_state->timer_active = 0;
			} else if (rep->timeout > 0) { /* new timeout */
				at_state->timer_expires = rep->timeout * 10;
				at_state->timer_active = 1;
				++at_state->timer_index;
			}
			spin_unlock_irqrestore(&cs->lock, flags);
		}
	}
}
Пример #3
0
void
process_command(int descr, dbref player, char *command)
{
	char *arg1;
	char *arg2;
	char *full_command;
	char *p;					/* utility */
	char pbuf[BUFFER_LEN];
	char xbuf[BUFFER_LEN];
	char ybuf[BUFFER_LEN];
	struct timeval starttime;
	struct timeval endtime;
	double totaltime;

	if (command == 0)
		abort();

	/* robustify player */
	if (player < 0 || player >= db_top ||
		(Typeof(player) != TYPE_PLAYER && Typeof(player) != TYPE_THING)) {
		log_status("process_command: bad player %d", player);
		return;
	}

	if ((tp_log_commands || Wizard(OWNER(player)))) {
		if (!(FLAGS(player) & (INTERACTIVE | READMODE))) {
			if (!*command) {
				return; 
			}
			log_command("%s: %s", whowhere(player), command);
		} else {
			if (tp_log_interactive) {
				log_command("%s: %s%s", whowhere(player),
						(FLAGS(player) & (READMODE)) ? "[READ] " : "[INTERP] ", command);
			}
		}
	}

	if (FLAGS(player) & INTERACTIVE) {
		interactive(descr, player, command);
		return;
	}
	/* eat leading whitespace */
	while (*command && isspace(*command))
		command++;

	/* Disable null command once past READ line */
	if (!*command)
		return;

	/* check for single-character commands */
	if (!tp_enable_prefix) {
		if (*command == SAY_TOKEN) {
			snprintf(pbuf, sizeof(pbuf), "say %s", command + 1);
			command = &pbuf[0];
		} else if (*command == POSE_TOKEN) {
			snprintf(pbuf, sizeof(pbuf), "pose %s", command + 1);
			command = &pbuf[0];
		} else if (*command == EXIT_DELIMITER) {
			snprintf(pbuf, sizeof(pbuf), "delimiter %s", command + 1);
			command = &pbuf[0];
		}
	}

	/* profile how long command takes. */
	gettimeofday(&starttime, NULL);

	/* if player is a wizard, and uses overide token to start line... */
	/* ... then do NOT run actions, but run the command they specify. */
	if (!(TrueWizard(OWNER(player)) && (*command == OVERIDE_TOKEN))) {
		if (can_move(descr, player, command, 0)) {
			do_move(descr, player, command, 0);	/* command is exact match for exit */
			*match_args = 0;
			*match_cmdname = 0;
		} else {
			if (tp_enable_prefix) {
				if (*command == SAY_TOKEN) {
					snprintf(pbuf, sizeof(pbuf), "say %s", command + 1);
					command = &pbuf[0];
				} else if (*command == POSE_TOKEN) {
					snprintf(pbuf, sizeof(pbuf), "pose %s", command + 1);
					command = &pbuf[0];
				} else if (*command == EXIT_DELIMITER) {
					snprintf(pbuf, sizeof(pbuf), "delimiter %s", command + 1);
					command = &pbuf[0];
				} else {
					goto bad_pre_command;
				}
				if (can_move(descr, player, command, 0)) {
					do_move(descr, player, command, 0);	/* command is exact match for exit */
					*match_args = 0;
					*match_cmdname = 0;
				} else {
					goto bad_pre_command;
				}
			} else {
				goto bad_pre_command;
			}
		}
	} else {
	  bad_pre_command:
		if (TrueWizard(OWNER(player)) && (*command == OVERIDE_TOKEN))
			command++;
		full_command = strcpyn(xbuf, sizeof(xbuf), command);
		for (; *full_command && !isspace(*full_command); full_command++) ;
		if (*full_command)
			full_command++;

		/* find arg1 -- move over command word */
		command = strcpyn(ybuf, sizeof(ybuf), command);
		for (arg1 = command; *arg1 && !isspace(*arg1); arg1++) ;
		/* truncate command */
		if (*arg1)
			*arg1++ = '\0';

		/* remember command for programs */
		strcpyn(match_args, sizeof(match_args), full_command);
		strcpyn(match_cmdname, sizeof(match_cmdname), command);

		/* move over spaces */
		while (*arg1 && isspace(*arg1))
			arg1++;

		/* find end of arg1, start of arg2 */
		for (arg2 = arg1; *arg2 && *arg2 != ARG_DELIMITER; arg2++) ;

		/* truncate arg1 */
		for (p = arg2 - 1; p >= arg1 && isspace(*p); p--)
			*p = '\0';

		/* go past delimiter if present */
		if (*arg2)
			*arg2++ = '\0';
		while (*arg2 && isspace(*arg2))
			arg2++;

		switch (command[0]) {
		case '@':
			switch (command[1]) {
			case 'a':
			case 'A':
				/* @action, @armageddon, @attach */
				switch (command[2]) {
				case 'c':
				case 'C':
					Matched("@action");
					NOGUEST("@action", player);
					BUILDERONLY("@action", player);
					do_action(descr, player, arg1, arg2);
					break;
				case 'r':
				case 'R':
					if (strcmp(command, "@armageddon"))
						goto bad;
/*
					WIZARDONLY("@armageddon", player);
					PLAYERONLY("@armageddon", player);
*/
					do_armageddon(player, full_command);
					break;
				case 't':
				case 'T':
					Matched("@attach");
					NOGUEST("@attach", player);
					BUILDERONLY("@attach", player);
					do_attach(descr, player, arg1, arg2);
					break;
				default:
					goto bad;
				}
				break;
			case 'b':
			case 'B':
				/* @bless, @boot */
				switch (command[2]) {
				case 'l':
				case 'L':
					Matched("@bless");
					WIZARDONLY("@bless", player);
					PLAYERONLY("@bless", player);
					NOFORCE("@bless", force_level, player);
					do_bless(descr, player, arg1, arg2);
					break;
				case 'o':
				case 'O':
					Matched("@boot");
					WIZARDONLY("@boot", player);
					PLAYERONLY("@boot", player);
					do_boot(player, arg1);
					break;
				default:
					goto bad;
				}
				break;
			case 'c':
			case 'C':
				/* @chlock, @chown, @chown_lock, @clone,
				   @conlock, @contents, @create, @credits */
				switch (command[2]) {
				case 'h':
				case 'H':
					switch (command[3]) {
					case 'l':
					case 'L':
						Matched("@chlock");
						NOGUEST("@chlock", player);
						set_standard_lock(descr, player, arg1, MESGPROP_CHLOCK, "Chown Lock", arg2);
						break;
					case 'o':
					case 'O':
						if(strlen(command) < 7) {
							Matched("@chown");
							do_chown(descr, player, arg1, arg2);
						} else {
							Matched("@chown_lock");
							NOGUEST("@chown_lock", player);
							set_standard_lock(descr, player, arg1, MESGPROP_CHLOCK, "Chown Lock", arg2);
						}
						break;
					default:
						goto bad;
					}
					break;
				case 'l':
				case 'L':
					Matched("@clone");
					NOGUEST("@clone", player);
					BUILDERONLY("@clone", player);
					do_clone(descr, player, arg1);
					break;
				case 'o':
				case 'O':
					switch (command[4]) {
					case 'l':
					case 'L':
						Matched("@conlock");
						NOGUEST("@conlock", player);
						set_standard_lock(descr, player, arg1, MESGPROP_CONLOCK, "Container Lock", arg2);
						break;
					case 't':
					case 'T':
						Matched("@contents");
						do_contents(descr, player, arg1, arg2);
						break;
					default:
						goto bad;
					}
					break;
				case 'r':
				case 'R':
					if (string_compare(command, "@credits")) {
						Matched("@create");
						NOGUEST("@create", player);
						BUILDERONLY("@create", player);
						do_create(player, arg1, arg2);
					} else {
						do_credits(player);
					}
					break;
				default:
					goto bad;
				}
				break;
			case 'd':
			case 'D':
				/* @dbginfo, @describe, @dig, @doing,
				   @drop, @dump */
				switch (command[2]) {
#ifdef DISKBASE
				case 'b':
				case 'B':
					Matched("@dbginfo");
					WIZARDONLY("@dbginfo", player);
					diskbase_debug(player);
					break;
#endif
				case 'e':
				case 'E':
					Matched("@describe");
					NOGUEST("@describe", player);
					set_standard_property(descr, player, arg1, MESGPROP_DESC, "Object Description", arg2);
					break;
				case 'i':
				case 'I':
					Matched("@dig");
					NOGUEST("@dig", player);
					BUILDERONLY("@dig", player);
					do_dig(descr, player, arg1, arg2);
					break;
				case 'o':
				case 'O':
					Matched("@doing");
					if (!tp_who_doing)
						goto bad;
					NOGUEST("@doing", player);
					set_standard_property(descr, player, arg1, MESGPROP_DOING, "Doing", arg2);
					break;
				case 'r':
				case 'R':
					Matched("@drop");
					NOGUEST("@drop", player);
					set_standard_property(descr, player, arg1, MESGPROP_DROP, "Drop Message", arg2);
					break;
				case 'u':
				case 'U':
					Matched("@dump");
					WIZARDONLY("@dump", player);
					PLAYERONLY("@dump", player);
					do_dump(player, full_command);
					break;
				default:
					goto bad;
				}
				break;
			case 'e':
			case 'E':
				/* @edit, @entrances, @examine */
				switch (command[2]) {
				case 'd':
				case 'D':
					Matched("@edit");
					NOGUEST("@edit", player);
					PLAYERONLY("@edit", player);
					MUCKERONLY("@edit", player);
					do_edit(descr, player, arg1);
					break;
				case 'n':
				case 'N':
					Matched("@entrances");
					do_entrances(descr, player, arg1, arg2);
					break;
				case 'x':
				case 'X':
					Matched("@examine");
					GODONLY("@examine", player);
					sane_dump_object(player, arg1);
					break;
				default:
					goto bad;
				}
				break;
			case 'f':
			case 'F':
				/* @fail, @find, @flock, @force, @force_lock */
				switch (command[2]) {
				case 'a':
				case 'A':
					Matched("@fail");
					NOGUEST("@fail", player);
					set_standard_property(descr, player, arg1, MESGPROP_FAIL, "Fail Message", arg2);
					break;
				case 'i':
				case 'I':
					Matched("@find");
					do_find(player, arg1, arg2);
					break;
				case 'l':
				case 'L':
					Matched("@flock");
					NOGUEST("@flock", player);
					NOFORCE("@flock", force_level, player);
					set_standard_lock(descr, player, arg1, MESGPROP_FLOCK, "Force Lock", arg2);
					break;
				case 'o':
				case 'O':
					if(strlen(command) < 7) {
						Matched("@force");
						do_force(descr, player, arg1, arg2);
					} else {
						Matched("@force_lock");
						NOGUEST("@force_lock", player);
						NOFORCE("@force_lock", force_level, player);
						set_standard_lock(descr, player, arg1, MESGPROP_FLOCK, "Force Lock", arg2);
					}
					break;
				default:
					goto bad;
				}
				break;
			case 'h':
			case 'H':
				/* @hashes */
				Matched("@hashes");
				do_hashes(player, arg1);
				break;
			case 'i':
			case 'I':
				/* @idescribe */
				Matched("@idescribe");
				NOGUEST("@idescribe", player);
				set_standard_property(descr, player, arg1, MESGPROP_IDESC, "Inside Description", arg2);
				break;
			case 'k':
			case 'K':
				/* @kill */
				Matched("@kill");
				do_dequeue(descr, player, arg1);
				break;
			case 'l':
			case 'L':
				/* @link, @list, @lock */
				switch (command[2]) {
				case 'i':
				case 'I':
					switch (command[3]) {
					case 'n':
					case 'N':
						Matched("@link");
						NOGUEST("@link", player);
						do_link(descr, player, arg1, arg2);
						break;
					case 's':
					case 'S':
						Matched("@list");
						match_and_list(descr, player, arg1, arg2);
						break;
					default:
						goto bad;
					}
					break;
				case 'o':
				case 'O':
					Matched("@lock");
					NOGUEST("@lock", player);
					set_standard_lock(descr, player, arg1, MESGPROP_LOCK, "Lock", arg2);
					break;
				default:
					goto bad;
				}
				break;
			case 'm':
			case 'M':
				/* @mcpedit, @mcpprogram, @memory, @mpitops,
				   @muftops */
				switch (command[2]) {
#ifdef MCP_SUPPORT
				case 'c':
				case 'C':
					if (string_prefix("@mcpedit", command)) {
						Matched("@mcpedit");
						NOGUEST("@mcpedit", player);
						PLAYERONLY("@mcpedit", player);
						MUCKERONLY("@mcpedit", player);
						do_mcpedit(descr, player, arg1);
						break;
					} else {
						Matched("@mcpprogram");
						NOGUEST("@mcpprogram", player);
						PLAYERONLY("@mcpprogram", player);
						MUCKERONLY("@mcpprogram", player);
						do_mcpprogram(descr, player, arg1);
						break;
					}
#endif
#ifndef NO_MEMORY_COMMAND
				case 'e':
				case 'E':
					Matched("@memory");
					WIZARDONLY("@memory", player);
					do_memory(player);
					break;
#endif
				case 'p':
			    case 'P':
			        Matched("@mpitops");
				WIZARDONLY("@mpitops", player);
			        do_mpi_topprofs(player, arg1);
			        break;
			    case 'u':
			    case 'U':
			        Matched("@muftops");
				WIZARDONLY("@muftops", player);
			        do_muf_topprofs(player, arg1);
			        break;
				default:
					goto bad;
				}
				break;
			case 'n':
			case 'N':
				/* @name, @newpassword */
				switch (command[2]) {
				case 'a':
				case 'A':
					Matched("@name");
					NOGUEST("@name", player);
					do_name(descr, player, arg1, arg2);
					break;
				case 'e':
				case 'E':
					if (strcmp(command, "@newpassword"))
						goto bad;
					WIZARDONLY("@newpassword", player);
					PLAYERONLY("@newpassword", player);
					do_newpassword(player, arg1, arg2);
					break;
				default:
					goto bad;
				}
				break;
			case 'o':
			case 'O':
				/* @odrop, @oecho, @ofail, @open, @osuccess,
				   @owned */
				switch (command[2]) {
				case 'd':
				case 'D':
					Matched("@odrop");
					NOGUEST("@odrop", player);
					set_standard_property(descr, player, arg1, MESGPROP_ODROP, "ODrop Message", arg2);
					break;
				case 'e':
				case 'E':
					Matched("@oecho");
					NOGUEST("@oecho", player);
					set_standard_property(descr, player, arg1, MESGPROP_OECHO, "Outside-echo Prefix", arg2);
					break;
				case 'f':
				case 'F':
					Matched("@ofail");
					NOGUEST("@ofail", player);
					set_standard_property(descr, player, arg1, MESGPROP_OFAIL, "OFail Message", arg2);
					break;
				case 'p':
				case 'P':
					Matched("@open");
					NOGUEST("@open", player);
					BUILDERONLY("@open", player);
					do_open(descr, player, arg1, arg2);
					break;
				case 's':
				case 'S':
					Matched("@osuccess");
					NOGUEST("@osuccess", player);
					set_standard_property(descr, player, arg1, MESGPROP_OSUCC, "OSuccess Message", arg2);
					break;
				case 'w':
				case 'W':
					Matched("@owned");
					do_owned(player, arg1, arg2);
					break;
				default:
					goto bad;
				}
				break;
			case 'p':
			case 'P':
				/* @password, @pcreate, @pecho, @program, 
				   @propset, @ps */
				switch (command[2]) {
				case 'a':
				case 'A':
					Matched("@password");
					PLAYERONLY("@password", player);
					NOGUEST("@password", player);
					do_password(player, arg1, arg2);
					break;
				case 'c':
				case 'C':
					Matched("@pcreate");
					WIZARDONLY("@pcreate", player);
					PLAYERONLY("@pcreate", player);
					do_pcreate(player, arg1, arg2);
					break;
				case 'e':
				case 'E':
					Matched("@pecho");
					NOGUEST("@pecho", player);
					set_standard_property(descr, player, arg1, MESGPROP_PECHO, "Puppet-echo Prefix", arg2);
					break;
				case 'r':
				case 'R':
					if (string_prefix("@program", command)) {
						Matched("@program");
						NOGUEST("@program", player);
						PLAYERONLY("@program", player);
						MUCKERONLY("@program", player);
						do_prog(descr, player, arg1);
						break;
					} else {
						Matched("@propset");
						NOGUEST("@propset", player);
						do_propset(descr, player, arg1, arg2);
						break;
					}
				case 's':
				case 'S':
					Matched("@ps");
					list_events(player);
					break;
				default:
					goto bad;
				}
				break;
			case 'r':
			case 'R':
				/* @recycle, @reconfiguressl, @relink, @restart, @restrict */
				switch (command[3]) {
				case 'c':
				case 'C':
#ifdef USE_SSL
                                        if (!strcmp(command, "@reconfiguressl")) {
                                                WIZARDONLY("@reconfiguressl", player);
                                                PLAYERONLY("@reconfiguressl", player);
                                                do_reconfigure_ssl(player);
                                                break;
                                        }
#endif
                                        Matched("@recycle");
                                        NOGUEST("@recycle", player);
                                        do_recycle(descr, player, arg1);
                                        break;
				case 'l':
				case 'L':
					Matched("@relink");
					NOGUEST("@relink", player);
					do_relink(descr, player, arg1, arg2);
					break;
				case 's':
				case 'S':
					if (!strcmp(command, "@restart")) {
/*
						WIZARDONLY("@restart", player);
						PLAYERONLY("@restart", player);
*/
						do_restart(player);
					} else if (!strcmp(command, "@restrict")) {
						WIZARDONLY("@restrict", player);
						PLAYERONLY("@restrict", player);
						do_restrict(player, arg1);
					} else {
						goto bad;
					}
					break;
				default:
					goto bad;
				}
				break;
			case 's':
			case 'S':
				/* @sanity, @sanchange, @sanfix, @set,
				   @shutdown, @stats, @success, @sweep */
				switch (command[2]) {
				case 'a':
				case 'A':
					if (!strcmp(command, "@sanity")) {
						GODONLY("@sanity", player);
						sanity(player);
					} else if (!strcmp(command, "@sanchange")) {
						GODONLY("@sanchange", player);
						sanechange(player, full_command);
					} else if (!strcmp(command, "@sanfix")) {
						GODONLY("@sanfix", player);
						sanfix(player);
					} else {
						goto bad;
					}
					break;
				case 'e':
				case 'E':
					Matched("@set");
					NOGUEST("@set", player);
					do_set(descr, player, arg1, arg2);
					break;
				case 'h':
				case 'H':
					if (strcmp(command, "@shutdown"))
						goto bad;
/*
					WIZARDONLY("@shutdown", player);
					PLAYERONLY("@shutdown", player);
*/
					do_shutdown(player);
					break;
				case 't':
				case 'T':
					Matched("@stats");
					do_stats(player, arg1);
					break;
				case 'u':
				case 'U':
					Matched("@success");
					NOGUEST("@success", player);
					set_standard_property(descr, player, arg1, MESGPROP_SUCC, "Success Message", arg2);
					break;
				case 'w':
				case 'W':
					Matched("@sweep");
					do_sweep(descr, player, arg1);
					break;
				default:
					goto bad;
				}
				break;
			case 't':
			case 'T':
				/* @teleport, @toad, @trace, @tune */
				switch (command[2]) {
				case 'e':
				case 'E':
					Matched("@teleport");
					do_teleport(descr, player, arg1, arg2);
					break;
				case 'o':
				case 'O':
					if (!strcmp(command, "@toad")) {
						WIZARDONLY("@toad", player);
						PLAYERONLY("@toad", player);
						do_toad(descr, player, arg1, arg2);
					} else if (!strcmp(command, "@tops")) {
						WIZARDONLY("@tops", player);
						do_all_topprofs(player, arg1);
					} else {
						goto bad;
					}
					break;
				case 'r':
				case 'R':
					Matched("@trace");
					do_trace(descr, player, arg1, atoi(arg2));
					break;
				case 'u':
				case 'U':
					Matched("@tune");
					WIZARDONLY("@tune", player);
					PLAYERONLY("@tune", player);
					do_tune(player, arg1, arg2, !!strchr(full_command, ARG_DELIMITER));
					break;
				default:
					goto bad;
				}
				break;
			case 'u':
			case 'U':
				/* @unbless, @unlink, @unlock, @uncompile,
				   @usage */
				switch (command[2]) {
				case 'N':
				case 'n':
					if (string_prefix(command, "@unb")) {
						Matched("@unbless");
						WIZARDONLY("@unbless", player);
						PLAYERONLY("@unbless", player);
						NOFORCE("@unbless", force_level, player);
						do_unbless(descr, player, arg1, arg2);
					} else if (string_prefix(command, "@unli")) {
						Matched("@unlink");
						NOGUEST("@unlink", player);
						do_unlink(descr, player, arg1);
					} else if (string_prefix(command, "@unlo")) {
						Matched("@unlock");
						NOGUEST("@unlock", player);
						set_standard_lock(descr, player, arg1, MESGPROP_LOCK, "Lock", "");
					} else if (string_prefix(command, "@uncom")) {
						Matched("@uncompile");
						WIZARDONLY("@uncompile", player);
						PLAYERONLY("@uncompile", player);
						do_uncompile(player);
					} else {
						goto bad;
					}
					break;
#ifndef NO_USAGE_COMMAND
				case 'S':
				case 's':
					Matched("@usage");
					WIZARDONLY("@usage", player);
					do_usage(player);
					break;
#endif
				default:
					goto bad;
					break;
				}
				break;
			case 'v':
			case 'V':
				/* @version */
				Matched("@version");
				do_version(player);
				break;
			case 'w':
			case 'W':
				/* @wall */
				if (strcmp(command, "@wall"))
					goto bad;
				WIZARDONLY("@wall", player);
				PLAYERONLY("@wall", player);
				do_wall(player, full_command);
				break;
			default:
				goto bad;
			}
			break;
		case 'd':
		case 'D':
			/* disembark, drop */
			switch (command[1]) {
			case 'i':
			case 'I':
				Matched("disembark");
				do_leave(descr, player);
				break;
			case 'r':
			case 'R':
				Matched("drop");
				do_drop(descr, player, arg1, arg2);
				break;
			default:
				goto bad;
			}
			break;
		case 'e':
		case 'E':
			/* examine */
			Matched("examine");
			do_examine(descr, player, arg1, arg2);
			break;
		case 'g':
		case 'G':
			/* get, give, goto, gripe */
			switch (command[1]) {
			case 'e':
			case 'E':
				Matched("get");
				do_get(descr, player, arg1, arg2);
				break;
			case 'i':
			case 'I':
				Matched("give");
				do_give(descr, player, arg1, atoi(arg2));
				break;
			case 'o':
			case 'O':
				Matched("goto");
				do_move(descr, player, arg1, 0);
				break;
			case 'r':
			case 'R':
				if (string_compare(command, "gripe"))
					goto bad;
				do_gripe(player, full_command);
				break;
			default:
				goto bad;
			}
			break;
		case 'h':
		case 'H':
			/* help */
			Matched("help");
			do_help(player, arg1, arg2);
			break;
		case 'i':
		case 'I':
			/* inventory, info */
			if (string_compare(command, "info")) {
				Matched("inventory");
				do_inventory(player);
			} else {
				Matched("info");
				do_info(player, arg1, arg2);
			}
			break;
		case 'k':
		case 'K':
			/* kill */
			Matched("kill");
			do_kill(descr, player, arg1, atoi(arg2));
			break;
		case 'l':
		case 'L':
			/* leave, look */
			if (string_prefix("look", command)) {
				Matched("look");
				do_look_at(descr, player, arg1, arg2);
				break;
			} else {
				Matched("leave");
				do_leave(descr, player);
				break;
			}
		case 'm':
		case 'M':
			/* man, motd, move, mpi */
			if (string_prefix(command, "move")) {
				do_move(descr, player, arg1, 0);
				break;
			} else if (!string_compare(command, "motd")) {
				do_motd(player, full_command);
				break;
			} else if (!string_compare(command, "mpi")) {
				do_mpihelp(player, arg1, arg2);
				break;
			} else {
				if (string_compare(command, "man"))
					goto bad;
				do_man(player, (!*arg1 && !*arg2 && arg1 != arg2) ? "=" : arg1, arg2);
			}
			break;
		case 'n':
		case 'N':
			/* news */
			Matched("news");
			do_news(player, arg1, arg2);
			break;
		case 'p':
		case 'P':
			/* page, pose, put */
			switch (command[1]) {
			case 'a':
			case 'A':
				Matched("page");
				do_page(player, arg1, arg2);
				break;
			case 'o':
			case 'O':
				Matched("pose");
				do_pose(player, full_command);
				break;
			case 'u':
			case 'U':
				Matched("put");
				do_drop(descr, player, arg1, arg2);
				break;
			default:
				goto bad;
			}
			break;
		case 'r':
		case 'R':
			/* read, rob */
			switch (command[1]) {
			case 'e':
			case 'E':
				Matched("read");	/* undocumented alias for look */
				do_look_at(descr, player, arg1, arg2);
				break;
			case 'o':
			case 'O':
				Matched("rob");
				do_rob(descr, player, arg1);
				break;
			default:
				goto bad;
			}
			break;
		case 's':
		case 'S':
			/* say, score */
			switch (command[1]) {
			case 'a':
			case 'A':
				Matched("say");
				do_say(player, full_command);
				break;
			case 'c':
			case 'C':
				Matched("score");
				do_score(player);
				break;
			default:
				goto bad;
			}
			break;
		case 't':
		case 'T':
			/* take, throw */
			switch (command[1]) {
			case 'a':
			case 'A':
				Matched("take");
				do_get(descr, player, arg1, arg2);
				break;
			case 'h':
			case 'H':
				Matched("throw");
				do_drop(descr, player, arg1, arg2);
				break;
			default:
			goto bad;
			}
			break;
		case 'w':
		case 'W':
			/* whisper */
			Matched("whisper");
			do_whisper(descr, player, arg1, arg2);
			break;
		default:
		  bad:
			if (tp_m3_huh != 0)
			{
				char hbuf[BUFFER_LEN];
				snprintf(hbuf,BUFFER_LEN,"HUH? %s", command);
				if(can_move(descr, player, hbuf, 3)) {
					do_move(descr, player, hbuf, 3);
					*match_args = 0;
					*match_cmdname = 0;
					break;
				}
			}	
			notify(player, tp_huh_mesg);
			if (tp_log_failed_commands && !controls(player, LOCATION(player))) {
				log_status("HUH from %s(%d) in %s(%d)[%s]: %s %s",
						   NAME(player), player, NAME(LOCATION(player)),
						   LOCATION(player),
						   NAME(OWNER(LOCATION(player))), command, full_command);
			}
			break;
		}
	}

	/* calculate time command took. */
	gettimeofday(&endtime, NULL);
	if (starttime.tv_usec > endtime.tv_usec) {
		endtime.tv_usec += 1000000;
		endtime.tv_sec -= 1;
	}
	endtime.tv_usec -= starttime.tv_usec;
	endtime.tv_sec -= starttime.tv_sec;

	totaltime = endtime.tv_sec + (endtime.tv_usec * 1.0e-6);
	if (totaltime > (tp_cmd_log_threshold_msec / 1000.0)) {
		log2file(LOG_CMD_TIMES, "%6.3fs, %.16s: %s: %s",
					totaltime, ctime((time_t *)&starttime.tv_sec),
					whowhere(player), command);
	}
}
Пример #4
0
static void
catch_sigusr2(int s) {
	(void)s;
	do_action(sigusr2);
}
Пример #5
0
int
main(int argc, char *argv[]) {
	int i;
	char *action_string = NULL;
	char *endptr;

	/* default values */
	dzen.cur_line  = 0;
	dzen.ret_val   = 0;
	dzen.title_win.x = dzen.slave_win.x = 0;
	dzen.title_win.y = 0;
	dzen.title_win.width = dzen.slave_win.width = 0;
	dzen.title_win.alignment = ALIGNCENTER;
	dzen.slave_win.alignment = ALIGNLEFT;
	dzen.fnt = FONT;
	dzen.bg  = BGCOLOR;
	dzen.fg  = FGCOLOR;
	dzen.slave_win.max_lines  = 0;
	dzen.running = True;
	dzen.xinescreen = 0;
	dzen.tsupdate = 0;
	dzen.line_height = 0;

	/* cmdline args */
	for(i = 1; i < argc; i++)
		if(!strncmp(argv[i], "-l", 3)){
			if(++i < argc) {
				dzen.slave_win.max_lines = atoi(argv[i]);
				init_input_buffer();
			}
		}
		else if(!strncmp(argv[i], "-u", 3)){
			dzen.tsupdate = True;
		}
		else if(!strncmp(argv[i], "-p", 3)) {
			dzen.ispersistent = True;
			if (i+1 < argc) {
				dzen.timeout = strtoul(argv[i+1], &endptr, 10);
				if(*endptr)
					dzen.timeout = 0;
				else
					i++;
			}
		}
		else if(!strncmp(argv[i], "-ta", 4)) {
			if(++i < argc) dzen.title_win.alignment = argv[i][0];
		}
		else if(!strncmp(argv[i], "-sa", 4)) {
			if(++i < argc) dzen.slave_win.alignment = argv[i][0];
		}
		else if(!strncmp(argv[i], "-m", 3)) {
			dzen.slave_win.ismenu = True;
			if(i+1 < argc) 
				dzen.slave_win.ishmenu = (argv[i+1][0] == 'h') ? ++i, True : False;
		}
		else if(!strncmp(argv[i], "-fn", 4)) {
			if(++i < argc) dzen.fnt = argv[i];
		}
		else if(!strncmp(argv[i], "-e", 3)) {
			if(++i < argc) action_string = argv[i];
		}
		else if(!strncmp(argv[i], "-bg", 4)) {
			if(++i < argc) dzen.bg = argv[i];
		}
		else if(!strncmp(argv[i], "-fg", 4)) {
			if(++i < argc) dzen.fg = argv[i];
		}
		else if(!strncmp(argv[i], "-x", 3)) {
			if(++i < argc) dzen.title_win.x = dzen.slave_win.x = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-y", 3)) {
			if(++i < argc) dzen.title_win.y = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-w", 3)) {
			if(++i < argc) dzen.slave_win.width = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-h", 3)) {
			if(++i < argc) dzen.line_height= atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-tw", 4)) {
			if(++i < argc) dzen.title_win.width = atoi(argv[i]);
		}
#ifdef DZEN_XINERAMA
		else if(!strncmp(argv[i], "-xs", 4)) {
			if(++i < argc) dzen.xinescreen = atoi(argv[i]);
		}
#endif
		else if(!strncmp(argv[i], "-v", 3)) 
			eprint("dzen-"VERSION", (C)opyright 2007 Robert Manea\n");
		else
			eprint("usage: dzen2 [-v] [-p [seconds]] [-m [v|h]] [-ta <l|c|r>] [-sa <l|c|r>]\n"
                   "             [-x <pixel>] [-y <pixel>] [-w <pixel>] [-tw <pixel>] [-u] \n"
				   "             [-e <string>] [-l <lines>]  [-fn <font>] [-bg <color>] [-fg <color>]\n"
#ifdef DZEN_XINERAMA
				   "             [-xs <screen>]\n"
#endif
				  );

	if(dzen.tsupdate && !dzen.slave_win.max_lines)
		dzen.tsupdate = False;

	if(!dzen.title_win.width)
		dzen.title_win.width = dzen.slave_win.width;

	if(!setlocale(LC_ALL, "") || !XSupportsLocale())
		puts("dzen: locale not available, expect problems with fonts.\n");

	if(action_string) 
		fill_ev_table(action_string);
	else {
		if(!dzen.slave_win.max_lines) {
			char edef[] = "button3=exit:13";
			fill_ev_table(edef);
		}
		else if(dzen.slave_win.ishmenu) {
			char edef[] = "enterslave=grabkeys;leaveslave=ungrabkeys;"
				"button4=scrollup;button5=scrolldown;"
				"key_Left=scrollup;key_Right=scrolldown;"
				"button1=menuexec;button3=exit:13;"
				"key_Escape=ungrabkeys,exit";
			fill_ev_table(edef);
		}
		else {
			char edef[]  = "entertitle=uncollapse,grabkeys;"
				"enterslave=grabkeys;leaveslave=collapse,ungrabkeys;"
				"button1=menuexec;button2=togglestick;button3=exit:13;"
				"button4=scrollup;button5=scrolldown;"
				"key_Up=scrollup;key_Down=scrolldown;"
				"key_Escape=ungrabkeys,exit";
			fill_ev_table(edef);
		}
	}

	if((find_event(onexit) != -1) 
			&& (setup_signal(SIGTERM, catch_sigterm) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGTERM\n");

	if((find_event(sigusr1) != -1) 
			&& (setup_signal(SIGUSR1, catch_sigusr1) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGUSR1\n");
	
	if((find_event(sigusr2) != -1) 
		&& (setup_signal(SIGUSR2, catch_sigusr2) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGUSR2\n");
	
	if(setup_signal(SIGALRM, catch_alrm) == SIG_ERR)
		fprintf(stderr, "dzen: error hooking SIGALARM\n");

	set_alignment();
	
	if(dzen.slave_win.ishmenu &&
			!dzen.slave_win.max_lines)
		dzen.slave_win.max_lines = 1;

	x_create_windows();
	
	if(!dzen.slave_win.ishmenu)
		x_map_window(dzen.title_win.win);
	else {
		XMapRaised(dzen.dpy, dzen.slave_win.win);
		for(i=0; i < dzen.slave_win.max_lines; i++)
			XMapWindow(dzen.dpy, dzen.slave_win.line[i]);
	}

	do_action(onstart);

	/* main loop */
	event_loop();

	do_action(onexit);
	clean_up();

	if(dzen.ret_val)
		return dzen.ret_val;

	return EXIT_SUCCESS;
}
Пример #6
0
static PyObject *
msg_call_function(msgobject *self, PyObject *args)
{
/* TODO: adapt to new cmd_export and params interface */
#if 0
    int i, rval;
    char *fname, *arg1, *arg2;
    cmd_export_t *fexport;
    struct action *act;
    action_elem_t elems[MAX_ACTION_ELEMS];

    if (self->msg == NULL) {
        PyErr_SetString(PyExc_RuntimeError, "self->msg is NULL");
        Py_INCREF(Py_None);
        return Py_None;
    }

    i = PySequence_Size(args);
    if (i < 1 || i > 3) {
        PyErr_SetString(PyExc_RuntimeError, "call_function() should " \
          "have from 1 to 3 arguments");
        Py_INCREF(Py_None);
        return Py_None;
    }

    if(!PyArg_ParseTuple(args, "s|ss:call_function", &fname, &arg1, &arg2))
        return NULL;

    fexport = find_cmd_export_t(fname, 0);
    if (fexport == NULL) {
        PyErr_SetString(PyExc_RuntimeError, "no such function");
        Py_INCREF(Py_None);
        return Py_None;
    }

    elems[0].type = CMD_ST;
    elems[0].u.data = fexport;
    elems[1].type = STRING_ST;
    elems[1].u.data = arg1;
    elems[2].type = STRING_ST;
    elems[2].u.data = arg2;
    act = mk_action(MODULE_T, 3, elems, 0, "python");

    if (act == NULL) {
        PyErr_SetString(PyExc_RuntimeError,
          "action structure could not be created");
        Py_INCREF(Py_None);
        return Py_None;
    }

    if (fexport->fixup != NULL) {
        if (i >= 3) {
            rval = fexport->fixup(&(act->elem[2].u.data), 2);
            if (rval < 0) {
                PyErr_SetString(PyExc_RuntimeError, "Error in fixup (2)");
                Py_INCREF(Py_None);
                return Py_None;
            }
            act->elem[2].type = MODFIXUP_ST;
        }
        if (i >= 2) {
            rval = fexport->fixup(&(act->elem[1].u.data), 1);
            if (rval < 0) {
                PyErr_SetString(PyExc_RuntimeError, "Error in fixup (1)");
                Py_INCREF(Py_None);
                return Py_None;
            }
            act->elem[1].type = MODFIXUP_ST;
        }
        if (i == 1) {
            rval = fexport->fixup(0, 0);
            if (rval < 0) {
                PyErr_SetString(PyExc_RuntimeError, "Error in fixup (0)");
                Py_INCREF(Py_None);
                return Py_None;
            }
        }
    }

    rval = do_action(act, self->msg);

    if ((act->elem[2].type == MODFIXUP_ST) && (act->elem[2].u.data) &&
      (act->elem[2].u.data != arg2)) {
       pkg_free(act->elem[2].u.data);
    }

    if ((act->elem[1].type == MODFIXUP_ST) && (act->elem[1].u.data)) {
        pkg_free(act->elem[1].u.data);
    }

    pkg_free(act);

    return PyInt_FromLong(rval);
#endif

    return NULL;
}
Пример #7
0
int moduleFunc(struct sip_msg *m, char *func,
	       char *param1, char *param2,
	       int *retval) {

	cmd_export_t *exp_func_struct;
	struct action *act;
	char *argv[2];
	int argc = 0;
	action_elem_t elems[MAX_ACTION_ELEMS];

	if (!func) {
		LM_ERR("moduleFunc called with null function name. Error.");
		return -1;
	}

	if ((!param1) && param2) {
		LM_ERR("moduleFunc called with parameter 1 UNSET and"
			   " parameter 2 SET. Error.");
		return -1;
	}


	if (param1) {
		argv[0] = (char *)pkg_malloc(strlen(param1)+1);
		strcpy(argv[0], param1);
		argc++;
	} else {
		argv[0] = NULL;
	}

	if (param2) {
		argv[1] = (char *)pkg_malloc(strlen(param2)+1);
		strcpy(argv[1], param2);
		argc++;
	} else {
		argv[1] = NULL;
	}

	exp_func_struct = find_cmd_export_t(func, argc, 0);
	if (!exp_func_struct) {
		LM_ERR("function '%s' called, but not available.", func);
		*retval = -1;
		if (argv[0]) pkg_free(argv[0]);
		if (argv[1]) pkg_free(argv[1]);
		return -1;
	}

	elems[0].type = CMD_ST;
	elems[0].u.data = exp_func_struct;
	elems[1].type = STRING_ST;
	elems[1].u.data = argv[0];
	elems[2].type = STRING_ST;
	elems[2].u.data = argv[1];
	act = mk_action(	MODULE_T,
				3,
				elems,
				0);


	if (!act) {
		LM_ERR("action structure could not be created. Error.");
		if (argv[0]) pkg_free(argv[0]);
		if (argv[1]) pkg_free(argv[1]);
		return -1;
	}


	if (exp_func_struct->fixup) {
		if (!unsafemodfnc) {
			LM_ERR("Module function '%s' is unsafe. Call is refused.\n", func);
			if (argv[0]) pkg_free(argv[0]);
			if (argv[1]) pkg_free(argv[1]);
			*retval = -1;
			return -1;
		}

		if (argc>=2) {
			*retval = exp_func_struct->fixup(&(act->elem[2].u.data), 2);
			if (*retval < 0) {
				LM_ERR("Error in fixup (2)\n");
				return -1;
			}
			act->elem[2].type = MODFIXUP_ST;
		}
		if (argc>=1) {
			*retval = exp_func_struct->fixup(&(act->elem[1].u.data), 1);
			if (*retval < 0) {
				LM_ERR("Error in fixup (1)\n");
				return -1;
			}
			act->elem[1].type = MODFIXUP_ST;
		}
		if (argc==0) {
			*retval = exp_func_struct->fixup(0, 0);
			if (*retval < 0) {
				LM_ERR("Error in fixup (0)\n");
				return -1;
			}
		}
	}

	*retval = do_action(act, m);

	if ((act->elem[2].type == MODFIXUP_ST) && (act->elem[2].u.data)) {
		/* pkg_free(act->elem[2].u.data); */
		LM_WARN("moduleFunction: A fixup function was called. "
				"This currently creates a memory leak.\n");
	}

	if ((act->elem[1].type == MODFIXUP_ST) && (act->elem[1].u.data)) {
		/* pkg_free(act->elem[1].u.data); */
		LM_WARN("moduleFunction: A fixup function was called. "
				"This currently creates a memory leak.\n");
	}

	if (argv[0]) pkg_free(argv[0]);
	if (argv[1]) pkg_free(argv[1]);

	pkg_free(act);
	
	return 1;
}
Пример #8
0
unsigned long right(unsigned long exe_t,  unsigned long const initial_exe_t, cbuf_t cbt, int len)
{
	return do_action(exe_t,initial_exe_t, cbt, len);
}
Пример #9
0
int exec_str(struct sip_msg *msg, char *cmd, char *param, int param_len) {

    struct action act;
    struct run_act_ctx ra_ctx;
    int cmd_len;
    FILE *pipe;
    char *cmd_line;
    int ret;
    int l1;
    static char uri_line[MAX_URI_SIZE+1];
    int uri_cnt;
    str uri;
    int exit_status;

    /* pessimist: assume error by default */
    ret=-1;

    l1=strlen(cmd);
    if(param_len>0)
        cmd_len=l1+param_len+4;
    else
        cmd_len=l1+1;
    cmd_line=pkg_malloc(cmd_len);
    if (cmd_line==0) {
        ret=ser_error=E_OUT_OF_MEM;
        LM_ERR("no pkg mem for command\n");
        goto error00;
    }

    /* 'command parameter \0' */
    memcpy(cmd_line, cmd, l1);
    if(param_len>0)
    {
        cmd_line[l1]=' ';
        cmd_line[l1+1]='\'';
        memcpy(cmd_line+l1+2, param, param_len);
        cmd_line[l1+param_len+2]='\'';
        cmd_line[l1+param_len+3]=0;
    } else {
        cmd_line[l1] = 0;
    }

    pipe=popen( cmd_line, "r" );
    if (pipe==NULL) {
        LM_ERR("cannot open pipe: %s\n", cmd_line);
        ser_error=E_EXEC;
        goto error01;
    }

    /* read now line by line */
    uri_cnt=0;
    while( fgets(uri_line, MAX_URI_SIZE, pipe)!=NULL) {
        uri.s = uri_line;
        uri.len=strlen(uri.s);
        /* trim from right */
        while(uri.len && (uri.s[uri.len-1]=='\r'
                          || uri.s[uri.len-1]=='\n'
                          || uri.s[uri.len-1]=='\t'
                          || uri.s[uri.len-1]==' ' )) {
            LM_DBG("rtrim\n");
            uri.len--;
        }
        /* skip empty line */
        if (uri.len==0) continue;
        /* ZT */
        uri.s[uri.len]=0;
        if (uri_cnt==0) {
            memset(&act, 0, sizeof(act));
            act.type = SET_URI_T;
            act.val[0].type = STRING_ST;
            act.val[0].u.string = uri.s;
            init_run_actions_ctx(&ra_ctx);
            if (do_action(&ra_ctx, &act, msg)<0) {
                LM_ERR("the action for has failed\n");
                ser_error=E_OUT_OF_MEM;
                goto error02;
            }
        } else {
            if (append_branch(msg, &uri, 0, 0, Q_UNSPECIFIED, 0, 0)==-1) {
                LM_ERR("append_branch failed; too many or too long URIs?\n");
                goto error02;
            }
        }
        uri_cnt++;
    }
    if (uri_cnt==0) {
        LM_ERR("no uri from %s\n", cmd_line );
        goto error02;
    }
    /* success */
    ret=1;

error02:
    if (ferror(pipe)) {
        LM_ERR("in pipe: %s\n", strerror(errno));
        ser_error=E_EXEC;
        ret=-1;
    }
    exit_status=pclose(pipe);
    if (WIFEXITED(exit_status)) { /* exited properly .... */
        /* return false if script exited with non-zero status */
        if (WEXITSTATUS(exit_status)!=0) ret=-1;
    } else { /* exited erroneously */
        LM_ERR("cmd %s failed. exit_status=%d, errno=%d: %s\n",
               cmd, exit_status, errno, strerror(errno) );
        ret=-1;
    }
error01:
    pkg_free(cmd_line);
error00:
    return ret;
}
Пример #10
0
const unsigned char*
do_action( const unsigned char* action, CIStream* args, COStream out) {
    const unsigned char* as;
    unsigned char ac;
    int argn = 0;

    as = action;
    if ( as != NULL )
        for ( ; ; ) {
            ac = *as++;
            switch (ac) {
            case PT_END:
                return as-1;
            case PT_SEPARATOR:
                return as;
            case PT_PUT_ARG: {
                CIStream arg = args[ (*as++) - 1 ];
                cis_rewind(arg);
                cos_copy_input_stream(out,arg);
                break;
            }
            case PT_ONE_OPT:
                cos_putch(out,arg_char);
                break;

            case PT_DOMAIN: {
                CIStream inbuf;
                Pattern save_rule = current_rule;
#if MAX_DOMAINS < 256
                int domain = *as++ - 1;
#else
                /* Get domain index as 14 bit little endian number */
                int domain = ((unsigned char)*as++)&0x7f;
                domain = ((((unsigned char)*as++)&0x7f)<<7) | domain;
#endif
                if ( as[0] == PT_VAR1 ||
                        ( as[0] == PT_OP &&
                          ( as[1] == OP_VAR || as[1] == OP_VAR_DFLT ) ) ) {
                    /* for safety, copy the variable's value in case it is
                       changed during translation.  */
                    COStream outbuf;
                    outbuf = make_buffer_output_stream();
                    as = do_action( as, args, outbuf );
                    inbuf = convert_output_to_input( outbuf );
                }
                else /* optimized operand access */
                    inbuf = function_operand( &as, args );
#ifdef TRACE
                if ( trace_switch ) {
                    int n;
                    fprintf( stderr, "%12ld,%2d ",
                             cis_line(input_stream), cis_column(input_stream));
                    for ( n = trace_indent ; n > 0 ; n-- )
                        fputc(' ',stderr);
                    if ( cis_is_file(inbuf) ) {
                        const char* inpath = cis_pathname(inbuf);
                        if ( inpath == NULL )
                            inpath = "-";
                        fprintf( stderr, "@%s{@read{%s}}\n",
                                 domains[domain]->name, inpath);
                    }
                    else
                        fprintf( stderr, "@%s{%.60s}\n",
                                 domains[domain]->name, cis_whole_string(inbuf));
                    ++trace_indent;
                }
#endif
                if ( !translate( inbuf, domains[domain], out, NULL ) &&
                        cis_is_file(inbuf) && exit_status < EXS_FAIL )
                    exit_status = EXS_FAIL;
#ifdef TRACE
                if ( trace_switch ) {
                    --trace_indent;
                }
#endif
                current_rule = save_rule;
                cis_close(inbuf);
                break;
            }

            case PT_VAR1: {
                char vname[2];
                vname[0] = *as++;
                vname[1] = '\0';
                put_var(out, vname, FALSE);
                break;
            }

            case PT_LINE:
                cos_freshline(out);
                break;

            case PT_MATCHED_TEXT:
                do_action( current_rule->pattern, args, out );
                break;

            case PT_SPECIAL_ARG:
#if MAX_DOMAINS >= 256 /* advance one more since  2 bytes for domain index */
            case PT_RECUR:
#endif
                as++;
            case PT_REGEXP:
#if MAX_DOMAINS < 256
            case PT_RECUR:
#endif
                as++;
            case PT_MATCH_ANY:
            case PT_MATCH_ONE: {
                /* these will be encountered only when replaying the template as $0 */
                CIStream arg = args[ argn++ ];
                cis_rewind(arg);
                cos_copy_input_stream(out,arg);
                break;
            }

            case PT_AUX:
                as++;
                break;

            case PT_OP: {
                CIStream inbuf = NULL;
                enum Operators ac;
                ac = (enum Operators)*as++;
                switch(ac) {
                case OP_UNDEFINE:
                case OP_DEFINE: {
                    inbuf = function_operand( &as, args );
                    read_patterns(inbuf, "", ac==OP_UNDEFINE);
                    break;
                }

                case OP_SUBST: {
                    int d;
                    CIStream arg;
                    Pattern save_rule = current_rule;
                    arg = function_operand( &as, args );
                    d = read_patterns(arg," temp ",FALSE);
                    inbuf = function_operand( &as, args );
                    translate ( inbuf, domains[d], out, NULL );
                    current_rule = save_rule;
                    delete_domain(d);
                    cis_close(arg);
                    break;
                }

                case OP_VAR: {
                    inbuf = function_operand( &as, args );
                    put_var(out, cis_whole_string(inbuf), FALSE );
                    break;
                }
                case OP_VAR_DFLT: {
                    inbuf = function_operand( &as, args ); /* variable name */
                    if ( put_var(out, cis_whole_string(inbuf), TRUE ) )
                        as = skip_action(as); /* skip default value */
                    else as = do_action( as, args, out ); /* output default */
                    break;
                }

                case OP_SET: {
                    CIStream name;
                    name = function_operand( &as, args );
                    inbuf = function_operand( &as, args );
                    set_var( cis_whole_string(name),
                             cis_whole_string(inbuf), cis_length(inbuf) );
                    cis_close(name);
                    break;
                }

                case OP_BIND: {
                    CIStream name;
                    name = function_operand( &as, args );
                    inbuf = function_operand( &as, args );
                    bind_var( cis_whole_string(name),
                              cis_whole_string(inbuf), cis_length(inbuf) );
                    cis_close(name);
                    break;
                }
                case OP_UNBIND: {
                    CIStream name;
                    name = function_operand( &as, args );
                    unbind_var( cis_whole_string(name) );
                    cis_close(name);
                    break;
                }

                case OP_APPEND: {
                    CIStream name;
                    name = function_operand( &as, args );
                    inbuf = function_operand( &as, args );
                    append_var( cis_whole_string(name),
                                cis_whole_string(inbuf), cis_length(inbuf) );
                    cis_close(name);
                    break;
                }

                case OP_INCR:
                case OP_DECR: {
                    CIStream name;
                    name = function_operand( &as, args );
                    incr_var( cis_whole_string(name), ac==OP_DECR? -1 : 1 );
                    cis_close(name);
                    break;
                }

                case OP_GETENV:
                case OP_GETENV_DEFAULT: {
                    CIStream dbuf = NULL;
                    char* value;
                    inbuf = function_operand( &as, args );
                    if ( ac == OP_GETENV_DEFAULT )
                        dbuf = function_operand( &as, args );
                    value = getenv(cis_whole_string(inbuf));
                    if ( value == NULL )
                        cos_copy_input_stream(out, dbuf);
                    else cos_puts(out, value);
                    cis_close(dbuf);
                    break;
                }

                case OP_ERR: {
                    static COStream err_stream = NULL;
                    if ( err_stream == NULL )
                        err_stream = make_file_output_stream(stderr,"stderr");
                    as = do_action( as, args, err_stream );
                    break;
                }

                case OP_OUT: {
                    as = do_action( as, args, output_stream );
                    break;
                }

                case OP_PATH:
                case OP_FILE: {
                    const char* path = cis_pathname(input_stream);
                    if ( path != NULL ) {
                        if ( ac == OP_FILE )
                            path = pathname_name_and_type(path);
                        cos_puts(out, path);
                    }
                    break;
                }
                case OP_OUTFILE: {
                    const char* opath;
                    opath = cos_pathname(out);
                    if ( opath == NULL )
                        opath = cos_pathname(output_stream);
                    cos_puts(out, opath);
                    break;
                }

                case OP_LINE: {
                    put_number(out, cis_line(input_stream));
                    break;
                }
                case OP_COL: {
                    put_number(out, cis_column(input_stream));
                    break;
                }
                case OP_OUTCOL: {
                    put_number(out, cos_column(output_stream));
                    break;
                }
                case OP_HELP:
                    usage();
                    break;
                case OP_VERSION:
                    cos_puts(out, Version);
                    break;

                case OP_DATE:
                case OP_TIME: {
                    time_t now;
                    struct tm* ts;
                    char tbuf [12];
                    now = time(NULL);
                    ts = localtime(&now);
                    if ( ac == OP_TIME )
                        sprintf(tbuf, "%02d:%02d:%02d",
                                ts->tm_hour, ts->tm_min, ts->tm_sec);
                    else sprintf(tbuf, "%02d/%02d/%d",
                                     ts->tm_mon + 1, ts->tm_mday, 1900 + ts->tm_year);
                    cos_puts(out, tbuf);
                    break;
                }
                case OP_DATIME: {
                    time_t now;
                    now = time(NULL);
                    put_datime( out, &now );
                    break;
                }
                case OP_MODTIME: {
                    time_t mtime;
                    mtime = cis_mod_time(input_stream);
                    if ( mtime != 0 )
                        put_datime( out, &mtime );
                    break;
                }
                case OP_PROBE: {
                    inbuf = function_operand( &as, args );
                    cos_putch(out, probe_pathname(cis_whole_string(inbuf)));
                    break;
                }

                case OP_READ: {
                    const char* pathname;
                    CIStream in;
                    inbuf = function_operand( &as, args );
                    pathname = cis_whole_string(inbuf);
                    close_output(pathname);
                    in = open_input_file(pathname,binary);
                    cos_copy_input_stream(out, in);
                    cis_close(in);
                    break;
                }

                case OP_WRITE: {
                    COStream oldout;
                    const char* pathname;
                    oldout = output_stream;
                    inbuf = function_operand( &as, args );
                    pathname = cis_whole_string(inbuf);
                    output_stream = find_output_file(pathname,TRUE);
                    as = do_action( as, args, output_stream );
                    output_stream = oldout;
                    break;
                }

                case OP_CLOSE: {
                    inbuf = function_operand( &as, args );
                    close_output(cis_whole_string(inbuf));
                    break;
                }

                case OP_COMBINEPATH:
                case OP_MERGEPATH: {
                    CIStream dir;
                    CIStream name;
                    CIStream typ;
                    dir = function_operand( &as, args );
                    name = function_operand( &as, args );
                    typ = function_operand( &as, args );
                    merge_pathnames( out, ac==OP_COMBINEPATH, cis_whole_string(dir),
                                     cis_whole_string(name),
                                     cis_whole_string(typ) );
                    cis_close(dir);
                    cis_close(name);
                    cis_close(typ);
                    break;
                }
                case OP_RELPATH: {
                    CIStream dir;
                    dir = function_operand( &as, args );
                    inbuf = function_operand( &as, args );
                    cos_puts( out, relative_pathname(cis_whole_string(dir),
                                                     cis_whole_string(inbuf)) );
                    cis_close(dir);
                    break;
                }
                case OP_EXP_WILD: {
                    inbuf = function_operand( &as, args );
                    expand_wildcard ( cis_whole_string(inbuf), out );
                    break;
                }

                case OP_ADD:
                case OP_SUB:
                case OP_MUL:
                case OP_DIV:
                case OP_MOD:
                case OP_AND:
                case OP_OR: {
                    long x,y,z;
                    x = numeric_operand( &as, args );
                    y = numeric_operand( &as, args );
                    switch(ac) {
                    case OP_ADD:
                        z = x + y;
                        break;
                    case OP_SUB:
                        z = x - y;
                        break;
                    case OP_MUL:
                        z = x * y;
                        break;
                    case OP_DIV:
                        z = x / y;
                        break;
                    case OP_MOD:
                        z = x % y;
                        break;
                    case OP_AND:
                        z = x & y;
                        break;
                    case OP_OR:
                        z = x | y;
                        break;
                    default: /* can't happen; just to avoid compiler warning */
                        assert(FALSE);
                        z = 0;
                        break;
                    }
                    put_number(out,z);
                    break;
                }
                case OP_NOT:
                    put_number(out, ~ numeric_operand( &as, args ) );
                    break;

                case OP_RADIX: {
                    int from, to;
                    unsigned long value;
                    char* string;
                    char* end;
                    const char* fmt;
                    char buf[24]; /* enough for 64 bits in octal */
                    from = (int)numeric_operand( &as, args );
                    to = (int)numeric_operand( &as, args );
                    inbuf = function_operand( &as, args );
                    string = cis_whole_string(inbuf);
                    value = strtoul( string, &end, from );
                    if ( *end != '\0' )
                        input_error ( input_stream, EXS_NUM,
                                      "Invalid argument for radix %d conversion: \"%.99s\"\n",
                                      from, string);
                    if ( to == 8 )
                        fmt = "%lo";
                    else if ( to == 16 )
                        fmt = "%lX";
                    else {
                        if ( to != 10 )
                            input_error ( input_stream, EXS_NUM,
                                          "Unsupported radix: %d\n", to);
                        while ( isspace(string[0]) )
                            string++;
                        fmt = (string[0]=='-') ? "%ld" : "%lu";
                    }
                    sprintf(buf, fmt, value);
                    cos_puts(out, buf);
                    break;
                }

                case OP_STR_CMP:
                case OP_STRI_CMP: {	/* string comparison */
                    CIStream x = function_operand( &as, args );
                    CIStream y = function_operand( &as, args );
                    const char* xs = cis_whole_string(x);
                    const char* ys = cis_whole_string(y);
                    int cmp;
                    cmp = ac == OP_STRI_CMP ? stricmp(xs, ys) : strcmp(xs, ys);
                    cis_close(x);
                    cis_close(y);
                    as = do_cmp( cmp, as, args, out);
                    break;
                }
                case OP_NUM_CMP: {	/* numeric comparison */
                    long x = numeric_operand( &as, args );
                    long y = numeric_operand( &as, args );
                    int cmp;
                    if ( x < y )
                        cmp = -1;
                    else if ( x == y )
                        cmp = 0;
                    else cmp = 1;
                    as = do_cmp( cmp, as, args, out);
                    break;
                }

                case OP_LENGTH: {
                    inbuf = function_operand( &as, args );
                    put_number(out, cis_length(inbuf));
                    break;
                }

                case OP_TAB: {
                    int col;
                    col = (int)numeric_operand( &as, args );
                    cos_spaces(out, col - (int)cos_column(out));
                    break;
                }

                case OP_WRAP: {
                    unsigned length;
                    unsigned col;
                    inbuf = function_operand( &as, args );
                    length = cis_length(inbuf);
                    col = cos_column(out);
                    if ( ( ((int)(col + length)) > wrap_column &&
                            col > wrap_indent_length ) ||
                            ( col <= 1 && length > 0 ) ) {
                        cos_freshline(out);
                        cos_puts(out, wrap_indent);
                        skip_whitespace(inbuf);
                    }
                    cos_copy_input_stream(out, inbuf);
                    break;
                }

                case OP_SET_WRAP: {
                    wrap_column = (int)numeric_operand( &as, args );
                    inbuf = function_operand( &as, args );
                    if ( wrap_indent != NULL )
                        free(wrap_indent);
                    wrap_indent_length = cis_length(inbuf);
                    wrap_indent = str_dup_len( cis_whole_string(inbuf),
                                               wrap_indent_length );
                    break;
                }

                case OP_RIGHT:
                case OP_LEFT:
                case OP_CENTER: { /* justify value in fixed-length field */
                    int field_length, string_length, left_pad, right_pad;
                    field_length = (int)numeric_operand( &as, args );
                    inbuf = function_operand( &as, args );
                    string_length = cis_length(inbuf);
                    left_pad = field_length - string_length;
                    right_pad = 0;
                    if ( left_pad < 0 )
                        left_pad = 0;
                    if ( ac == OP_LEFT ) {
                        right_pad = left_pad;
                        left_pad = 0;
                    }
                    else if ( ac == OP_CENTER ) {
                        left_pad = left_pad / 2;
                        right_pad = field_length - string_length - left_pad;
                    }
                    cos_spaces(out, left_pad);
                    cos_copy_input_stream(out, inbuf);
                    cos_spaces(out, right_pad);
                    break;
                }

                case OP_FILL_RIGHT:
                case OP_FILL_LEFT:
                case OP_FILL_CENTER: { /* justify value in fixed-length field */
                    int field_length, string_length, left_pad, right_pad;
                    CIStream background;
                    int i;
                    background = function_operand( &as, args );
                    field_length = cis_length(background);
                    inbuf = function_operand( &as, args );
                    string_length = cis_length(inbuf);
                    left_pad = field_length - string_length;
                    right_pad = 0;
                    if ( left_pad < 0 )
                        left_pad = 0;
                    if ( ac == OP_FILL_LEFT ) {
                        right_pad = left_pad;
                        left_pad = 0;
                    }
                    else if ( ac == OP_FILL_CENTER ) {
                        left_pad = left_pad / 2;
                        right_pad = field_length - string_length - left_pad;
                    } else assert( ac == OP_FILL_RIGHT );
                    for ( i = left_pad ; i > 0 ; i-- )
                        cos_putch(out, cis_getch(background));
                    cos_copy_input_stream(out, inbuf);
                    if ( right_pad > 0 ) {
                        for ( i = string_length ; i > 0 ; i-- )
                            (void)cis_getch(background);
                        cos_copy_input_stream(out, background);
                    }
                    cis_close(background);
                    break;
                }

                case OP_SUBSTRING: {
                    int skip_length, result_length, string_length;
                    skip_length = (int)numeric_operand( &as, args );
                    result_length = (int)numeric_operand( &as, args );
                    inbuf = function_operand( &as, args );
                    string_length = cis_length(inbuf);
                    if ( skip_length <= string_length ) {
                        if ( skip_length < 0 )
                            skip_length = 0;
                        if ( (skip_length + result_length) > string_length )
                            result_length = string_length - skip_length;
                        cos_put_len(out, cis_whole_string(inbuf) + skip_length,
                                    result_length);
                    }
                    break;
                }

                case OP_DOWNCASE:
                case OP_UPCASE: {
                    int cc;
                    inbuf = function_operand( &as, args );
                    while ( (cc = cis_getch(inbuf)) != EOF )
                        cos_putch(out, ac==OP_DOWNCASE ? tolower(cc) : toupper(cc) );
                    break;
                }

                case OP_CHARINT:
                    inbuf = function_operand( &as, args );
                    put_number(out, cis_getch(inbuf));
                    break;
                case OP_INTCHAR:
                    cos_putch(out, (char)numeric_operand( &as, args ));
                    break;

                case OP_REVERSE: {
                    int len;
                    const char* start;
                    const char* ip;
                    inbuf = function_operand( &as, args );
                    len = cis_length(inbuf);
                    start = cis_whole_string(inbuf);
                    for ( ip = start+len-1 ; ip >= start ; ip-- )
                        cos_putch(out, *ip);
                    break;
                }

                case OP_SHELL: {
                    const char* command;
                    inbuf = function_operand( &as, args );
                    command = cis_whole_string(inbuf);
                    fflush(stdout);
                    if ( system( command ) < 0 ) {
                        input_error ( input_stream, EXS_SHELL,
                                      "Failed shell command \"%.20s...\":\n", command );
                        perror("system");
                    }
                    break;
                }

                case OP_EXIT:
                    translation_status = Translate_Exited;
                    break;

                case OP_FAIL:
                    translation_status = Translate_Failed;
                    break;

                case OP_END_OR_FAIL:
                    /* ideally this should be testing whether the input stream
                       has been advanced, but that is not so easy. */
                    translation_status =
                        ( cis_out_length(out) == 0 )? Translate_Failed : Translate_Exited;
                    break;

                case OP_EXIT_STATUS:
                    exit_status = (Exit_States)(int)numeric_operand( &as, args );
                    break;

                case OP_ABORT:
                    exit((int)(exit_status > EXS_FAIL ? exit_status : EXS_FAIL ));
                    break;

                case OP_GET_SWITCH:
                case OP_SET_SWITCH: {
                    const char* name;
                    int* valpt;
                    inbuf = function_operand( &as, args );
                    name = cis_whole_string(inbuf);
                    valpt = find_switch(name);
                    if ( valpt == NULL ) {
                        input_error(input_stream, EXS_UNDEF,
                                    "Undefined switch name \"%.99s\"\n", name );
                        if ( ac == OP_SET_SWITCH )
                            (void)numeric_operand( &as, args );
                    }
                    else {
                        if ( ac == OP_SET_SWITCH )
                            *valpt = (int)numeric_operand( &as, args );
                        else
                            put_number( out, *valpt );
                    }
                    break;
                }

                case OP_SET_PARM: {
                    const char* name;
                    CIStream val;
                    inbuf = function_operand( &as, args );
                    name = cis_whole_string(inbuf);
                    val = function_operand( &as, args );
                    if ( !set_parm( name, cis_whole_string(val) ) )
                        input_error(input_stream, EXS_UNDEF,
                                    "Undefined parameter name \"%.99s\"\n", name );
                    cis_close(val);
                    break;
                }

                case OP_SYNTAX: {
                    const char* type;
                    const char* charset;
                    CIStream val;
                    inbuf = function_operand( &as, args );
                    val = function_operand( &as, args );
                    charset = cis_whole_string(val);
                    for ( type = cis_whole_string(inbuf) ; *type != '\0' ; type++ ) {
                        const char* chars;
                        char c[2];
                        if ( type[1] == '\0' )
                            chars = charset;
                        else {
                            c[0] = *charset++;
                            c[1] = '\0';
                            chars = c;
                        }
                        if ( !set_syntax(type[0], chars) )
                            input_error(input_stream, EXS_UNDEF,
                                        "Undefined syntax type \"%.99s\"\n", type );
                    }
                    cis_close(val);
                    break;
                }

                case OP_DEFAULT_SYNTAX:
                    initialize_syntax();
                    break;

#ifndef MSDOS
                case OP_LOCALE: {
                    const char* lname;
                    inbuf = function_operand( &as, args );
                    lname = cis_whole_string(inbuf);
                    if ( setlocale(LC_ALL, lname) == NULL )
                        input_error(input_stream, EXS_UNDEF,
                                    "Undefined locale \"%.99s\"\n", lname );
                    break;
                }
#endif

                case OP_REPEAT: {
                    long n = numeric_operand( &as, args );
                    if ( n <= 0 )
                        as = skip_action(as);
                    else {
                        const unsigned char* start = as;
                        for ( ; n > 0 ; n-- )
                            as = do_action( start, args, out );
                    }
                    break;
                }

                case OP_QUOTE: {
                    inbuf = function_operand( &as, args );
                    quoted_copy( inbuf, out );
                    break;
                }
                default:
                    fprintf(stderr, "Undefined op in action: %d\n", (int)ac);
                    break;

                } /* end switch on ops */
                cis_close(inbuf);
                break;
                } /* end PT_OP */

            case PT_WORD_DELIM:
            case PT_ID_DELIM:
                /* Ignore if in expansion of "$0" */
                if ( current_rule == NULL || action != current_rule->pattern ) {
                    /* output a space if needed as a delimiter */
                    int prevch = cos_prevch(out);
                    if ( prevch != EOF )
                        if ( ac == PT_ID_DELIM ? isident(prevch) : isalnum(prevch) )
                            cos_putch(out,' ');
                }
                break;
#if 0   /* not needed now */
            case PT_ARG_DELIM:
                if ( cos_prevch(out) != Arg_Delim )
                    cos_putch(out,Arg_Delim);
                break;
#endif

            case PT_SPACE: {
                /* output a space if the last character is not white space */
                int prevch = cos_prevch(out);
                if ( !isspace(prevch) )
                    cos_putch(out,' ');
                break;
            }

            case PT_SKIP_WHITE_SPACE:
                break;

            case PT_QUOTE:		/* use next character literally */
                ac = *as++;
            /* and fall-through */
            default:
                cos_putch(out, ac);
            } /* end switch ac */
        } /* end for */
    /* can't ever get here, but return to avoid Gnu compiler warning. */
    return as;
}
Пример #11
0
static
LRESULT CALLBACK mouse_ll_proc(int code, WPARAM wparam, LPARAM lparam)
{
    MSLLHOOKSTRUCT *msll;

    if(code < 0) {
        goto norm_end;
    }

    msll = (MSLLHOOKSTRUCT *)lparam;

    if(msll->flags & LLMHF_INJECTED) {
        goto norm_end;
    }

    if(ctx.mode_data.cur_conf == NULL) {
        goto norm_end;
    }

    {
        int motion, btn;

        motion = msg_to_motion(wparam);
        btn = msg_to_button(wparam, msll->mouseData);

        if(ctx.hook_data.pressed) {
            struct mouse_action *cmb_d_act, *cmb_u_act;

            ctx.hook_data.pressed = 0;
            KillTimer(NULL, comb_timer_id);

            cmb_d_act = &ctx.mode_data.cur_conf->
                        button[ctx.hook_data.pressed_btn].comb_d_act[btn];
            cmb_u_act = &ctx.mode_data.cur_conf->
                        button[ctx.hook_data.pressed_btn].comb_u_act[btn];

            if(motion == MOTION_DOWN &&
               (cmb_d_act->code != MOUSE_ACT_NOTHING ||
                cmb_u_act->code != MOUSE_ACT_NOTHING)) {
                /* combination press */
                do_action(cmb_d_act, msll);

                ctx.hook_data.
                    combination[ctx.hook_data.combinated * 2] =
                    ctx.hook_data.pressed_btn;
                ctx.hook_data.
                    combination[ctx.hook_data.combinated * 2 + 1] = btn;
                ctx.hook_data.combinated += 1;

                return 1;
            }

            do_action(&ctx.mode_data.cur_conf->
                      button[ctx.hook_data.pressed_btn].d_act,
                      &ctx.hook_data.pressed_btn_data);
        }

        if(btn >= 0) {
            /* check ignore mask */
            if(ctx.hook_data.ignore_btn_mask & MOUSE_BTN_BIT(btn)) {
                ctx.hook_data.ignore_btn_mask &= ~MOUSE_BTN_BIT(btn);
                return 1;
            }

            if(motion == MOTION_DOWN) {
                /* try combination */
                if(ctx.mode_data.cur_conf->button[btn].flags &
                   MOUSE_BTN_CONF_ENABLE_COMB) {
                    ctx.hook_data.pressed = 1;
                    ctx.hook_data.pressed_btn = btn;
                    memcpy(&ctx.hook_data.pressed_btn_data, msll,
                           sizeof(MSLLHOOKSTRUCT));
                    comb_timer_id = SetTimer(NULL, 0,
                                             ctx.app_conf.comb_time,
                                             comb_timer);
                    return 1;
                }
            }

            if(motion == MOTION_UP) {
                if(ctx.hook_data.combinated) {
                    int i;

                    for(i = 0; i < ctx.hook_data.combinated; i++) {
                        /* combination release */
                        if(ctx.hook_data.combination[i * 2] == btn ||
                           ctx.hook_data.combination[i * 2 + 1] == btn) {
                            do_action(
                                &ctx.mode_data.cur_conf->
                                button[ctx.hook_data.combination[i * 2]].
                                comb_u_act[
                                    ctx.hook_data.combination[i * 2 + 1]],
                                msll);

                            ctx.hook_data.ignore_btn_mask |=
                                MOUSE_BTN_BIT(
                                    btn == ctx.hook_data.combination[i * 3] ?
                                    ctx.hook_data.combination[i * 3 + 1] :
                                    ctx.hook_data.combination[i * 3]);

                            memmove(&ctx.hook_data.combination[i * 2],
                                    &ctx.hook_data.combination[(i + 1) * 2],
                                    sizeof(ctx.hook_data.combination[0]) *
                                    (ctx.hook_data.combinated - i - 1));
                            ctx.hook_data.combinated -= 1;

                            return 1;
                        }
                    }
                }
            }

            /* generic action */
            if(motion == MOTION_DOWN) {
                do_action(&ctx.mode_data.cur_conf->button[btn].d_act, msll);
            } else {
                do_action(&ctx.mode_data.cur_conf->button[btn].u_act, msll);
            }

            return 1;
        }

        if(motion == MOTION_WHEEL) {
            if(ctx.mode_data.cur_conf->wheel_act.code == MOUSE_ACT_WHEEL) {
                goto norm_end;
            }

            do_action(&ctx.mode_data.cur_conf->wheel_act, msll);

            return 1;
        }

        if(motion == MOTION_MOVE) {
            if(ctx.mode_data.cur_conf->move_act.code == MOUSE_ACT_MOVE) {
                goto norm_end;
            }

            do_action(&ctx.mode_data.cur_conf->move_act, msll);

            return 1;
        }
    }

  norm_end:
    return CallNextHookEx(mouse_ll_hook, code, wparam, lparam);
}
Пример #12
0
static CIStream
function_operand( const unsigned char** asp, CIStream* args ) {
    const unsigned char* ap;
    ap = *asp;
    if ( ap[2] == PT_SEPARATOR ) {
        if ( ap[0] == PT_PUT_ARG ) {
            /* special case when operand is $n and nothing else */
            CIStream arg = args[ ap[1] - 1 ];
            *asp = ap+3;
            cis_rewind(arg);
            return clone_input_stream( arg );
        } /* end PUT_PUT_ARG */
        if ( ap[0] == PT_VAR1 ) {
            /* special case for variable to avoid copying the value */
            char vname[2];
            size_t len;
            const char* value;
            vname[0] = ap[1];
            vname[1] = '\0';
            value = get_var(vname, TRUE, &len);
            if ( value != NULL ) {
                *asp = ap+3;
                return make_string_input_stream(value, len, FALSE);
            }
        }
    }
    if ( ap[0] == PT_OP ) {
        if ( ap[1] == OP_READ ) {
            CIStream path;
            ap += 2;
            path = function_operand( &ap, args );
            if ( *ap == PT_SEPARATOR ) {
                /* special case when operand is "@include{...}" and nothing else. */
                const char* pathname;
                CIStream istream;
                pathname = cis_whole_string(path);
                if ( strcmp(canonicalize_path(cos_pathname(output_stream)),
                            canonicalize_path(pathname))==0 ) {
                    /* Using same file for translation input and output --
                       actually read the backup file instead. */
                    if ( current_backup != NULL )
                        pathname = current_backup;
                    else input_error( input_stream, EXS_INPUT,
                                          "input and output files same but no backup\n" );
                }
                else
                    close_output(pathname);
                istream = open_input_file(pathname, binary );
                if ( istream == NULL )
                    istream = make_string_input_stream("", 0, FALSE);
                *asp = ap + 1;
                cis_close(path);
                return istream;
            }
            cis_close(path);
        } /* end OP_READ */
#if 0	/* changed my mind; use @read{-} instead of of @stdin{}   */
        else if ( ap[1] == OP_STDIN && ap[2] == PT_SEPARATOR ) {
            *asp = ap + 3;
            return stdin_stream;
        }
#endif
    } /* end PT_OP */
    {
        /* else general case */
        COStream outbuf;
        outbuf = make_buffer_output_stream();
        *asp = do_action( *asp, args, outbuf );
        return convert_output_to_input( outbuf );
    }
}
Пример #13
0
static void* thread_callback(void* raw_arg)
{
    return (void*) do_action((const char*) raw_arg);
}
Пример #14
0
Файл: ne.c Проект: vigna/ne
int main(int argc, char **argv) {

	char *locale = setlocale(LC_ALL, "");
	for(int i = 0; i < 256; i++) localised_up_case[i] = toupper(i);

	if (locale) {
		struct re_pattern_buffer re_pb;
		struct re_registers re_reg;
		memset(&re_pb, 0, sizeof re_pb);
		memset(&re_reg, 0, sizeof re_reg);

		re_pb.translate = localised_up_case;
		re_compile_pattern(LOCALE_REGEX, strlen(LOCALE_REGEX), &re_pb);
		if (re_search(&re_pb, locale, strlen(locale), 0, strlen(locale), &re_reg) >= 0) {
			if (re_reg.start[1] >= 0) io_utf8 = true;
		}
		free(re_reg.start);
		free(re_reg.end);
	}

	bool no_config = false;
	char *macro_name = NULL, *key_bindings_name = NULL, *menu_conf_name = NULL, *startup_prefs_name = DEF_PREFS_NAME;

	char * const skiplist = calloc(argc, 1);
	if (!skiplist) exit(1);  /* We need this many flags. */

	for(int i = 1; i < argc; i++) {

		if (argv[i][0] == '-' && (!strcmp(&argv[i][1], "h") || !strcmp(&argv[i][1], "-help" "\0" VERSION_STRING))) {
			puts(ARG_HELP);
			exit(0);
		}

		/* Special arguments start with two dashes. If we find one, we
		   cancel its entry in argv[], so that it will be skipped when opening
		   the specified files. The only exception is +N for skipping to the
		   N-th line. */

		if (argv[i][0] == '-' && argv[i][1] == '-') {
			if (!argv[i][2]) i++; /* You can use "--" to force the next token to be a filename */
			else if (!strcmp(&argv[i][2], "noconfig") || !strcmp(&argv[i][2], "no-config")) {
				no_config = true;
				skiplist[i] = 1; /* argv[i] = NULL; */
			}
			else if (!strcmp(&argv[i][2], "noansi") || !strcmp(&argv[i][2], "no-ansi")) {
				ansi = false;
				skiplist[i] = 1; /* argv[i] = NULL; */
			}
			else if (!strcmp(&argv[i][2], "no-syntax")) {
				do_syntax = false;
				skiplist[i] = 1; /* argv[i] = NULL; */
			}
			else if (!strcmp(&argv[i][2], "prefs")) {
				if (i < argc-1) {
					startup_prefs_name = argv[i+1];
					skiplist[i] = skiplist[i+1] = 1; /* argv[i] = argv[i+1] = NULL; */
				}
			}
			else if (!strcmp(&argv[i][2], "ansi")) {
				ansi = true;
				skiplist[i] = 1; /* argv[i] = NULL; */
			}
			else if (!strcmp(&argv[i][2], "utf8")) {
				io_utf8 = true;
				skiplist[i] = 1; /* argv[i] = NULL; */
			}
			else if (!strcmp(&argv[i][2], "no-utf8")) {
				io_utf8 = false;
				skiplist[i] = 1; /* argv[i] = NULL; */
			}
			else if (!strcmp(&argv[i][2], "macro")) {
				if (i < argc-1) {
					macro_name = argv[i+1];
					skiplist[i] = skiplist[i+1] = 1; /* argv[i] = argv[i+1] = NULL; */
				}
			}
			else if (!strcmp(&argv[i][2], "keys")) {
				if (i < argc-1) {
					key_bindings_name = argv[i+1];
					skiplist[i] = skiplist[i+1] = 1; /* argv[i] = argv[i+1] = NULL; */
				}
			}
			else if (!strcmp(&argv[i][2], "menus")) {
				if (i < argc-1) {
					menu_conf_name = argv[i+1];
					skiplist[i] = skiplist[i+1] = 1; /* argv[i] = argv[i+1] = NULL; */
				}
			}
		}
	}

#ifdef NE_TEST
	/* Dump the builtin menu and key bindings to compare to
	   doc/default.menus and doc/default.keys. */
	int dump_config(void);
	dump_config();
#endif

	/* Unless --noconfig was specified, we try to configure the
	   menus and the keyboard. Note that these functions can exit() on error. */

	if (!no_config) {
		get_menu_configuration(menu_conf_name);
		get_key_bindings(key_bindings_name);
	}

	/* If we cannot even create a buffer, better go... */

	if (!new_buffer()) exit(1);

	/* Now that key_bindings are loaded, try to fix up the message for NOT_FOUND. */
	{
		char *repeat_last_keystroke, *new_not_found;
		if ((repeat_last_keystroke = find_key_strokes(REPEATLAST_A, 1))) {
			if ((new_not_found = malloc(39+strlen(repeat_last_keystroke)))) {
				strcat(strcat(strcpy(new_not_found, "Not Found. (RepeatLast with "), repeat_last_keystroke), " to wrap.)");
				error_msg[NOT_FOUND] = new_not_found;
			}
			free(repeat_last_keystroke);
		}
	}

	clear_buffer(cur_buffer);

	/* The INT_MAX clip always exists, and it is used by the Through command. */

	clip_desc * const cd = alloc_clip_desc(INT_MAX, 0);
	if (!cd) exit(1);

	add_head(&clips, &cd->cd_node);

	/* General terminfo and cursor motion initalization. From here onwards,
	   we cannot exit() lightly. */

	term_init();

	/* We will be always using the last line for the status bar. */

	set_terminal_window(ne_lines-1);

	/* We read in all the key capabilities. */

	read_key_capabilities();

	/* Some initializations of other modules... */

	re_set_syntax(
		RE_CONTEXT_INDEP_ANCHORS |
		RE_CONTEXT_INDEP_OPS     | RE_HAT_LISTS_NOT_NEWLINE |
		RE_NEWLINE_ALT           | RE_NO_BK_PARENS          |
		RE_NO_BK_VBAR            | RE_NO_EMPTY_RANGES
	);

	bool first_file = true;

	load_virtual_extensions();
	load_auto_prefs(cur_buffer, startup_prefs_name);

	buffer *stdin_buffer = NULL;
	if (!isatty(fileno(stdin))) {
		first_file = false;
		const int error = load_fd_in_buffer(cur_buffer, fileno(stdin));
		print_error(error);
		stdin_buffer = cur_buffer;

		if (!(freopen("/dev/tty", "r", stdin))) {
			fprintf(stderr, "Cannot reopen input tty\n");
			abort();
		}
	}

	/* The terminal is prepared for interactive I/O. */

	set_interactive_mode();

	clear_entire_screen();

	/* This function sets fatal_code() as signal interrupt handler
	   for all the dangerous signals (SIGILL, SIGSEGV etc.). */

	set_fatal_code();

	if (argc > 1) {

		/* The first file opened does not need a NEWDOC_A action. Note that
		   file loading can be interrupted (wildcarding can sometimes produce
		   unwanted results). */

		uint64_t first_line = 0, first_col = 0;
		bool binary = false, skip_plus = false, read_only = false;
		stop = false;

		for(int i = 1; i < argc && !stop; i++) {
			if (argv[i] && !skiplist[i]) {
				if (argv[i][0] == '+' && !skip_plus) {       /* looking for "+", or "+N" or "+N,M"  */
					uint64_t tmp_l = INT64_MAX, tmp_c = 0;
					char *d;
					errno = 0;
					if (argv[i][1]) {
						if (isdigit((unsigned char)argv[i][1])) {
							tmp_l = strtoll(argv[i]+1, &d, 10);
							if (!errno) {
								if (*d) {  /* separator between N and M */
									if (isdigit((unsigned char)d[1])) {
										tmp_c = strtoll(d+1, &d, 10);
										if (*d) errno = ERANGE;
									}
									else errno = ERANGE;
								}
							}
						}
						else errno = ERANGE;
					}
					if (!errno) {
						first_line = tmp_l;
						first_col  = tmp_c;
					}
					else {
						skip_plus = true;
						i--;
					}
				}
				else if (!strcmp(argv[i], "--binary")) {
					binary = true;
				}
				else if (!strcmp(argv[i], "--read-only") || !strcmp(argv[i], "--readonly") || !strcmp(argv[i], "--ro")) {
					read_only = true;
				}
				else {
					if (!strcmp(argv[i], "-") && stdin_buffer) {
						stdin_buffer->opt.binary = binary;
						if (read_only) stdin_buffer->opt.read_only = read_only;
						if (first_line) do_action(stdin_buffer, GOTOLINE_A, first_line, NULL);
						if (first_col)  do_action(stdin_buffer, GOTOCOLUMN_A, first_col, NULL);
						stdin_buffer = NULL;
					}
					else {
						if (!strcmp(argv[i], "--")) i++;
						if (!first_file) do_action(cur_buffer, NEWDOC_A, -1, NULL);
						else first_file = false;
						cur_buffer->opt.binary = binary;
						if (i < argc) do_action(cur_buffer, OPEN_A, 0, str_dup(argv[i]));
						if (first_line) do_action(cur_buffer, GOTOLINE_A, first_line, NULL);
						if (first_col)  do_action(cur_buffer, GOTOCOLUMN_A, first_col, NULL);
						if (read_only) cur_buffer->opt.read_only = read_only;
					}
					first_line =
					first_col  = 0;
					skip_plus  =
					binary    =
					read_only  = false;
				}
			}
		}

		free(skiplist);

		/* This call makes current the first specified file. It is called
		   only if more than one buffer exist. */

		if (get_nth_buffer(1)) do_action(cur_buffer, NEXTDOC_A, -1, NULL);

	}

	/* We delay updates. In this way the macro activity does not cause display activity. */

	reset_window();
	delay_update();

	if (macro_name) do_action(cur_buffer, MACRO_A, -1, str_dup(macro_name));
	else if (first_file) {
		/* If there is no file to load, and no macro to execute, we display
		   the "NO WARRANTY" message. */
		about();
	}

	while(true) {
		/* If we are displaying the "NO WARRANTY" info, we should not refresh the
		   window now */
		if (!displaying_info) {
			refresh_window(cur_buffer);
			if (cur_buffer->opt.automatch) automatch_bracket(cur_buffer, true);
		}

		draw_status_bar();
		move_cursor(cur_buffer->cur_y, cur_buffer->cur_x);

		int c = get_key_code();

		if (window_changed_size) {
			print_error(do_action(cur_buffer, REFRESH_A, 0, NULL));
			window_changed_size = displaying_info = false;
			cur_buffer->automatch.shown = 0;
		}

		if (c == INVALID_CHAR) continue; /* Window resizing. */
		const input_class ic = CHAR_CLASS(c);

		if (displaying_info) {
			refresh_window(cur_buffer);
			displaying_info = false;
		}

		if (cur_buffer->automatch.shown) automatch_bracket(cur_buffer, false);

		switch(ic) {
		case INVALID:
			print_error(INVALID_CHARACTER);
			break;

		case ALPHA:
			print_error(do_action(cur_buffer, INSERTCHAR_A, c, NULL));
			break;

		case TAB:
			print_error(do_action(cur_buffer, INSERTTAB_A, 1, NULL));
			break;

		case RETURN:
			print_error(do_action(cur_buffer, INSERTLINE_A, -1, NULL));
			break;

		case COMMAND:
			if (c < 0) c = -c - 1;
			if (key_binding[c]) print_error(execute_command_line(cur_buffer, key_binding[c]));
			break;

		default:
			break;
		}
	}
}
Пример #15
0
static PyObject *msg_call_function(msgobject *self, PyObject *args)
{
	int i, rval;
	char *fname, *arg1, *arg2;
	sr31_cmd_export_t* fexport;
	struct action *act;
	struct run_act_ctx ra_ctx;
	unsigned mod_ver;

	if (self->msg == NULL) {
		PyErr_SetString(PyExc_RuntimeError, "self->msg is NULL");
		Py_INCREF(Py_None);
		return Py_None;
	}

	i = PySequence_Size(args);
	if (i < 1 || i > 3) {
		PyErr_SetString(PyExc_RuntimeError, "call_function() should " \
				"have from 1 to 3 arguments");
		Py_INCREF(Py_None);
		return Py_None;
	}

	if(!PyArg_ParseTuple(args, "s|ss:call_function", &fname, &arg1, &arg2))
		return NULL;

	fexport = find_export_record(fname, i - 1, 0, &mod_ver);
	if (fexport == NULL) {
		PyErr_SetString(PyExc_RuntimeError, "no such function");
		Py_INCREF(Py_None);
		return Py_None;
	}

	act = mk_action(MODULE2_T, 4 /* number of (type, value) pairs */,
			MODEXP_ST, fexport, /* function */
			NUMBER_ST, 2,       /* parameter number */
			STRING_ST, arg1,    /* param. 1 */
			STRING_ST, arg2     /* param. 2 */
			);

	if (act == NULL) {
		PyErr_SetString(PyExc_RuntimeError,
				"action structure could not be created");
		Py_INCREF(Py_None);
		return Py_None;
	}

	if (fexport->fixup != NULL) {
		if (i >= 3) {
			rval = fexport->fixup(&(act->val[3].u.data), 2);
			if (rval < 0) {
				PyErr_SetString(PyExc_RuntimeError, "Error in fixup (2)");
				Py_INCREF(Py_None);
				return Py_None;
			}
			act->val[3].type = MODFIXUP_ST;
		}
		if (i >= 2) {
			rval = fexport->fixup(&(act->val[2].u.data), 1);
			if (rval < 0) {
				PyErr_SetString(PyExc_RuntimeError, "Error in fixup (1)");
				Py_INCREF(Py_None);
				return Py_None;
			}
			act->val[2].type = MODFIXUP_ST;
		}
		if (i == 1) {
			rval = fexport->fixup(0, 0);
			if (rval < 0) {
				PyErr_SetString(PyExc_RuntimeError, "Error in fixup (0)");
				Py_INCREF(Py_None);
				return Py_None;
			}
		}
	}

	init_run_actions_ctx(&ra_ctx);
	rval = do_action(&ra_ctx, act, self->msg);

	if ((act->val[3].type == MODFIXUP_ST) && (act->val[3].u.data)) {
		pkg_free(act->val[3].u.data);
	}

	if ((act->val[2].type == MODFIXUP_ST) && (act->val[2].u.data)) {
		pkg_free(act->val[2].u.data);
	}

	pkg_free(act);

	return PyInt_FromLong(rval);
}
Пример #16
0
//int main(int argc,char *argv[])
int server_socket_init(void)
{
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY); 
    server_addr.sin_port = htons(PORT);
    int client_sockfd =0;
	int on = 1; 
	int need_connect = 1;

    int size;
    char buffer[MAX_BUFFER + 1];
    struct sockaddr_in client_addr;
    socklen_t len = sizeof(client_addr);

    //reigster ctrl+c /ctrl+z signal.
    signal(SIGINT, signalHandler); 
    signal(SIGTSTP, signalHandler); 

    server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if((setsockopt(server_sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on))) < 0) {  
        perror("setsockopt failed");  
        exit(EXIT_FAILURE);  
    }  

    bind(server_sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    
    /* listen */
    listen(server_sockfd, 5);
    
    #ifndef UBUNTU_HOST
        mini_car_gpio_init();
    #endif

    while(1) 
    {
        if(need_connect) {
            printf("waiting connection...\n");
            client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_addr, &len);
            need_connect = 0;
            printf("connect client ok!\n");
			start_camera();
        }

        memset(buffer, 0, MAX_BUFFER);
        size = read(client_sockfd, buffer, 4);
        // printf("Got %d bytes: %s\n", size, buffer);
        
        if(size == 0) {
            continue;
        }
        
        do_action(buffer, NULL);
        if(atoi(buffer) == MSG_STOP) {
            printf("disconnect client !\n");
            close(client_sockfd);
            client_sockfd = 0;
            need_connect = 1;
            //send_signal_to_proc(SIGINT, "mjpg_streamer");
        }
    }
    
    close(server_sockfd);
    return 0;
}
Пример #17
0
Файл: input.c Проект: dmt4/ne
static void input_autocomplete(void) {
	int dx = 0, prefix_pos = pos;
	char *p;

	/* find a usable prefix */
	if (prefix_pos && prefix_pos <= len) {
		prefix_pos = prev_pos(input_buffer, prefix_pos, encoding);
		dx--;
		while (prefix_pos && ne_isword(get_char(&input_buffer[prefix_pos], encoding), encoding)) {
			dx--;
			prefix_pos = prev_pos(input_buffer, prefix_pos, encoding);
		}
		if (! ne_isword(get_char(&input_buffer[prefix_pos], encoding), encoding)) {
			dx++;
			prefix_pos = next_pos(input_buffer, prefix_pos, encoding);
		}
		p = malloc(pos - prefix_pos + 1);
		if (!p) {
			alert(); /* OUT_OF_MEMORY */
			return;
		}
		strncpy(p, &input_buffer[prefix_pos], pos - prefix_pos);
	}
	else p = malloc(1); /* no prefix left of the cursor; we'll give an empty one. */
	p[pos - prefix_pos] = 0;

	int ac_err;
	if (p = autocomplete(p, NULL, true, &ac_err)) {
		encoding_type ac_encoding = detect_encoding(p, strlen(p));
		if (ac_encoding != ENC_ASCII && encoding != ENC_ASCII && ac_encoding != encoding) {
			free(p);
			alert();
		} else {
			encoding = ac_encoding;

			if (prefix_pos < pos) {
				memmove(&input_buffer[prefix_pos], &input_buffer[pos], len - pos + 1);
				len -= pos - prefix_pos;
				pos = prefix_pos;
			}
			int ac_len = strlen(p);
			if (ac_len + len >= MAX_INPUT_LINE_LEN) ac_len = MAX_INPUT_LINE_LEN - len;
			memmove(&input_buffer[pos + ac_len], &input_buffer[pos], len - pos + 1);
			memmove(&input_buffer[pos], p, ac_len);
			len += ac_len;
			while (ac_len > 0) {
				const int cw = get_char_width(&input_buffer[pos],encoding);
				pos = next_pos(input_buffer, pos, encoding);
				ac_len -= cw;
				dx++;
			}
			free(p); 
			x += dx;
			if (x >= ne_columns) {
				dx = x - ne_columns + 1;
				while (dx--) {
					offset = next_pos(input_buffer, offset, encoding);
				}
				x = ne_columns - 1;
			}
		}
	}
	if (ac_err == AUTOCOMPLETE_COMPLETED || ac_err == AUTOCOMPLETE_CANCELLED) {
		do_action(cur_buffer, REFRESH_A, 0, NULL);
		refresh_window(cur_buffer);
		set_attr(0);
		print_prompt(NULL);
	}
	input_refresh();
}
Пример #18
0
lr_symbol* lr_parser::parse()
{
  /* set up direct reference to tables to drive the parser */
  production_tab = production_table();
  action_tab     = action_table();
  reduce_tab     = reduce_table();

  /* initialize the action encapsulation object */
  init_actions();

  /* do user initialization */
  user_init();

  /* get the first token */
  cur_token = scan();

  /* push dummy symbol with start state to get us underway */
  stack.remove_all_elements();
  lr_symbol dummy_sym(0, start_state());
  stack.push(&dummy_sym);

  /* continue until accept or fatal error */
  while (true)
    {
      /* Check current token for freshness. */
      assert(-1 == cur_token->parse_state);

      /* current state is always on the top of the stack */

      /* look up action out of the current state with the current input */
      int act = get_action(stack.peek()->parse_state, cur_token->sym);

      /* decode the action -- > 0 encodes shift */
      if (act > 0)
        {
          act = act - 1;

          DEBUG_LOG("Shift and goto " << act);

          /* shift to the encoded state by pushing it on the stack */
          cur_token->parse_state = act;
          stack.push(cur_token);

          /* advance to the next Symbol */
          cur_token = scan();
        }
      /* if its less than zero, then it encodes a reduce action */
      else if (act < 0)
        {
          act = (-act) - 1;

          DEBUG_LOG("Reduce by rule " << act);

          /* perform the action for the reduce */
          lr_symbol* lhs_sym = do_action(act);

          /* check for accept indication */
          if (lhs_sym == 0)
            {
              return stack.peek();
            }

          /* look up information about the production */

          lhs_sym->sym      = production_tab[act].lhs_sym;
          short handle_size = production_tab[act].rhs_size;

          /* pop the handle off the stack */
          stack.npop(handle_size);

          /* look up the state to go to from the one popped back to */
          act = get_reduce(stack.peek()->parse_state, lhs_sym->sym);

          /* shift to that state */
          lhs_sym->parse_state = act;
          stack.push(lhs_sym);

          DEBUG_LOG("      and goto " << act);
        }
      /* finally if the entry is zero, we have an error */
      else if (act == 0)
        {
          DEBUG_LOG("Error");

          /* call user syntax error reporting routine */
          syntax_error(cur_token);

          /* try to error recover */
          switch (error_recovery())
            {
            case ERS_FAIL:
              /* if that fails give up with a fatal syntax error */
              unrecovered_syntax_error(cur_token);
              return 0;
            case ERS_SUCCESS:
              break;
            case ERS_ACCEPT:
              return stack.peek();
            default:
              assert(0);
            }
        }
    }

}
Пример #19
0
/* Event handler in Podzilla compiling style */
static int tuxchess_handle_event(GR_EVENT *event)
{
	int ret = 0;
	switch (event->type)
	{
	case GR_EVENT_TYPE_KEY_DOWN:
		switch (event->keystroke.ch)
		{
		case'm':
			do_menu();
			ret |= KEY_CLICK;
			break;

		case'w':
			if (end == 0) {
				do_rev();
				ret |= KEY_CLICK;
			}
			break;

		case'f':
			if (end == 0) {
				do_fwd();
				ret |= KEY_CLICK;
			}
			break;

		case'\r':
			if (end == 0) {
				do_action();
			}
			else if (end == 1) {
				draw_end(end_type);
			}
			else {
				new_game();
			}
			ret |= KEY_CLICK;
			break;

		case'l':
			if (end == 0) {
				do_left();
				ret |= KEY_CLICK;
			}
			break;

		case'r':
			if (end == 0) {
				do_right();
				ret |= KEY_CLICK;
			}
			break;

		default:
			ret |= KEY_UNUSED;
			break;
		}
		break;
	default:
		ret |= EVENT_UNUSED;
		break;
	}

	return ret;
}
Пример #20
0
lr_parser::ers_t  lr_parser::parse_lookahead()
{
  /* restart the saved input at the beginning */
  lookahead_pos = 0;

  DEBUG_LOG("# Reparsing saved input with actions"
            << "# Current symbol is #" << cur_err_token()->sym
            << "\n# Current state is #"
            << stack.peek()->parse_state);

  /* continue until we accept or have read all lookahead input */
  while (true)
    {
      /* current state is always on the top of the stack */

      /* look up action out of the current state with the current input */
      int act = get_action(stack.peek()->parse_state, cur_err_token()->sym);

      /* decode the action -- > 0 encodes shift */
      if (act > 0)
        {
          /* shift to the encoded state by pushing it on the stack */
          cur_err_token()->parse_state = act-1;
          // if (debug) debug_shift(cur_err_token());
          stack.push(cur_err_token());

          /* advance to the next symbol, if there is none, we are done */
          if (!advance_lookahead())
            {
              DEBUG_LOG("# Completed reparse");

              /* scan next symbol so we can continue parse */
              // BUGFIX by Chris Harris <*****@*****.**>:
              //   correct a one-off error by commenting out
              //   this next line.
              cur_token = scan();

              /* go back to normal parser */
              return ERS_SUCCESS;
            }

          DEBUG_LOG("# Current symbol is #" << cur_err_token()->sym);
        }
      /* if its less than zero, then it encodes a reduce action */
      else if (act < 0)
        {
          /* perform the action for the reduce */
          lr_symbol* lhs_sym = do_action((-act)-1);

          if (lhs_sym == 0)
            {
              return ERS_ACCEPT;
            }

          /* look up information about the production */
          lhs_sym->sym      = production_tab[(-act)-1].lhs_sym;
          short handle_size = production_tab[(-act)-1].rhs_size;

          // if (debug) debug_reduce((-act)-1, lhs_sym->sym, handle_size);

          /* pop the handle off the stack */
          stack.npop(handle_size);

          /* look up the state to go to from the one popped back to */
          act = get_reduce(stack.peek()->parse_state, lhs_sym->sym);

          /* shift to that state */
          lhs_sym->parse_state = act;
          stack.push(lhs_sym);

          DEBUG_LOG("# Goto state #" << act);
        }
      /* finally if the entry is zero, we have an error
      (shouldn't happen here, but...)*/
      else // (act == 0)
        {
          assert(0);
        }
    }
}
Пример #21
0
static void
handle_xev(void) {
	XEvent ev;
	int i;
	char buf[32];
	KeySym ksym;

	XNextEvent(dzen.dpy, &ev);
	switch(ev.type) {
		case Expose:
			if(ev.xexpose.count == 0) 
				x_redraw(ev);
			break;
		case EnterNotify:
			if(dzen.slave_win.ismenu) { 
				for(i=0; i < dzen.slave_win.max_lines; i++) 
					if(ev.xcrossing.window == dzen.slave_win.line[i])
						x_hilight_line(i);
			}
			if(!dzen.slave_win.ishmenu 
					&& ev.xcrossing.window == dzen.title_win.win)
				do_action(entertitle);
			if(ev.xcrossing.window == dzen.slave_win.win)
				do_action(enterslave);
			break;
		case LeaveNotify:
			if(dzen.slave_win.ismenu) {
				for(i=0; i < dzen.slave_win.max_lines; i++)
					if(ev.xcrossing.window == dzen.slave_win.line[i])
						x_unhilight_line(i);
			}
			if(!dzen.slave_win.ishmenu 
					&& ev.xcrossing.window == dzen.title_win.win)
				do_action(leavetitle);
			if(ev.xcrossing.window == dzen.slave_win.win) {
				do_action(leaveslave);
			}
			break;
		case ButtonRelease:
			if(dzen.slave_win.ismenu) {
				for(i=0; i < dzen.slave_win.max_lines; i++) 
					if(ev.xbutton.window == dzen.slave_win.line[i]) 
						dzen.slave_win.sel_line = i;
			}
			switch(ev.xbutton.button) {
				case Button1:
					do_action(button1);
					break;
				case Button2:
					do_action(button2);
					break;
				case Button3:
					do_action(button3);
					break;
				case Button4:
					do_action(button4);
					break;
				case Button5:
					do_action(button5);
					break;
			}
			break;
		case KeyPress:
			XLookupString(&ev.xkey, buf, sizeof buf, &ksym, 0);
			do_action(ksym+keymarker);
			break;
		
		/* TODO: XRandR rotation and size chnages */
#if 0

#ifdef DZEN_XRANDR 
		case RRScreenChangeNotify:
			handle_xrandr();
#endif

#endif
		
	}
}
Пример #22
0
static int lua_sr_modf (lua_State *L)
{
	int ret;
	char *luav[MAX_ACTIONS];
	char *argv[MAX_ACTIONS];
	int argc;
	int i;
	int mod_type;
	struct run_act_ctx ra_ctx;
	unsigned modver;
	struct action *act;
	sr31_cmd_export_t* expf;
	sr_lua_env_t *env_L;

	ret = 1;
	act = NULL;
	argc = 0;
	memset(luav, 0, MAX_ACTIONS*sizeof(char*));
	memset(argv, 0, MAX_ACTIONS*sizeof(char*));
	env_L = sr_lua_env_get();
	if(env_L->msg==NULL)
		goto error;

#if 0
	app_lua_dump_stack(L);
#endif
	argc = lua_gettop(L);
	if(argc==0)
	{
		LM_ERR("name of module function not provided\n");
		goto error;
	}
	if(argc>=MAX_ACTIONS)
	{
		LM_ERR("too many parameters\n");
		goto error;
	}
	/* first is function name, then parameters */
	for(i=1; i<=argc; i++)
	{
		if (!lua_isstring(L, i))
		{
			LM_ERR("invalid parameter type (%d)\n", i);
			goto error;
		}
		luav[i-1] = (char*)lua_tostring(L, i);
	}
	/* pkg copy only parameters */
	for(i=1; i<MAX_ACTIONS; i++)
	{
		if(luav[i]!=NULL)
		{
			argv[i] = (char*)pkg_malloc(strlen(luav[i])+1);
			if(argv[i]==NULL)
			{
				LM_ERR("no more pkg\n");
				goto error;
			}
			strcpy(argv[i], luav[i]);
		}
	}

	expf = find_export_record(luav[0], argc-1, 0, &modver);
	if (expf==NULL) {
		LM_ERR("function '%s' is not available\n", luav[0]);
		goto error;
	}
	/* check fixups */
	if (expf->fixup!=NULL && expf->free_fixup==NULL) {
		LM_ERR("function '%s' has fixup - cannot be used\n", luav[0]);
		goto error;
	}
	switch(expf->param_no) {
		case 0:
			mod_type = MODULE0_T;
			break;
		case 1:
			mod_type = MODULE1_T;
			break;
		case 2:
			mod_type = MODULE2_T;
			break;
		case 3:
			mod_type = MODULE3_T;
			break;
		case 4:
			mod_type = MODULE4_T;
			break;
		case 5:
			mod_type = MODULE5_T;
			break;
		case 6:
			mod_type = MODULE6_T;
			break;
		case VAR_PARAM_NO:
			mod_type = MODULEX_T;
			break;
		default:
			LM_ERR("unknown/bad definition for function '%s' (%d params)\n",
					luav[0], expf->param_no);
			goto error;
	}

	act = mk_action(mod_type,  argc+1   /* number of (type, value) pairs */,
					MODEXP_ST, expf,    /* function */
					NUMBER_ST, argc-1,  /* parameter number */
					STRING_ST, argv[1], /* param. 1 */
					STRING_ST, argv[2], /* param. 2 */
					STRING_ST, argv[3], /* param. 3 */
					STRING_ST, argv[4], /* param. 4 */
					STRING_ST, argv[5], /* param. 5 */
					STRING_ST, argv[6]  /* param. 6 */
			);

	if (act==NULL) {
		LM_ERR("action structure could not be created for '%s'\n", luav[0]);
		goto error;
	}

	/* handle fixups */
	if (expf->fixup) {
		if(argc==1)
		{ /* no parameters */
			if(expf->fixup(0, 0)<0)
			{
				LM_ERR("Error in fixup (0) for '%s'\n", luav[0]);
				goto error;
			}
		} else {
			for(i=1; i<argc; i++)
			{
				if(expf->fixup(&(act->val[i+1].u.data), i)<0)
				{
					LM_ERR("Error in fixup (%d) for '%s'\n", i, luav[0]);
					goto error;
				}
				act->val[i+1].type = MODFIXUP_ST;
			}
		}
	}
	init_run_actions_ctx(&ra_ctx);
	ret = do_action(&ra_ctx, act, env_L->msg);

	/* free fixups */
	if (expf->fixup) {
		for(i=1; i<argc; i++)
		{
			if ((act->val[i+1].type == MODFIXUP_ST) && (act->val[i+1].u.data))
			{
				expf->free_fixup(&(act->val[i+1].u.data), i);
			}
		}
	}
	pkg_free(act);
	for(i=0; i<MAX_ACTIONS; i++)
	{
		if(argv[i]!=NULL) pkg_free(argv[i]);
		argv[i] = 0;
	}
	lua_pushinteger(L, ret);
	return 1;

error:
	if(act!=NULL)
		pkg_free(act);
	for(i=0; i<MAX_ACTIONS; i++)
	{
		if(argv[i]!=NULL) pkg_free(argv[i]);
		argv[i] = 0;
	}
	lua_pushinteger(L, -1);
	return 1;
}
Пример #23
0
static void
catch_sigterm(int s) {
	(void)s;
	do_action(onexit);
}
Пример #24
0
void shopping_buy( char *arg, struct char_data *ch,
	 struct char_data *keeper, int shop_nr)
{
	char argm[100], buf[MAX_STRING_LENGTH];
	struct obj_data *temp1;
	struct char_data *temp_char;

	if(!(is_ok(keeper,ch,shop_nr)))
		return;
	

	one_argument(arg, argm);
	if(!(*argm))
	{
		sprintf(buf,
		"%s what do you want to buy??"
		,GET_NAME(ch));
		do_tell(keeper,buf,19);
		return;
	};
	if(!( temp1 = 
		get_obj_in_list_vis(ch,argm,keeper->carrying)))
	{
		sprintf(buf,
		shop_index[shop_nr].no_such_item1
		,GET_NAME(ch));
		do_tell(keeper,buf,19);
		return;
	}

	if(temp1->obj_flags.cost <= 0)
	{
		sprintf(buf,
		shop_index[shop_nr].no_such_item1
		,GET_NAME(ch));
		do_tell(keeper,buf,19);
		extract_obj(temp1);
		return;
	}

	if(GET_GOLD(ch) < (int) (temp1->obj_flags.cost*
		shop_index[shop_nr].profit_buy) && GET_LEVEL(ch)<22)
	{
		sprintf(buf,
		shop_index[shop_nr].missing_cash2,
		GET_NAME(ch));
		do_tell(keeper,buf,19);

		switch(shop_index[shop_nr].temper1)
		{
			case 0:
				do_action(keeper,GET_NAME(ch),30);
				return;
			case 1:
				do_emote(keeper,"smokes on his joint",36);
				return;
			default:
				return;
		}
	}
	
	if ((IS_CARRYING_N(ch) + 1 > CAN_CARRY_N(ch)))
	{
		sprintf(buf,"%s : You can't carry that many items.\n\r", 
			fname(temp1->name));
		send_to_char(buf, ch);
		return;
	}

	if ((IS_CARRYING_W(ch) + temp1->obj_flags.weight) > CAN_CARRY_W(ch))
	{
		sprintf(buf,"%s : You can't carry that much weight.\n\r", 
			fname(temp1->name));
		send_to_char(buf, ch);
		return;
	}


	act("$n buys $p.", FALSE, ch, temp1, 0, TO_ROOM);

	sprintf(buf,
		shop_index[shop_nr].message_buy,
		GET_NAME(ch),
		(int) (temp1->obj_flags.cost*
			shop_index[shop_nr].profit_buy));
	do_tell(keeper,buf,19);
	sprintf(buf,"You now have %s.\n\r",
		temp1->short_description);
	send_to_char(buf,ch);
   if(GET_LEVEL(ch)<22)
		GET_GOLD(ch) -= (int)(temp1->obj_flags.cost*
			shop_index[shop_nr].profit_buy);

   GET_GOLD(keeper) += (int)(temp1->obj_flags.cost*
      shop_index[shop_nr].profit_buy);

	/* Test if producing shop ! */
	if(shop_producing(temp1,shop_nr))
		temp1 = read_object(temp1->item_number, REAL);
	else
		obj_from_char(temp1);

	obj_to_char(temp1,ch);

	return; 
}
Пример #25
0
int uac_reg_request_to(struct sip_msg *msg, str *src, unsigned int mode)
{
	char ruri[MAX_URI_SIZE];
	struct sip_uri puri;
	reg_uac_t *reg = NULL;
	pv_value_t val;
	struct action act;
	struct run_act_ctx ra_ctx;

	switch(mode)
	{
		case 0:
			reg = reg_ht_get_byuuid(src);
			break;
		case 1:
			if(reg_use_domain)
			{
				if (parse_uri(src->s, src->len, &puri)!=0)
				{
					LM_ERR("failed to parse uri\n");
					return -2;
				}
				reg = reg_ht_get_byuser(&puri.user, &puri.host);
			} else {
				reg = reg_ht_get_byuser(src, NULL);
			}
			break;
		default:
			LM_ERR("unknown mode: %d\n", mode);
			return -1;
	}

	if(reg==NULL)
	{
		LM_DBG("no user: %.*s\n", src->len, src->s);
		return -1;
	}

	// Set uri ($ru)
	snprintf(ruri, MAX_URI_SIZE, "sip:%.*s@%.*s",
		reg->r_username.len, reg->r_username.s,
		reg->r_domain.len, reg->r_domain.s);
	memset(&act, 0, sizeof(act));
	act.type = SET_URI_T;
	act.val[0].type = STRING_ST;
	act.val[0].u.string = ruri;
	init_run_actions_ctx(&ra_ctx);
	if (do_action(&ra_ctx, &act, msg) < 0) {
		LM_ERR("error while setting request uri\n");
		return -1;
	}

	// Set auth_proxy ($du)
	if (set_dst_uri(msg, &reg->auth_proxy) < 0) {
		LM_ERR("error while setting outbound proxy\n");
		return -1;
	}

	memset(&val, 0, sizeof(pv_value_t));
	val.flags |= PV_VAL_STR;

	// Set auth_realm
	val.rs = reg->realm;
	if(pv_set_spec_value(msg, &auth_realm_spec, 0, &val)!=0) {
		LM_ERR("error while setting auth_realm\n");
		return -1;
	}

	// Set auth_username
	val.rs = reg->auth_username;
	if(pv_set_spec_value(msg, &auth_username_spec, 0, &val)!=0) {
		LM_ERR("error while setting auth_username\n");
		return -1;
	}

	// Set auth_password
	val.rs = reg->auth_password;
	if(pv_set_spec_value(msg, &auth_password_spec, 0, &val)!=0) {
		LM_ERR("error while setting auth_password\n");
		return -1;
	}

	return 1;
}
Пример #26
0
MBToolbar::MBToolbar(std::string current_level, int r, int g, int b, int n_activities, int n_ins, int n_intermediaries, int n_outs1, int n_outs2, int n_treatments, map<string, vector<int> > ids)
	: m_r(r), m_g(g), m_b(b), m_x(0), m_y(440), m_following(false), m_active_rectangle(0) {
    if(TOOLBAR) printf("Construindo toolbar\n");

    for(auto &id : ids){
        vector<int> &v = id.second;
        random_shuffle(v.begin(), v.end());
    }

	for(int i = 0; i < n_ins; i++){
        m_pieces.push_back(new MBPiece(current_level, TOOLBAR_DISTANCE + 80 * (i%11), 445 + 100 * (i/11), ids["in"][i], "in"));        
        add_child(m_pieces.back());
    }
    // int x;
    // scanf("%d", &x);

    for(int i = 0; i < n_intermediaries; i++){
        m_pieces.push_back(new MBPiece(current_level, TOOLBAR_DISTANCE + 90 * (i%11), 445 + 90 * (i/11), ids["intermediary"][i], "intermediary"));
        add_child(m_pieces.back());
    }

    for(int i = 0; i < n_activities; i++){
        m_pieces.push_back(new MBPiece(current_level, TOOLBAR_DISTANCE + 280 * (i%4), 445 + 170 * (i/4), ids["activity"][i], "activity"));
        add_child(m_pieces.back());
    }
        

    for(int i = 0; i < n_outs1; i++){
        m_pieces.push_back(new MBPiece(current_level, TOOLBAR_DISTANCE + 90 * (i%11), 445 + 70 * (i/11), ids["out1"][i], "out1"));
        add_child(m_pieces.back());
    }

    //For das out2 fixme
    for(int i = 0; i < n_outs2; i++){
        m_pieces.push_back(new MBPiece(current_level, TOOLBAR_DISTANCE + 90 * (i%11), 585 + 70 * (i/11), ids["out2"][i], "out2"));
        add_child(m_pieces.back());
    }

    for(int i = 0; i < n_treatments; i++){
        m_pieces.push_back(new MBPiece(current_level, TOOLBAR_DISTANCE + 160 * (i%7), 445 + 72 * (i/7), ids["treatment"][i], "treatment"));
	    add_child(m_pieces.back());
	}

    int font_size = 20;

    m_buttons.push_back(new MBButton("Atividades", "atividades", "toolbar", 0, m_y + 0, 180, 66, font_size));
    m_buttons.push_back(new MBButton("Entradas", "entradas", "toolbar", 0, m_y + 66, 180, 66, font_size));
    m_buttons.push_back(new MBButton("Intermediários", "intermediarios", "toolbar", 0, m_y + 132, 180, 66, font_size));
    m_buttons.push_back(new MBButton("Saídas", "saidas", "toolbar", 0, m_y + 198, 180, 66, font_size));
    m_buttons.push_back(new MBButton("Tratamentos", "tratamentos", "toolbar", 0, m_y + 264, 180, 66, font_size));

    for(auto button : m_buttons){
        button->set_priority(20);
        button->set_texture(current_level + "/toolbar_rectangle.png");
        button->set_active_texture(true);
        add_child(button);
    }

    do_action("atividades");

    m_background = resources::get_texture(current_level + "/toolbar.png");

    if(TOOLBAR) printf("Construiu toolbar\n");
}
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;

#if defined(SHELL_AYGSHELL) && !defined(WIN32_PLATFORM_WFSP)
    static SHACTIVATEINFO s_sai;
#endif // SHELL_AYGSHELL && !WIN32_PLATFORM_WFSP
	
    switch (message) 
    {
		case WM_COMMAND:
            wmId    = LOWORD(wParam); 
            wmEvent = HIWORD(wParam); 
            // Parse the menu selections:
            switch (wmId)
            {
#ifndef WIN32_PLATFORM_WFSP
                case IDM_HELP_ABOUT:
                    DialogBox(g_hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, About);
                    break;
#endif // !WIN32_PLATFORM_WFSP
#ifdef WIN32_PLATFORM_WFSP
                case IDM_OK:
					do_action();

                    break;
#endif // WIN32_PLATFORM_WFSP
#ifdef WIN32_PLATFORM_PSPC
                case IDM_OK:
					do_action();
                    break;
#endif // WIN32_PLATFORM_PSPC
				default:
                    return DefWindowProc(hWnd, message, wParam, lParam);
            }
            break;
        case WM_CREATE:
#ifdef SHELL_AYGSHELL
            SHMENUBARINFO mbi;

            memset(&mbi, 0, sizeof(SHMENUBARINFO));
            mbi.cbSize     = sizeof(SHMENUBARINFO);
            mbi.hwndParent = hWnd;
            mbi.nToolBarId = IDR_MENU;
            mbi.hInstRes   = g_hInst;

            if (!SHCreateMenuBar(&mbi)) 
            {
                g_hWndMenuBar = NULL;
            }
            else
            {
                g_hWndMenuBar = mbi.hwndMB;
            }

#ifndef WIN32_PLATFORM_WFSP
            // Initialize the shell activate info structure
            memset(&s_sai, 0, sizeof (s_sai));
            s_sai.cbSize = sizeof (s_sai);
#endif // !WIN32_PLATFORM_WFSP
#endif // SHELL_AYGSHELL

#ifdef WIN32_PLATFORM_WFSP
			hWndList = CreateWindow(TEXT("listbox"),NULL, WS_CHILD|
				WS_VISIBLE|WS_HSCROLL|WS_VSCROLL|WS_TABSTOP, 0,0, 300, 200, hWnd, 
				(HMENU)"", g_hInst, NULL);			
#else
			hWndList = CreateWindow(TEXT("listbox"),NULL, WS_CHILD|
				WS_VISIBLE|WS_HSCROLL|WS_VSCROLL|WS_TABSTOP, 0,0, 250, 200, hWnd, 
				(HMENU)"", g_hInst, NULL);			
#endif // !WIN32_PLATFORM_WFSP
			
			font = CreateFont(10,           // height of font
                       0,            // average character width
                       0,               // angle of escapement
                       0,               // base-line orientation angle
                       400,     // font weight
                       0,               // italic attribute option
                       FALSE,                // underline attribute option
                       FALSE,                // strikeout attribute option
                       ANSI_CHARSET,         // character set identifier
                       OUT_DEFAULT_PRECIS,   // output precision
                       CLIP_DEFAULT_PRECIS,  // clipping precision
                       ANTIALIASED_QUALITY,  // output quality
                       FF_DONTCARE,          // pitch and family
					   TEXT("Times New Roman"));       

			SendMessage(hWndList, WM_SETFONT, (WPARAM)font, (LPARAM)TRUE);

			SetFocus(hWndList);
			break;
        case WM_PAINT:
            hdc = BeginPaint(hWnd, &ps);
            
            EndPaint(hWnd, &ps);
            break;
        case WM_DESTROY:
#ifdef SHELL_AYGSHELL
            CommandBar_Destroy(g_hWndMenuBar);
#endif // SHELL_AYGSHELL
            PostQuitMessage(0);
            break;

#if defined(SHELL_AYGSHELL) && !defined(WIN32_PLATFORM_WFSP)
        case WM_ACTIVATE:
            // Notify shell of our activate message
            SHHandleWMActivate(hWnd, wParam, lParam, &s_sai, FALSE);
            break;
        case WM_SETTINGCHANGE:
            SHHandleWMSettingChange(hWnd, wParam, lParam, &s_sai);
            break;
#endif // SHELL_AYGSHELL && !WIN32_PLATFORM_WFSP

        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}
Пример #28
0
int ops_pushto_avp (struct sip_msg* msg, struct fis_param* dst,
													struct fis_param* src)
{
	struct action  act;
	struct usr_avp *avp;
	unsigned short name_type;
	int_str        avp_val;
	int        avp_name;
	str            val;
	int            act_type;
	int            n;
	int            flags;
	pv_value_t     xvalue;

	avp = NULL;
	flags = 0;
	if(src->u.sval.type==PVT_AVP)
	{
		/* search for the avp */
		if(avpops_get_aname(msg, src, &avp_name, &name_type)!=0)
		{
			LM_ERR("failed to get src AVP name\n");
			goto error;
		}
		avp = search_first_avp( name_type, avp_name, &avp_val, 0);
		if (avp==0)
		{
			LM_DBG(" no src avp found\n");
			goto error;
		}
		flags = avp->flags;
	} else {
		if(pv_get_spec_value(msg, &(src->u.sval), &xvalue)!=0)
		{
			LM_ERR("cannot get src value\n");
			goto error;
		}
		if(xvalue.flags&PV_TYPE_INT)
		{
			avp_val.n = xvalue.ri;
		} else {
			flags = AVP_VAL_STR;
			avp_val.s = xvalue.rs;
		}
	}

	n = 0;
	do {
		/* the avp val will be used all the time as str */
		if (flags&AVP_VAL_STR) {
			val = avp_val.s;
		} else {
			val.s = int2str((unsigned long)avp_val.n, &val.len);
		}

		act_type = 0;
		/* push the value into right position */
		if (dst->opd&AVPOPS_USE_RURI)
		{
			if (dst->opd&AVPOPS_FLAG_USER0)
				act_type = SET_USER_T;
			else if (dst->opd&AVPOPS_FLAG_DOMAIN0)
				act_type = SET_HOST_T;
			else
				act_type = SET_URI_T;
			if ( flags&AVP_VAL_STR && append_0( &val, &val)!=0 ) {
				LM_ERR("failed to make 0 term.\n");
				goto error;
			}
		} else if (dst->opd&AVPOPS_USE_DURI) {
			if (!(flags&AVP_VAL_STR)) {
				goto error;
			}
		} else if (dst->opd&AVPOPS_USE_BRANCH) {
			if (!(flags&AVP_VAL_STR)) {
				goto error;
			}
		} else {
			LM_CRIT("destination unknown (%d/%d)\n", dst->opd, dst->ops);
			goto error;
		}

		if ( act_type )
		{
			/* rewrite part of ruri */
			if (n)
			{
				/* if is not the first modification, push the current uri as
				 * branch */
				if (append_branch( msg, 0, 0, 0, Q_UNSPECIFIED, 0, 0)!=1 )
				{
					LM_ERR("append_branch action failed\n");
					goto error;
				}
			}
			memset(&act, 0, sizeof(act));
			act.elem[0].type = STR_ST;
			act.elem[0].u.s = val;
			act.type = act_type;
			if (do_action(&act, msg)<0)
			{
				LM_ERR("SET_XXXX_T action failed\n");
				goto error;
			}
		} else if (dst->opd&AVPOPS_USE_DURI) {
			if(set_dst_uri(msg, &val)!=0)
			{
				LM_ERR("changing dst uri failed\n");
				goto error;
			}
		} else if (dst->opd&AVPOPS_USE_BRANCH) {
			if (append_branch( msg, &val, 0, 0, Q_UNSPECIFIED, 0,
			msg->force_send_socket)!=1 )
			{
				LM_ERR("append_branch action failed\n");
				goto error;
			}
		} else {
			LM_ERR("unknown destination\n");
			goto error;
		}

		n++;
		if ( !(src->ops&AVPOPS_FLAG_ALL) )
			break;
		if(avp==NULL)
			break;
		if((avp = search_first_avp( name_type, avp_name, &avp_val, avp))!=NULL)
			flags = avp->flags;
	} while (avp);/* end while */

	LM_DBG("%d avps were processed\n",n);
	return 1;
error:
	return -1;
}
Пример #29
0
void on_copy_btn_clicked (GtkWidget *widget, gpointer user_data) {
	do_action(TRUE);
}
Пример #30
0
	void save(Arc& ar, const unsigned v) const {
		do_action();
		boost::serialization::serialize(ar, output, v);
	}