Esempio n. 1
0
/* call strescape on a string and xhtmlize the string (\n-><br/>) */
char * _con_room_xhtml_strescape(pool p, char * buf) {
  char *result,*temp;
  int i,j;
  int oldlen, newlen;
  result = strescape(p, buf);
  oldlen = newlen=strlen(result);
  for (i=0; i<oldlen;i++) {
    if (result[i]=='\n') {
      newlen += 6;
    }
  }

  if(oldlen == newlen) return result;

  temp = pmalloc(p,newlen+1);
  if (temp == NULL) return NULL;

  for (i=j=0;i<oldlen;i++) {
    if (result[i]== '\n') {
      memcpy(&temp[j], "<br />", 6);
      j+=6;
    }
    else temp[j++] = result[i];
  }
  temp[j]='\0';
  return temp;
}
Esempio n. 2
0
char *escapestr(const char *in)
{
	static size_t buflen = 0;
	static char *buf = NULL;
	size_t inlen;
	const char *p;

	if (in == 0) return 0;

	inlen = strlen(in) + 1;

	/* Each newline will consume an additional byte due to escaping. */
	for (p = in; *p; ++p)
		if (*p == '\n')
			++inlen;

	if (buflen < inlen) {
		buflen = inlen;
		buf = realloc(buf, buflen * sizeof *buf);
		if (!buf)
			DIE("Out of memory");
	}

	strescape(in, buf, buflen, 0);
	return buf;
}
Esempio n. 3
0
/*
 * assing the value of the const to the fop.value
 *
 * all the value are integer32 and are saved in host order
 */
int encode_const(char *string, struct filter_op *fop)
{
   char *p;
   
   memset(fop, 0, sizeof(struct filter_op));
   
   /* it is an hexadecimal value */
   if (!strncmp(string, "0x", 2) && isdigit((int)string[2])) {
      fop->op.test.value = strtoul(string, NULL, 16);
      return ESUCCESS;
      
   /* it is an integer value */
   } else if (isdigit((int)string[0])) {
      fop->op.test.value = strtoul(string, NULL, 10);
      return ESUCCESS;
      
   /* it is an ip address */
   } else if (string[0] == '\'' && string[strlen(string) - 1] == '\'') {
      struct in_addr ipaddr;
      
      /* remove the single quote */
      p = strchr(string + 1, '\'');
      *p = '\0';

      if (inet_aton(string + 1, &ipaddr) == 0)
         return -EFATAL;
      
      fop->op.test.value = ntohl(ipaddr.s_addr);
      return ESUCCESS;
      
   /* it is a string */
   } else if (string[0] == '\"' && string[strlen(string) - 1] == '\"') {
  
      /* remove the quotes */
      p = strchr(string + 1, '\"');
      *p = '\0';

      /* copy the string */
      fop->op.test.string = (u_char*)strdup(string + 1);
         
      /* escape it in the structure */
      fop->op.test.slen = strescape((char*)fop->op.test.string, (char*)fop->op.test.string);
     
      return ESUCCESS;
      
   /* it is a constant */
   } else if (isalpha((int)string[0])) {
      return get_constant(string, &fop->op.test.value);
   }
   
   /* anything else is an error */
   return -ENOTFOUND;
}
static void gtkui_inject_user(int side)
{
   size_t len;
    
   /* escape the sequnces in the buffer */
   len = strescape(injectbuf, injectbuf);

   /* check where to inject */
   if (side == 1 || side == 2) {
      user_inject(injectbuf, len, curr_conn, side);
   }
}
static void inject_user(void) 
{
   size_t len;

   /* escape the sequnces in the buffer */
   len = strescape((char*)injectbuf, (char*)injectbuf, strlen(injectbuf)+1);
   
   /* check where to inject */
   if (wdg_c1->flags & WDG_OBJ_FOCUSED) {
      user_inject(injectbuf, len, curr_conn, 1);
   } else if (wdg_c2->flags & WDG_OBJ_FOCUSED) {
      user_inject(injectbuf, len, curr_conn, 2);
   }
}
Esempio n. 6
0
void *
emphasis_cover_thread_process(void *data)
{
  Emphasis_Gui *gui;
  Cover_Info *ci;
  char *cover_path;
  char *artist, *album;

  gui = data;
  while (1)
    {
      if (gui->cover_queue)
        {
          ci = gui->cover_queue;

          artist = ci->artist;
          album  = ci->album;
          strescape(artist);
          strescape(album);
          gui->cover_queue = NULL;
          
          cover_path = emphasis_cover_db_search(artist, album);
          emphasis_player_cover_set(gui->player, cover_path);
          if (cover_path != NULL) { free(cover_path); }
          //emphasis_player_cover_size_update(gui->player);

          free(artist);
          free(album);
          free(ci);
        }
      else
        {
          usleep(200);
        }
    }
}
Esempio n. 7
0
File: xmlnode.c Progetto: bcy/muc
static spool _xmlnode2spool(xmlnode node)
{
    spool s;
    int level=0,dir=0;
    xmlnode tmp;

    if(!node || xmlnode_get_type(node)!=NTYPE_TAG)
        return NULL;

    s = spool_new(xmlnode_pool(node));
    if(!s) return(NULL);

    while(1)
    {
        if(dir==0)
        {
    	    if(xmlnode_get_type(node) == NTYPE_TAG)
            {
                if(xmlnode_has_children(node))
                {
                    _xmlnode_tag2str(s,node,1);
                    node = xmlnode_get_firstchild(node);
                    level++;
                    continue;
                }else{
                    _xmlnode_tag2str(s,node,0);
                }
            }else{
                spool_add(s,strescape(xmlnode_pool(node),xmlnode_get_data(node)));
            }
        }

    	tmp = xmlnode_get_nextsibling(node);
        if(!tmp)
        {
            node = xmlnode_get_parent(node);
            level--;
            if(level>=0) _xmlnode_tag2str(s,node,2);
            if(level<1) break;
            dir = 1;
        }else{
            node = tmp;
            dir = 0;
        }
    }

    return s;
}
Esempio n. 8
0
static void
print_one_tag (const GstTagList * list, const gchar * tag, gpointer user_data)
{
  int i, num;

  num = gst_tag_list_get_tag_size (list, tag);
  for (i = 0; i < num; ++i) {
    const GValue *val;

    /* Note: when looking for specific tags, use the g_tag_list_get_xyz() API,
     * we only use the GValue approach here because it is more generic */
    val = gst_tag_list_get_value_index (list, tag, i);
    if (G_VALUE_HOLDS_STRING (val)) {
      const char* unformatted = g_value_get_string (val);
      gchar* formatted = strescape(unformatted,"\"","\"");
      g_print ("(%s . \"%s\")\n", tag, formatted);
      g_free(formatted);
    } else if (G_VALUE_HOLDS_UINT (val)) {
	  unsigned int uint = g_value_get_uint (val);
	  if(uint > 0xf)
      	g_print ("(%s . #x%x)\n", tag, uint);
    } else if (G_VALUE_HOLDS_DOUBLE (val)) {
      g_print ("(%s . %g)\n", tag, g_value_get_double (val));
    } else if (G_VALUE_HOLDS_BOOLEAN (val)) {
      g_print ("(%s . %s)\n", tag,
          (g_value_get_boolean (val)) ? "#t" : "#f");
    } else if (GST_VALUE_HOLDS_BUFFER (val)) {
      g_print ("(%s . (buffer %u))", tag,
              gst_buffer_get_size(gst_value_get_buffer (val)));
    } else if (GST_VALUE_HOLDS_DATE_TIME (val)) {
	   GDate* date = (GDate*)g_value_get_boxed(val);
      g_print ("(%s . (date 0 0 0 %u %u %u))\n", tag,
	  	g_date_get_day(date),
		g_date_get_month(date),
        g_date_get_year (date));
    } else {
      g_print ("(%20s . (type %s))", tag, G_VALUE_TYPE_NAME (val));
    }
  }

}
Esempio n. 9
0
File: xmlnode.c Progetto: bcy/muc
static void _xmlnode_tag2str(spool s, xmlnode node, int flag)
{
    xmlnode tmp;

    if(flag==0 || flag==1)
    {
	    spooler(s,"<",xmlnode_get_name(node),s);
	    tmp = xmlnode_get_firstattrib(node);
	    while(tmp) {
	        spooler(s," ",xmlnode_get_name(tmp),"='",strescape(xmlnode_pool(node),xmlnode_get_data(tmp)),"'",s);
	        tmp = xmlnode_get_nextsibling(tmp);
	    }
	    if(flag==0)
	        spool_add(s,"/>");
	    else
	        spool_add(s,">");
    }
    else
    {
	    spooler(s,"</",xmlnode_get_name(node),">",s);
    }
}
Esempio n. 10
0
void
make_output(char *output, size_t outlen, const char *binname,
    pid_t pid, pid_t ppid,
    int policynr, const char *policy, int nfilters, const char *emulation,
    const char *name, int code, struct intercept_tlq *tls,
    struct intercept_replace *repl)
{
	struct intercept_translate *tl;
	char *p, *line;
	int size;

	snprintf(output, outlen,
	    "%s, pid: %d(%d)[%d], policy: %s, filters: %d, syscall: %s-%s(%d)",
	    binname, pid, policynr, ppid, policy, nfilters,
	    emulation, name, code);

	p = output + strlen(output);
	size = outlen - strlen(output);

	if (tls == NULL)
		return;

	TAILQ_FOREACH(tl, tls, next) {
		if (!tl->trans_valid)
			continue;
		line = intercept_translate_print(tl);
		if (line == NULL)
			continue;

		snprintf(p, size, ", %s: %s", tl->name, strescape(line));
		p = output + strlen(output);
		size = outlen - strlen(output);

		if (repl != NULL && tl->trans_size)
			intercept_replace_add(repl, tl->off,
			    tl->trans_data, tl->trans_size,
			    tl->trans_flags);
	}
}
/* Like command_arg_longstring_get but escape spaces with '\'.
 */
gboolean
command_arg_longstring_get_escaped (command_context_t *ctx, gint at, gchar **v)
{
	gboolean retval = FALSE;
	gchar **args;
	gint i, len, count = command_arg_count (ctx);

	len = count-at+1;
	if (at < count) {
		args = g_new0 (gchar *, len);
		args[len-1] = NULL;
		for (i = at; i < count; i++) {
			args[i-at] = strescape (command_arg_get (ctx, i), " ", '\\');
		}
		*v = g_strjoinv (" ", args);

		for (i = at; i < count; i++) {
			g_free (args[i-at]);
		}
		g_free (args);

		retval = TRUE;
	}
Esempio n. 12
0
  static void ConfirmShutdown(cDBusObject *Object, GVariant *Parameters, GDBusMethodInvocation *Invocation)
  {
    gboolean ignoreuser = FALSE;
    g_variant_get(Parameters, "(b)", &ignoreuser);

    // this is nearly a copy of vdr's cShutdownHandler::ConfirmShutdown
    // if the original changes take this into account

    if (!ignoreuser && !ShutdownHandler.IsUserInactive()) {
       SendReply(Invocation, 901, "user is active", 0, "");
       return;
       }

#if APIVERSNUM > 20101
    if (RecordingsHandler.Active()) {
#else
    if (cCutter::Active()) {
#endif
       SendReply(Invocation, 902, "cutter is active", 0, "");
       return;
       }

    time_t Now = time(NULL);
#if VDRVERSNUM > 20300
    LOCK_TIMERS_READ;
    const cTimers *timers = Timers;
#else
    cTimers *timers = &Timers;
#endif
    const cTimer *timer = timers->GetNextActiveTimer();
    time_t Next = timer ? timer->StartTime() : 0;
    time_t Delta = timer ? Next - Now : 0;
    if (cRecordControls::Active() || (Next && Delta <= 0)) {
       // VPS recordings in timer end margin may cause Delta <= 0
       SendReply(Invocation, 903, "recording is active", 0, "");
       return;
       }
    else if (Next && Delta <= Setup.MinEventTimeout * 60) {
       // Timer within Min Event Timeout
       SendReply(Invocation, 904, "recording is active in the near future", 0, "");
       return;
       }

    if (cPluginManager::Active(NULL)) {
       SendReply(Invocation, 905, "some plugin is active", 0, "");
       return;
       }

    cPlugin *Plugin = cPluginManager::GetNextWakeupPlugin();
    time_t NextPlugin = Plugin ? Plugin->WakeupTime() : 0;
    Delta = NextPlugin ? NextPlugin - Now : 0;
    if (NextPlugin && Delta <= Setup.MinEventTimeout * 60) {
       // Plugin wakeup within Min Event Timeout
       cString buf = cString::sprintf("plugin %s wakes up in %ld min", Plugin->Name(), Delta / 60);
       SendReply(Invocation, 906, *buf, 0, "");
       return;
       }

    // insanity check: ask vdr again, if implementation of ConfirmShutdown has changed...
    if (cRemote::Enabled() && !ShutdownHandler.ConfirmShutdown(false)) {
       SendReply(Invocation, 550, "vdr is not ready for shutdown", 0, "");
       return;
       }

    if (((*cDBusShutdown::_shutdownHooksDir) != NULL) && (strlen(*cDBusShutdown::_shutdownHooksDir) > 0)
     && ((*cDBusShutdown::_shutdownHooksWrapper) != NULL) && (strlen(*cDBusShutdown::_shutdownHooksWrapper) > 0)) {
       if (NextPlugin && (!Next || Next > NextPlugin)) {
          Next = NextPlugin;
          timer = NULL;
          }
       Delta = Next ? Next - Now : 0;

       char *tmp;
       if (Next && timer)
          tmp = strdup(*cString::sprintf("%ld %ld %d \"%s\" %d", Next, Delta, timer->Channel()->Number(), *strescape(timer->File(), "\\\"$"), false));
       else if (Next && Plugin)
          tmp = strdup(*cString::sprintf("%ld %ld %d \"%s\" %d", Next, Delta, 0, Plugin->Name(), false));
       else
          tmp = strdup(*cString::sprintf("%ld %ld %d \"%s\" %d", Next, Delta, 0, "", false));
       cString params = strescape(tmp, "\\\"");

       cString shutdowncmd;
       cString cmd = cString::sprintf("%s %s \"%s\"", *cDBusShutdown::_shutdownHooksWrapper, *cDBusShutdown::_shutdownHooksDir, *params);
       if (access(*cDBusShutdown::_shutdownHooksWrapper, X_OK) != 0)
          cmd = cString::sprintf("/bin/sh %s %s \"%s\"", *cDBusShutdown::_shutdownHooksWrapper, *cDBusShutdown::_shutdownHooksDir, *params);
       isyslog("dbus2vdr: calling shutdown-hook-wrapper %s", *cmd);
       tmp = NULL;
       cExitPipe p;
       int ret = -1;
       if (p.Open(*cmd, "r")) {
          int l = 0;
          int c;
          while ((c = fgetc(p)) != EOF) {
                if (l % 20 == 0) {
                   if (char *NewBuffer = (char *)realloc(tmp, l + 21))
                      tmp = NewBuffer;
                   else {
                      esyslog("dbus2vdr: out of memory");
                      break;
                      }
                   }
                tmp[l++] = char(c);
                }
          if (tmp)
             tmp[l] = 0;
          ret = p.Close();
          }
       else
          esyslog("dbus2vdr: can't open pipe for command '%s'", *cmd);

       cString result(stripspace(tmp), true); // for automatic free
       isyslog("dbus2vdr: result(%d) = %s", ret, *result);
       if (ret != 0) {
          if (*result) {
             static const char *message = "ABORT_MESSAGE=\"";
             if ((strlen(*result) > strlen(message)) && startswith(*result, message)) {
                cString abort_message = tmp + strlen(message);
                abort_message.Truncate(-1);
                SendReply(Invocation, 992, *abort_message, ret, "");
                return;
                }
             }
          SendReply(Invocation, 999, "shutdown-hook returned a non-zero exit code", ret, "");
          return;
          }

       if (*result) {
          static const char *message = "TRY_AGAIN=\"";
          if ((strlen(*result) > strlen(message)) && startswith(*result, message)) {
             cString s_try_again = tmp + strlen(message);
             s_try_again.Truncate(-1);
             if ((strlen(*s_try_again) > 0) && isnumber(*s_try_again)) {
                int try_again = strtol(s_try_again, NULL, 10);
                if (try_again > 0) {
                   SendReply(Invocation, 991, *s_try_again, 0, "");
                   return;
                   }
                }
             }
          }

       if (*result) {
          static const char *message = "SHUTDOWNCMD=\"";
          if ((strlen(*result) > strlen(message)) && startswith(*result, message)) {
             shutdowncmd = tmp + strlen(message);
             shutdowncmd.Truncate(-1);
             }
          }
       if (*shutdowncmd && (strlen(*shutdowncmd) > 0)) {
          SendReply(Invocation, 990, *shutdowncmd, 0, *params);
          return;
          }
       }

    SendReply(Invocation, 250, "vdr is ready for shutdown", 0, "");
  };

  static void ManualStart(cDBusObject *Object, GVariant *Parameters, GDBusMethodInvocation *Invocation)
  {
    gboolean manual = FALSE;
    time_t Delta = Setup.NextWakeupTime ? Setup.NextWakeupTime - cDBusShutdown::StartupTime : 0;
    if (!Setup.NextWakeupTime || (abs(Delta) > 600)) // 600 comes from vdr's MANUALSTART constant in vdr.c
       manual = TRUE;
    g_dbus_method_invocation_return_value(Invocation, g_variant_new("(b)", manual));
  };
Esempio n. 13
0
/*
 * mainline for awk
 */
int
main(int argc, char *argv[])
{
	wchar_t *ap;
	char *cmd;

	cmd = argv[0];
	_cmdname = cmd;

	linebuf = emalloc(NLINE * sizeof (wchar_t));

	/*
	 * At this point only messaging should be internationalized.
	 * numbers are still scanned as in the Posix locale.
	 */
	(void) setlocale(LC_ALL, "");
	(void) setlocale(LC_NUMERIC, "C");
#if !defined(TEXT_DOMAIN)
#define	TEXT_DOMAIN	"SYS_TEST"
#endif
	(void) textdomain(TEXT_DOMAIN);

	awkvarinit();
	/* running = 1; */
	while (argc > 1 && *argv[1] == '-') {
		void *save_ptr = NULL;
		ap = mbstowcsdup(&argv[1][1]);
		if (ap == NULL)
			break;
		if (*ap == '\0') {
			free(ap);
			break;
		}
		save_ptr = (void *) ap;
		++argv;
		--argc;
		if (*ap == '-' && ap[1] == '\0')
			break;
		for (; *ap != '\0'; ++ap) {
			switch (*ap) {
#ifdef DEBUG
			case 'd':
				dflag = 1;
				continue;

#endif
			case 'f':
				if (argc < 2) {
					(void) fprintf(stderr,
				gettext("Missing script file\n"));
					return (1);
				}
				*progfilep++ = argv[1];
				--argc;
				++argv;
				continue;

			case 'F':
				if (ap[1] == '\0') {
					if (argc < 2) {
						(void) fprintf(stderr,
				gettext("Missing field separator\n"));
						return (1);
					}
					ap = mbstowcsdup(argv[1]);
					--argc;
					++argv;
				} else
					++ap;
				strescape(ap);
				strassign(varFS, linebuf, FALLOC,
				    wcslen(linebuf));
				break;

			case 'v': {
				wchar_t *vp;
				wchar_t *arg;

				if (argc < 2) {
					(void) fprintf(stderr,
		gettext("Missing variable assignment\n"));
					return (1);
				}
				arg = mbconvert(argv[1]);
				/*
				 * Ensure the variable expression
				 * is valid (correct form).
				 */
				if (((vp = wcschr(arg, '=')) != NULL) &&
				    isclvar(arg)) {
					*vp = '\0';
					strescape(vp+1);
					strassign(vlook(arg), linebuf,
					    FALLOC|FSENSE,
					    wcslen(linebuf));
					*vp = '=';
				} else {
					(void) fprintf(stderr, gettext(
					    "Invalid form for variable "
					    "assignment: %S\n"), arg);
					return (1);
				}
				--argc;
				++argv;
				continue;
			}

			default:
				(void) fprintf(stderr,
				gettext("Unknown option \"-%S\"\n"), ap);
				return (usage());
			}
			break;
		}
		if (save_ptr)
			free(save_ptr);
	}
	if (progfilep == &progfiles[0]) {
		if (argc < 2)
			return (usage());
		filename = "[command line]";	/* BUG: NEEDS TRANSLATION */
		progptr = mbstowcsdup(argv[1]);
		proglen = wcslen(progptr);
		--argc;
		++argv;
	}

	argv[0] = cmd;

	awkarginit(argc, argv);

	/* running = 0; */
	(void) yyparse();

	lineno = 0;
	/*
	 * Ok, done parsing, so now activate the rest of the nls stuff, set
	 * the radix character.
	 */
	(void) setlocale(LC_ALL, "");
	radixpoint = *localeconv()->decimal_point;
	awk();
	/* NOTREACHED */
	return (0);
}
Esempio n. 14
0
/*
 * parse a function and its arguments and fill the structure
 */
int encode_function(char *string, struct filter_op *fop)
{
   char *str = strdup(string);
   int ret = -ENOTFOUND;
   char *name, *args;
   int nargs = 0, i;
   char **dec_args = NULL;
   char *tok;

   memset(fop, 0, sizeof(struct filter_op));
   
   /* get the name of the function */
   name = ec_strtok(string, "(", &tok);
   /* get all the args */
   args = name + strlen(name) + 1;

   /* analyze the arguments */
   dec_args = decode_args(args, &nargs);

   /* this fop is a function */
   fop->opcode = FOP_FUNC;

   /* check if it is a known function */
   if (!strcmp(name, "search")) {
      if (nargs == 2) {
         /* get the level (DATA or DECODED) */
         if (encode_offset(dec_args[0], fop) == ESUCCESS) {
            /* encode offset wipe the fop !! */
            fop->opcode = FOP_FUNC;
            fop->op.func.op = FFUNC_SEARCH;
            fop->op.func.string = (u_char*)strdup(dec_args[1]);
            fop->op.func.slen = strescape((char*)fop->op.func.string, (char*)fop->op.func.string);
            ret = ESUCCESS;
         } else
            SCRIPT_ERROR("Unknown offset %s ", dec_args[0]);
      } else
         SCRIPT_ERROR("Wrong number of arguments for function \"%s\" ", name);
   } else if (!strcmp(name, "regex")) {
      if (nargs == 2) {
         int err;
         regex_t regex;
         char errbuf[100];
         
         /* get the level (DATA or DECODED) */
         if (encode_offset(dec_args[0], fop) == ESUCCESS) {
            /* encode offset wipe the fop !! */
            fop->opcode = FOP_FUNC;
            fop->op.func.op = FFUNC_REGEX;
            fop->op.func.string = (u_char*)strdup(dec_args[1]);
            fop->op.func.slen = strescape((char*)fop->op.func.string, (char*)fop->op.func.string);
            ret = ESUCCESS;
         } else
            SCRIPT_ERROR("Unknown offset %s ", dec_args[0]);

         /* check if the regex is valid */
         err = regcomp(&regex, (const char*)fop->op.func.string, REG_EXTENDED | REG_NOSUB | REG_ICASE );
         if (err) {
            regerror(err, &regex, errbuf, sizeof(errbuf));
            SCRIPT_ERROR("%s", errbuf);
         } 
         
         regfree(&regex);
                        
      } else
         SCRIPT_ERROR("Wrong number of arguments for function \"%s\" ", name);
   } else if (!strcmp(name, "pcre_regex")) {
#ifndef HAVE_PCRE
      WARNING("The script contains pcre_regex, but you don't have support for it.");
#else
      pcre *pregex;
      const char *errbuf = NULL;
      int erroff;
      
      if (nargs == 2) {
                     
         /* get the level (DATA or DECODED) */
         if (encode_offset(dec_args[0], fop) == ESUCCESS) {
            /* encode offset wipe the fop !! */
            fop->opcode = FOP_FUNC;
            fop->op.func.op = FFUNC_PCRE;
            fop->op.func.string = strdup(dec_args[1]);
            fop->op.func.slen = strlen(fop->op.func.string);
            ret = ESUCCESS;
         } else
            SCRIPT_ERROR("Unknown offset %s ", dec_args[0]);

         /* check if the pcre is valid */
         pregex = pcre_compile(fop->op.func.string, 0, &errbuf, &erroff, NULL );
         if (pregex == NULL)
            SCRIPT_ERROR("%s\n", errbuf);

         pcre_free(pregex);
      } else if (nargs == 3) {
            
         fop->opcode = FOP_FUNC;
         fop->op.func.op = FFUNC_PCRE;
         /* substitution always at layer DATA */
         fop->op.func.level = 5;
         fop->op.func.string = strdup(dec_args[1]);
         fop->op.func.slen = strlen(fop->op.func.string);
         fop->op.func.replace = strdup(dec_args[2]);
         fop->op.func.rlen = strlen(fop->op.func.replace);
         ret = ESUCCESS;
         
         /* check if the pcre is valid */
         pregex = pcre_compile(fop->op.func.string, 0, &errbuf, &erroff, NULL );
         if (pregex == NULL)
            SCRIPT_ERROR("%s\n", errbuf);

         pcre_free(pregex);
      } else
         SCRIPT_ERROR("Wrong number of arguments for function \"%s\" ", name);
#endif
   } else if (!strcmp(name, "replace")) {
      if (nargs == 2) {
         fop->op.func.op = FFUNC_REPLACE;
         /* replace always operate at DATA level */
         fop->op.func.level = 5;
         fop->op.func.string = (u_char*)strdup(dec_args[0]);
         fop->op.func.slen = strescape((char*)fop->op.func.string, (char*)fop->op.func.string);
         fop->op.func.replace = (u_char*)strdup(dec_args[1]);
         fop->op.func.rlen = strescape((char*)fop->op.func.replace, (char*)fop->op.func.replace);
         ret = ESUCCESS;
      } else
         SCRIPT_ERROR("Wrong number of arguments for function \"%s\" ", name);
   } else if (!strcmp(name, "inject")) {
      if (nargs == 1) {
         fop->op.func.op = FFUNC_INJECT;
         /* inject always operate at DATA level */
         fop->op.func.level = 5;
         fop->op.func.string = (u_char*)strdup(dec_args[0]);
         fop->op.func.slen = strlen((const char*)fop->op.func.string);
         ret = ESUCCESS;
      } else
         SCRIPT_ERROR("Wrong number of arguments for function \"%s\" ", name);
   } else if (!strcmp(name, "execinject")) {
      if (nargs == 1) {
         fop->op.func.op = FFUNC_EXECINJECT;
         /* execinject always operate at DATA level */
         fop->op.func.level = 5;
         fop->op.func.string = (u_char*)strdup(dec_args[0]);
         fop->op.func.slen = strlen((const char*)fop->op.func.string);
         ret = ESUCCESS;
      } else
         SCRIPT_ERROR("Wrong number of arguments for function \"%s\" ", name);
   } else if (!strcmp(name, "log")) {
      if (nargs == 2) {
         /* get the level (DATA or DECODED) */
         if (encode_offset(dec_args[0], fop) == ESUCCESS) {
            /* encode offset wipe the fop !! */
            fop->opcode = FOP_FUNC;
            fop->op.func.op = FFUNC_LOG;
            fop->op.func.string = (u_char*)strdup(dec_args[1]);
            fop->op.func.slen = strlen((const char*)fop->op.func.string);
            ret = ESUCCESS;
         } else
            SCRIPT_ERROR("Unknown offset %s ", dec_args[0]);
      } else
         SCRIPT_ERROR("Wrong number of arguments for function \"%s\" ", name);
   } else if (!strcmp(name, "drop")) {
      if (nargs == 0) {
         fop->op.func.op = FFUNC_DROP;
         ret = ESUCCESS;
      } else
         SCRIPT_ERROR("Wrong number of arguments for function \"%s\" ", name);
   } else if (!strcmp(name, "kill")) {
      if (nargs == 0) {
         fop->op.func.op = FFUNC_KILL;
         ret = ESUCCESS;
      } else
         SCRIPT_ERROR("Wrong number of arguments for function \"%s\" ", name);
   } else if (!strcmp(name, "msg")) {
      if (nargs == 1) {
         fop->op.func.op = FFUNC_MSG;
         fop->op.func.string = (u_char*)strdup(dec_args[0]);
         fop->op.func.slen = strescape((char*)fop->op.func.string, (char*)fop->op.func.string);
         ret = ESUCCESS;
      } else
         SCRIPT_ERROR("Wrong number of arguments for function \"%s\" ", name);
   } else if (!strcmp(name, "exec")) {
      if (nargs == 1) {
         fop->op.func.op = FFUNC_EXEC;
         fop->op.func.string = (u_char*)strdup(dec_args[0]);
         fop->op.func.slen = strlen((const char*)fop->op.func.string);
         ret = ESUCCESS;
      } else
         SCRIPT_ERROR("Wrong number of arguments for function \"%s\" ", name);
   } else if (!strcmp(name, "exit")) {
      if (nargs == 0) {
         fop->opcode = FOP_EXIT;
         ret = ESUCCESS;
      } else
         SCRIPT_ERROR("Wrong number of arguments for function \"%s\" ", name);
   }

   /* free the array */
   for (i = 0; i < nargs; i++)
      SAFE_FREE(dec_args[i]);
      
   SAFE_FREE(dec_args);
   SAFE_FREE(str);
   return ret;
}
Esempio n. 15
0
void cShutdownHandler::CallShutdownCommand(time_t WakeupTime, int Channel, const char *File, bool UserShutdown)
{
  time_t Delta = WakeupTime ? WakeupTime - time(NULL) : 0;
  cString cmd = cString::sprintf("%s %ld %ld %d \"%s\" %d", shutdownCommand, WakeupTime, Delta, Channel, *strescape(File, "\\\"$"), UserShutdown);
  isyslog("executing '%s'", *cmd);
  int Status = SystemExec(cmd, true);
  if (!WIFEXITED(Status) || WEXITSTATUS(Status))
     esyslog("SystemExec() failed with status %d", Status);
  else {
     Setup.NextWakeupTime = WakeupTime; // Remember this wakeup time for comparison on reboot
     Setup.Save();
     }
}
Esempio n. 16
0
/* Handles logging for each room, simply returning if logfile is not defined */
void con_room_log(cnr room, char *nick, char *message)
{
  time_t t;
  xmlnode xml;
  jid user;
  char *output;
  char timestr[80];
  size_t timelen = 79;
  FILE *logfile;
  pool p;

  if(message == NULL || room == NULL) 
  {
    log_warn(NAME, "[%s] ERR: Aborting - NULL reference found - ", FZONE);
    return;
  }

  logfile = room->logfile;

  if(logfile == NULL) 
  {
    log_debug(NAME, "[%s] Logging not enabled for this room", FZONE);
    return;
  }

  p = pool_heap(1024);

  /* nicked from mod_time */
  t = time(NULL);
  
  if(room->logformat == LOG_XHTML)
    strftime(timestr, timelen, "<a name=\"t%H:%M:%S\" href=\"#t%H:%M:%S\">[%H:%M:%S]</a>", localtime(&t));
  else
    strftime(timestr, timelen, "[%H:%M:%S]", localtime(&t));

  if(room->logformat == LOG_XML)
  {
    xml = jutil_msgnew("groupchat", jid_full(room->id) , NULL, strescape(p, message));

    user = jid_new(xmlnode_pool(xml), jid_full(room->id));
    jid_set(user, strescape(p, nick), JID_RESOURCE);
    xmlnode_put_attrib(xml, "from", jid_full(user));

    jutil_delay(xml, NULL);

    fprintf(logfile, "%s\n", xmlnode2str(xml));

    xmlnode_free(xml);
  }
  else if(room->logformat == LOG_XHTML)
  {
    if(nick)
    {
      if(j_strncmp(message, "/me ", 4) == 0)
      {
        output = extractAction(_con_room_xhtml_strescape(p, message), p);
        fprintf(logfile, "<span class=\"time\">%s</span> * <span class=\"nick\">%s</span>%s<br />\n", timestr, strescape(p, nick), output);

      }
      else
      {
        fprintf(logfile, "<span class=\"time\">%s</span> &lt;<span class=\"nick\">%s</span>&gt; %s<br />\n", timestr, strescape(p, nick), _con_room_xhtml_strescape(p, message));
      }
    }
    else
    {
      fprintf(logfile, "<span class=\"time\">%s</span> --- %s<br />\n", timestr, message);
    }
  }
  else
  {
    if(nick)
    {
      if(j_strncmp(message, "/me ", 4) == 0)
      {
        output = extractAction(message, p);
        fprintf(logfile, "%s * %s%s\n", timestr, nick, output);
      }
      else
      {
        fprintf(logfile, "%s <%s> %s\n", timestr, nick, message);
      }
    }
    else
    {
      fprintf(logfile, "%s --- %s\n", timestr, message);
    }
  }

  fflush(logfile);
  pool_free(p);
  return;
}
Esempio n. 17
0
/*
 * assing the value of the const to the fop.value
 *
 * all the value are integer32 and are saved in host order
 */
int encode_const(char *string, struct filter_op *fop)
{
   char *p;
   
   memset(fop, 0, sizeof(struct filter_op));
   
   /* it is an hexadecimal value */
   if (!strncmp(string, "0x", 2) && isdigit((int)string[2])) {
      fop->op.test.value = strtoul(string, NULL, 16);
      return E_SUCCESS;
      
   /* it is an integer value */
   } else if (isdigit((int)string[0])) {
      fop->op.test.value = strtoul(string, NULL, 10);
      return E_SUCCESS;
      
   /* it is an ip address */
   } else if (string[0] == '\'' && string[strlen(string) - 1] == '\'') {
      struct in_addr ipaddr;
      struct in6_addr ip6addr;
      
      /* remove the single quote */
      p = strchr(string + 1, '\'');
      *p = '\0';

      if (inet_pton(AF_INET, string + 1, &ipaddr) == 1) { /* try IPv4 */
         /* 4-bytes - handle as a integer */
         fop->op.test.value = ntohl(ipaddr.s_addr);
      }
      else if (inet_pton(AF_INET6, string + 1, &ip6addr) == 1) { /* try IPv6 */
         /* 16-bytes - handle as a byte pointer */
         memcpy(&fop->op.test.ipaddr, &ip6addr.s6_addr, 16);
      }
      else {
         return -E_FATAL;
      }
      
      return E_SUCCESS;
      
   /* it is a string */
   } else if (string[0] == '\"' && string[strlen(string) - 1] == '\"') {
  
      /* remove the quotes */
      p = strchr(string + 1, '\"');
      *p = '\0';

      /* copy the string */
      fop->op.test.string = (u_char*)strdup(string + 1);
         
      /* escape it in the structure */
      fop->op.test.slen = strescape((char*)fop->op.test.string, (char*)fop->op.test.string);
     
      return E_SUCCESS;
      
   /* it is a constant */
   } else if (isalpha((int)string[0])) {
      return get_constant(string, &fop->op.test.value);
   }
   
   /* anything else is an error */
   return -E_NOTFOUND;
}
Esempio n. 18
0
/*
 * Recursive file perusal.
 *
 * Return FALSE on "?", otherwise TRUE.
 *
 * This function could be made much more efficient with the use of "seek"
 * functionality, especially when moving backwards through a file, or
 * forwards through a file by less than a page at a time.  XXX XXX XXX
 */
bool show_file(const char *name, const char *what, int line, int mode)
{
	int i, k, n;

	struct keypress ch;

	/* Number of "real" lines passed by */
	int next = 0;

	/* Number of "real" lines in the file */
	int size;

	/* Backup value for "line" */
	int back = 0;

	/* This screen has sub-screens */
	bool menu = FALSE;

	/* Case sensitive search */
	bool case_sensitive = FALSE;

	/* Current help file */
	ang_file *fff = NULL;

	/* Find this string (if any) */
	char *find = NULL;

	/* Jump to this tag */
	const char *tag = NULL;

	/* Hold a string to find */
	char finder[80] = "";

	/* Hold a string to show */
	char shower[80] = "";

	/* Filename */
	char filename[1024];

	/* Describe this thing */
	char caption[128] = "";

	/* Path buffer */
	char path[1024];

	/* General buffer */
	char buf[1024];

	/* Lower case version of the buffer, for searching */
	char lc_buf[1024];

	/* Sub-menu information */
	char hook[26][32];

	int wid, hgt;
	
	/* TRUE if we are inside a RST block that should be skipped */
	bool skip_lines = FALSE;



	/* Wipe the hooks */
	for (i = 0; i < 26; i++) hook[i][0] = '\0';

	/* Get size */
	Term_get_size(&wid, &hgt);

	/* Copy the filename */
	my_strcpy(filename, name, sizeof(filename));

	n = strlen(filename);

	/* Extract the tag from the filename */
	for (i = 0; i < n; i++)
	{
		if (filename[i] == '#')
		{
			filename[i] = '\0';
			tag = filename + i + 1;
			break;
		}
	}

	/* Redirect the name */
	name = filename;

	/* Hack XXX XXX XXX */
	if (what)
	{
		my_strcpy(caption, what, sizeof(caption));

		my_strcpy(path, name, sizeof(path));
		fff = file_open(path, MODE_READ, FTYPE_TEXT);
	}

	/* Look in "help" */
	if (!fff)
	{
		strnfmt(caption, sizeof(caption), "Help file '%s'", name);

		path_build(path, sizeof(path), ANGBAND_DIR_HELP, name);
		fff = file_open(path, MODE_READ, FTYPE_TEXT);
	}

	/* Look in "info" */
	if (!fff)
	{
		strnfmt(caption, sizeof(caption), "Info file '%s'", name);

		path_build(path, sizeof(path), ANGBAND_DIR_INFO, name);
		fff = file_open(path, MODE_READ, FTYPE_TEXT);
	}

	/* Oops */
	if (!fff)
	{
		/* Message */
		msg("Cannot open '%s'.", name);
		event_signal(EVENT_MESSAGE_FLUSH);

		/* Oops */
		return (TRUE);
	}


	/* Pre-Parse the file */
	while (TRUE)
	{
		/* Read a line or stop */
		if (!file_getl(fff, buf, sizeof(buf))) break;

		/* Skip lines if we are inside a RST directive*/
		if(skip_lines){
			if(contains_only_spaces(buf))
				skip_lines=FALSE;
			continue;
		}

		/* Parse a very small subset of RST */
		/* TODO: should be more flexible */
		if (prefix(buf, ".. "))
		{
			/* parse ".. menu:: [x] filename.txt" (with exact spacing)*/
			if(prefix(buf+strlen(".. "), "menu:: [") && 
                           buf[strlen(".. menu:: [x")]==']')
			{
				/* This is a menu file */
				menu = TRUE;

				/* Extract the menu item */
				k = A2I(buf[strlen(".. menu:: [")]);

				/* Store the menu item (if valid) */
				if ((k >= 0) && (k < 26))
					my_strcpy(hook[k], buf + strlen(".. menu:: [x] "), sizeof(hook[0]));
			}
			/* parse ".. _some_hyperlink_target:" */
			else if (buf[strlen(".. ")] == '_')
			{
				if (tag)
				{
					/* Remove the closing '>' of the tag */
					buf[strlen(buf) - 1] = '\0';

					/* Compare with the requested tag */
					if (streq(buf + strlen(".. _"), tag))
					{
						/* Remember the tagged line */
						line = next;
					}
				}
			}

			/* Skip this and enter skip mode*/
			skip_lines = TRUE;
			continue;
		}

		/* Count the "real" lines */
		next++;
	}

	/* Save the number of "real" lines */
	size = next;


	/* Display the file */
	while (TRUE)
	{
		/* Clear screen */
		Term_clear();


		/* Restrict the visible range */
		if (line > (size - (hgt - 4))) line = size - (hgt - 4);
		if (line < 0) line = 0;

		skip_lines = FALSE;
		/* Re-open the file if needed */
		if (next > line)
		{
			/* Close it */
			file_close(fff);

			/* Hack -- Re-Open the file */
			fff = file_open(path, MODE_READ, FTYPE_TEXT);
			if (!fff) return (TRUE);

			/* File has been restarted */
			next = 0;
		}


		/* Goto the selected line */
		while (next < line)
		{
			/* Get a line */
			if (!file_getl(fff, buf, sizeof(buf))) break;

			/* Skip lines if we are inside a RST directive*/
			if(skip_lines){
				if(contains_only_spaces(buf))
					skip_lines=FALSE;
				continue;
			}

			/* Skip RST directives */
			if (prefix(buf, ".. "))
			{
				skip_lines=TRUE;
				continue;
			}

			/* Count the lines */
			next++;
		}


		/* Dump the next lines of the file */
		for (i = 0; i < hgt - 4; )
		{
			/* Hack -- track the "first" line */
			if (!i) line = next;

			/* Get a line of the file or stop */
			if (!file_getl(fff, buf, sizeof(buf))) break;

			/* Skip lines if we are inside a RST directive*/
			if(skip_lines){
				if(contains_only_spaces(buf))
					skip_lines=FALSE;
				continue;
			}

			/* Skip RST directives */
			if (prefix(buf, ".. "))
			{
				skip_lines=TRUE;
				continue;
			}

			/* skip | characters */
			strskip(buf,'|');

			/* escape backslashes */
			strescape(buf,'\\');

			/* Count the "real" lines */
			next++;

			/* Make a copy of the current line for searching */
			my_strcpy(lc_buf, buf, sizeof(lc_buf));

			/* Make the line lower case */
			if (!case_sensitive) string_lower(lc_buf);

			/* Hack -- keep searching */
			if (find && !i && !strstr(lc_buf, find)) continue;

			/* Hack -- stop searching */
			find = NULL;

			/* Dump the line */
			Term_putstr(0, i+2, -1, COLOUR_WHITE, buf);

			/* Highlight "shower" */
			if (shower[0])
			{
				const char *str = lc_buf;

				/* Display matches */
				while ((str = strstr(str, shower)) != NULL)
				{
					int len = strlen(shower);

					/* Display the match */
					Term_putstr(str-lc_buf, i+2, len, COLOUR_YELLOW,
								&buf[str-lc_buf]);

					/* Advance */
					str += len;
				}
			}

			/* Count the printed lines */
			i++;
		}

		/* Hack -- failed search */
		if (find)
		{
			bell("Search string not found!");
			line = back;
			find = NULL;
			continue;
		}


		/* Show a general "title" */
		prt(format("[%s, %s, Line %d-%d/%d]", buildid,
		           caption, line, line + hgt - 4, size), 0, 0);


		/* Prompt -- menu screen */
		if (menu)
		{
			/* Wait for it */
			prt("[Press a Letter, or ESC to exit.]", hgt - 1, 0);
		}

		/* Prompt -- small files */
		else if (size <= hgt - 4)
		{
			/* Wait for it */
			prt("[Press ESC to exit.]", hgt - 1, 0);
		}

		/* Prompt -- large files */
		else
		{
			/* Wait for it */
			prt("[Press Space to advance, or ESC to exit.]", hgt - 1, 0);
		}

		/* Get a keypress */
		ch = inkey();

		/* Exit the help */
		if (ch.code == '?') break;

		/* Toggle case sensitive on/off */
		if (ch.code == '!')
		{
			case_sensitive = !case_sensitive;
		}

		/* Try showing */
		if (ch.code == '&')
		{
			/* Get "shower" */
			prt("Show: ", hgt - 1, 0);
			(void)askfor_aux(shower, sizeof(shower), NULL);

			/* Make the "shower" lowercase */
			if (!case_sensitive) string_lower(shower);
		}

		/* Try finding */
		if (ch.code == '/')
		{
			/* Get "finder" */
			prt("Find: ", hgt - 1, 0);
			if (askfor_aux(finder, sizeof(finder), NULL))
			{
				/* Find it */
				find = finder;
				back = line;
				line = line + 1;

				/* Make the "finder" lowercase */
				if (!case_sensitive) string_lower(finder);

				/* Show it */
				my_strcpy(shower, finder, sizeof(shower));
			}
		}

		/* Go to a specific line */
		if (ch.code == '#')
		{
			char tmp[80] = "0";

			prt("Goto Line: ", hgt - 1, 0);
			if (askfor_aux(tmp, sizeof(tmp), NULL))
				line = atoi(tmp);
		}

		/* Go to a specific file */
		if (ch.code == '%')
		{
			char ftmp[80] = "help.hlp";

			prt("Goto File: ", hgt - 1, 0);
			if (askfor_aux(ftmp, sizeof(ftmp), NULL))
			{
				if (!show_file(ftmp, NULL, 0, mode))
					ch.code = ESCAPE;
			}
		}

		switch (ch.code) {
			/* up a line */
			case ARROW_UP:
			case '8': line--; break;

			/* up a page */
			case KC_PGUP:
			case '9':
			case '-': line -= (hgt - 4); break;

			/* home */
			case KC_HOME:
			case '7': line = 0; break;

			/* down a line */
			case ARROW_DOWN:
			case '2':
			case KC_ENTER: line++; break;

			/* down a page */
			case KC_PGDOWN:
			case '3':
			case ' ': line += hgt - 4; break;

			/* end */
			case KC_END:
			case '1': line = size; break;
		}

		/* Recurse on letters */
		if (menu && isalpha((unsigned char)ch.code))
		{
			/* Extract the requested menu item */
			k = A2I(ch.code);

			/* Verify the menu item */
			if ((k >= 0) && (k <= 25) && hook[k][0])
			{
				/* Recurse on that file */
				if (!show_file(hook[k], NULL, 0, mode)) ch.code = ESCAPE;
			}
		}

		/* Exit on escape */
		if (ch.code == ESCAPE) break;
	}

	/* Close the file */
	file_close(fff);

	/* Done */
	return (ch.code != '?');
}