Пример #1
0
int main(int argc, char *argv[]) {
  char *routerip, *interface, mac[6] = "";
  char rdatabuf[1024], wdatabuf[1024], cmsgbuf[1024], mybuf[1024];
  unsigned char *routerip6, *route6, *mac6 = mac, *ip6, *ptr, *ptr1, *ptr2, *ptr3;
  unsigned char *dns;
  int size, /*mtu = 1500, */ i, j, k, l, m, s, len, t, mlen, csize = 0;
  socklen_t fromlen;
  static struct iovec iov;
  struct sockaddr_storage from;
  struct msghdr mhdr;
  struct sockaddr_in6 ddst;
  unsigned long long int count = 0;

  if (argc < 3 || strncmp(argv[1], "-h", 2) == 0)
    help(argv[0]);

  if (strcmp(argv[1], "-r") == 0) {     // is ignored
    argv++;
    argc--;
  }

  memset(mac, 0, sizeof(mac));
  interface = argv[1];
  if (argc >= 6 && (ptr = argv[5]) != NULL)
    sscanf(ptr, "%x:%x:%x:%x:%x:%x", (unsigned int *) &mac[0], (unsigned int *) &mac[1], (unsigned int *) &mac[2], (unsigned int *) &mac[3], (unsigned int *) &mac[4],
           (unsigned int *) &mac[5]);
  else
    mac6 = thc_get_own_mac(interface);

  if (argc >= 5 && argv[4] != NULL)
    ip6 = thc_resolve6(argv[4]);
  else
    ip6 = thc_get_own_ipv6(interface, NULL, PREFER_LINK);

  if (argc >= 4 && argv[3] != NULL)
    dns = thc_resolve6(argv[3]);
  else
    dns = thc_resolve6("FF02::FB");

  routerip = argv[2];
  if ((ptr = index(routerip, '/')) == NULL) {
    printf("Error: Option must be supplied as IP-ADDRESS/PREFIXLENGTH, e.g. ff80::01/16\n");
  }
  *ptr++ = 0;
  size = atoi(ptr);

  routerip6 = thc_resolve6(routerip);
  route6 = thc_resolve6(routerip);

  if (routerip6 == NULL || size < 1 || size > 128) {
    fprintf(stderr, "Error: IP-ADDRESS/PREFIXLENGTH argument is invalid: %s\n", argv[2]);
    exit(-1);
  }
  if (size < 64) {
    fprintf(stderr, "Warning: network prefix must be a minimum of /64, resizing to /64\n");
    size = 64;
  }
  if (size % 8 > 0) {
    size = ((size / 8) + 1) * 8;
    fprintf(stderr, "Warning: prefix must be a multiple of 8, resizing to /%d\n", csize * 8);
  }
  csize = 8 - ((size - 64) / 8);
  if (dns == NULL) {
    fprintf(stderr, "Error: dns argument is invalid: %s\n", argv[3]);
    exit(-1);
  }
  if (ip6 == NULL) {
    fprintf(stderr, "Error: link-local-ip6 argument is invalid: %s\n", argv[4]);
    exit(-1);
  }

/*
  if (mtu < 1 || mtu > 65536) {
    fprintf(stderr, "Error: mtu argument is invalid: %s\n", argv[5]);
    exit(-1);
  }
  if (mtu < 1228 || mtu > 1500)
    fprintf(stderr, "Warning: unusual mtu size defined, be sure what you are doing :%d\n", mtu);
*/
  if (mac6 == NULL) {
    fprintf(stderr, "Error: mac address in invalid\n");
    exit(-1);
  }

  if ((s = thc_bind_udp_port(547)) < 0) {
    fprintf(stderr, "Error: could not bind to 547/udp\n");
    exit(-1);
  }
  if (thc_bind_multicast_to_socket(s, interface, thc_resolve6("ff02::1:2")) < 0 || thc_bind_multicast_to_socket(s, interface, thc_resolve6("ff02::1:3")) < 0) {
    fprintf(stderr, "Error: could not bind multicast address\n");
    exit(-1);
  }
  if ((t = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
    perror("Error:");
    exit(-1);
  }

  memset(mybuf, 0, sizeof(mybuf));
  mybuf[1] = 2;
  mybuf[3] = 14;
  mybuf[5] = 1;
  mybuf[7] = 1;
  // mybuf + 8 == time
  memcpy(mybuf + 12, mac6, 6);
  mlen = 18;
  mybuf[mlen + 1] = 23;
  mybuf[mlen + 3] = 16;
  memcpy(mybuf + mlen + 4, dns, 16);
  mlen += 20;

  printf("Starting to fake dhcp6 server on %s for %s (Press Control-C to end) ...\n\n", interface, argv[2]);
  while (1) {
    memset((char *) &from, 0, sizeof(from));
    memset(&iov, 0, sizeof(iov));
    memset(&mhdr, 0, sizeof(mhdr));
    iov.iov_base = rdatabuf;
    iov.iov_len = sizeof(rdatabuf);
    mhdr.msg_name = &from;
    mhdr.msg_namelen = sizeof(from);
    mhdr.msg_iov = &iov;
    mhdr.msg_iovlen = 1;
    mhdr.msg_control = (caddr_t) cmsgbuf;
    mhdr.msg_controllen = sizeof(cmsgbuf);
    if ((len = recvmsg(s, &mhdr, 0)) > 0) {
      fromlen = mhdr.msg_namelen;
      if (debug)
        thc_dump_data(rdatabuf, len, "Received Packet");
      ddst.sin6_addr = ((struct sockaddr_in6 *) mhdr.msg_name)->sin6_addr;
      ptr2 = thc_ipv62notation((char *) &ddst.sin6_addr);
      switch (rdatabuf[0]) {
      case 1:
        ptr1 = "Solicitate";
        break;
      case 2:
        ptr1 = "Advertise (illegal, ignored)";
        break;
      case 3:
        ptr1 = "Request";
        break;
      case 4:
        ptr1 = "Confirm";
        break;
      case 5:
        ptr1 = "Renew";
        break;
      case 6:
        ptr1 = "Rebind";
        break;
      case 7:
        ptr1 = "Reply (illegal, ignored)";
        break;
      case 8:
        ptr1 = "Release (ignored)";
        break;
      case 9:
        ptr1 = "Decline (ignored)";
        break;
      case 10:
        ptr1 = "Reconfigure (illegal, ignored)";
        break;
      case 11:
        ptr1 = "Information Request (ignored)";
        break;
      case 12:
        ptr1 = "Relay Forward (ignored)";
        break;
      case 13:
        ptr1 = "Relay Reply (ignored)";
        break;
      default:
        ptr1 = "Unknown (ignored)";
        break;
      }
      printf("Received DHCP6 %s packet from %s\n", ptr1, ptr2);
      free(ptr2);
      if (rdatabuf[0] >= 1 && rdatabuf[0] < 7 && rdatabuf[0] != 2) {
        memset(wdatabuf, 0, sizeof(wdatabuf));
        memcpy(wdatabuf + 1, rdatabuf + 1, 3);
        i = j = 4;
        k = -1;
        if (rdatabuf[0] == 1) { // initial request
          wdatabuf[0] = 2;
          while ((j + 4) < len) {
            l = rdatabuf[j + 2] * 256 + rdatabuf[j + 3];
            if (l + j + 4 > len) {
              l = 0;
              j = len;
              printf("Info: received evil packet\n");
            } else {
              if (rdatabuf[j + 1] == 1) {
                memcpy(wdatabuf + i, rdatabuf + j, l + 4);
                i += l + 4;
              } else if (rdatabuf[j + 1] == 3) {
                k = j;          // just set a pointer
              }
              j += l + 4;
            }
          }
          // add 02, 23
          j = time(NULL);
          memcpy(mybuf + 8, (char *) &j, 4);
          memcpy(wdatabuf + i, mybuf, mlen);
          i += mlen;
          // now expand 3
          if (k > -1 && rdatabuf[k + 3] == 12 && rdatabuf[k + 2] == 0) {        // copy structure
            memcpy(wdatabuf + i, rdatabuf + k, 16);
          } else {              // or create new
            wdatabuf[i + 1] = 3;
            memcpy(wdatabuf + i + 4, (char *) &j, 4);   // copy time as IAID
          }
          wdatabuf[i + 3] = 40;
          memset(wdatabuf + i + 8, 0, 8);
          wdatabuf[i + 10] = 0x7f;
          wdatabuf[i + 14] = 0xfe;
          i += 16;
          wdatabuf[i + 1] = 5;
          wdatabuf[i + 3] = 24;
          memcpy(wdatabuf + i + 4, routerip6, 16);      // address
          count++;
          if (csize > 0)
            memcpy(wdatabuf + i + 4 + 16 - csize, (char *) &count, csize);      // counter
          ptr3 = thc_ipv62notation(wdatabuf + i + 4);
          wdatabuf[i + 21] = 2;
          wdatabuf[i + 25] = 2;
          i += 28;
        } else {
          wdatabuf[0] = 7;
          m = 0;
          while ((j + 4) < len) {
            l = rdatabuf[j + 2] * 256 + rdatabuf[j + 3];
            if (l + j + 4 > len) {
              l = 0;
              j = len;
              printf("Info: received evil packet\n");
            } else {            // just copy types 1-3 and 23
              if ((rdatabuf[j + 1] >= 1 && rdatabuf[j + 1] <= 3) || rdatabuf[j + 1] == 23) {
                memcpy(wdatabuf + i, rdatabuf + j, l + 4);
                i += l + 4;
                if (rdatabuf[j + 1] == 23)
                  k = 1;
                if (rdatabuf[j + 1] == 3)
                  m = 1;
              }
              j += l + 4;
            }
          }
          if (k == -1) {
            memcpy(wdatabuf + i, mybuf + 18, 20);
            i += 20;
          }
        }
        len = i;
        if (debug)
          thc_dump_data(wdatabuf, len, "Reply Packet");
        ddst.sin6_family = AF_INET6;
        ddst.sin6_port = htons(546);
        //ddst.sin6_addr = ((struct sockaddr_in6 *)mhdr.msg_name)->sin6_addr;
        ddst.sin6_scope_id = ((struct sockaddr_in6 *) mhdr.msg_name)->sin6_scope_id;
        if (sendto(t, wdatabuf, len, 0, (struct sockaddr *) &ddst, sizeof(ddst)) < 0)
          perror("Error:");
        else {
          ptr2 = thc_ipv62notation((char *) &ddst.sin6_addr);
          if (wdatabuf[0] == 2) {
            printf("Sent DHCP6 Advertise packet to %s (offer: %s)\n", ptr2, ptr3);
            free(ptr3);
          } else if (m)
            printf("Sent DHCP6 Reply packet to %s (address accepted)\n", ptr2);
          else
            printf("Sent DHCP6 Reply packet to %s (did not set address)\n", ptr2);
          free(ptr2);
        }
      }
    }
  }

/*  packet structure:
      1 byte  = type
      3 bytes = sessionid
      while(packet data) {
        2 bytes = type
        2 bytes = length in bytes of following data
        ... defined fixed length data ...
      }

    server listen on ff02::1:2 udp 547
    client connects from linklocal port 546, ttl 1
        01 = solicit
        3 bytes = sessionid
        6 bytes = blog (elapsed, 8)
        8 bytes = 01 blob (client id + time + mac)
        4 bytes = time
        6 bytes = mac
        16 bytes = 03 blob (want perm address)
        5 + length + hostname = hostname
        18 bytes = blob (vendor class, type 16)
        12 bytes = blob (requested options, type 6)
    server sends to linklocal (respect client port), ttl 1
        02 = advertise
        3 bytes = sessionid (copy)
        18 bytes = 01 blob (client copy of client-id)
        8 bytes = 02 blob (server id + time + mac)
        4 bytes = time
        6 bytes = mac
        0003 = give perm address
        2 bytes = length
        4 bytes = IAID (from client request!)
        4 bytes = validity time 1 (1800)
        4 bytes = validity time 2 (2880)
          0005 = address structure
          2 bytes = length (24 bytes)
          16 bytes = address
          4 bytes = validity time (3600)
          4 byte = validity time (same)
        0023 = dns option
        2 bytes = length (16 bytes)
        16 bytes = dns server address
    client sends to ff02::1:2 !
        03 = request
        3 bytes = sessionid
        6 bytes = blog (elapsed, 8)
        8 bytes = 01 blob (client id + time + mac)
        4 bytes = time
        6 bytes = mac
        18 bytes = client (again)
        18 bytes = server (copy)
        44 bytes = address (copy)
        5 + length + hostname = hostname (again)
        18 bytes = blob again (vendor class, type 16)
        12 bytes = blob again (requested options, type 6)
    server replies
        7 = reply
        copy original advertise packet :-)
  */

  return 0;                     // never reached
}
Пример #2
0
void dtkColorGrid::keyPressEvent ( QKeyEvent * event )
{
    QToolTip::hideText();

    switch (event->key()) {

        case Qt::Key_Right:
            if (d->idx == -1) {
                d->row = d->col = 0;
                d->idx = 0;
            } else {
                if (++d->col == d->widthInCells)
                { d->col = 0; d->row++; }
                d->idx = index();
                if (d->idx == -1) {
                    d->row = d->col = 0;
                    d->idx = 0;
                }
            }
            repaint();
            d->hlColor = d->colors->at(d->idx);
            emit highlighted(d->hlColor);
            event->accept();
            return;

        case Qt::Key_Left:
            if (d->idx == -1) {
                d->row = d->col = 0;
                d->idx = 0;
            } else {
                if (--d->col < 0)
                { d->col = d->widthInCells-1; d->row--; }
                d->idx = index();
                if (d->idx == -1) {
                    d->row = heightInCells()-1;
                    d->idx = d->colors->size()-1;
                    d->col = d->idx % d->widthInCells;
                }
            }
            repaint();
            d->hlColor = d->colors->at(d->idx);
            emit highlighted(d->hlColor);
            event->accept();
            return;

        case Qt::Key_Up:
            if (d->idx == -1) {
                d->row = d->col = 0;
                d->idx = 0;
            } else {
                int h = heightInCells()-1;
                if (--d->row < 0)
                {
                    d->row = h;
                    if (--d->col < 0) {
                        d->row = h;
                        d->idx = d->colors->size()-1;
                        d->col = d->idx % d->widthInCells;
                    }
                }
                d->idx = index();
                if (d->idx == -1 && d->row == h) {
                    d->row--;
                    d->idx = index();
                }
                if (d->idx == -1) {
                    d->row = h;
                    d->idx = d->colors->size()-1;
                    d->col = d->idx % d->widthInCells;
                }
            }
            repaint();
            d->hlColor = d->colors->at(d->idx);
            emit highlighted(d->hlColor);
            event->accept();
            return;

        case Qt::Key_Down:
            if (d->idx == -1) {
                d->row = d->col = 0;
                d->idx = 0;
            } else {
                int h = heightInCells()-1;
                if (++d->row > h)
                { d->row = 0; d->col++; }
                d->idx = index();
                if (d->idx == -1 && d->row == h) {
                    d->row = 0; d->col++;
                    d->idx = index();
                }
                if (d->idx == -1) {
                    d->row = d->col = 0;
                    d->idx = 0;
                }
            }
            repaint();
            d->hlColor = d->colors->at(d->idx);
            emit highlighted(d->hlColor);
            event->accept();
            return;

        case Qt::Key_Return:
            if (d->idx != -1) {
                emit picked(d->selColor = d->hlColor);
                emit accepted();
            }
            event->accept();
            return;

        case Qt::Key_Escape:
            emit rejected();
            event->accept();
            return;

        default:
            event->ignore();
    }

    return QWidget::keyPressEvent(event);
}
Пример #3
0
void SessionModel::setDecimalTotals(bool decimals)
{
	m_decimals = decimals;
	emit dataChanged(index(0, 0), index(rowCount(), columnCount()));
}
Пример #4
0
void ListModel::update(int row)
{
    emit dataChanged(index(row, 0), index(row, 1));
}
Пример #5
0
/**
 * magmad command line parsing code 
 *
 * @param argc number of command line arguments
 * @param argv vector of command line arguments
 */
void magma_parse_args(int argc, char **argv)
{
	memset(magma_environment.log, 0, 255);

	magma_environment.progname = *argv;						/* saving program name */
	magma_environment.port = MAGMA_PORT;					/* default port */
	magma_environment.servername = g_strdup("");			/* default server name */
	magma_environment.nickname = g_strdup("");				/* default server nickname */
	magma_environment.ipaddr = g_strdup("");				/* default server IP address */
	magma_environment.hashpath = g_strdup("");				/* default server path for local storage */
	magma_environment.bootserver = NULL;					/* default remote boot server */
	magma_environment.secretkey = NULL;
	magma_environment.bandwidth = MAGMA_DEFAULT_BANDWIDTH;	/* Declared bandwidth */
	magma_environment.storage = MAGMA_DEFAULT_STORAGE;		/* Declared storage */
	magma_environment.bootstrap = 0;						/* If true, this node should bootstrap a new network, if false this node should join an existing one */

	/*
	 * cycling through options
	 */
	char c;
	while ((c = getopt(argc, argv, "blhHA?D:Tp:i:n:s:d:w:r:k:" )) != -1) {
		switch (c) {
			case 'b':
				if (magma_environment.bootserver) {
					dbg(LOG_ERR, DEBUG_BOOT, "Bootstrap and remote server can't be specified together. Exiting now.");
					exit(1);
				}
				magma_environment.bootstrap = 1;
				break;
			case 'h':
			case 'H':
				magma_usage(NULL);
				break;
			case 'A':
				memset(magma_environment.log, 1, 255);
				dbg(LOG_INFO, DEBUG_BOOT, "Enabling all debug statements");
				break;
			case 'D':
				if (optarg) {
					magma_environment.logstring = g_strdup(optarg);
					dbg(LOG_INFO, DEBUG_BOOT, "Setting debug mask to %s", magma_environment.logstring);
				}
				break;
			case 'p':
				if (optarg) {
					magma_environment.port = atol(optarg);
					dbg(LOG_INFO, DEBUG_BOOT, "port: %d", magma_environment.port);
				}
				break;
			case 'i':
				if (optarg) {
					g_free_null(magma_environment.ipaddr);
					magma_environment.ipaddr = g_strdup(optarg);
					dbg(LOG_INFO, DEBUG_BOOT, "Server local IP addr: %s", magma_environment.ipaddr);
				}
				break;
			case 'n':
				if (optarg) {
					g_free_null(magma_environment.nickname);
					magma_environment.nickname = g_strndup(optarg, 255);
					dbg(LOG_INFO, DEBUG_BOOT, "Server Nickname: %s", magma_environment.nickname);
				}
				break;
			case 's':
				if (optarg) {
					g_free_null(magma_environment.servername);
					magma_environment.servername = g_strndup(optarg, 255);
					dbg(LOG_INFO, DEBUG_BOOT, "Server FQDN name: %s", magma_environment.servername);
				}
				break;
			case 'd':
				if (optarg) {
					g_free_null(magma_environment.hashpath);
					magma_environment.hashpath = g_strdup(optarg);
					if (magma_environment.hashpath[strlen(magma_environment.hashpath) - 1] == '/') {
						magma_environment.hashpath[strlen(magma_environment.hashpath) - 1] = '\0';
					}
					dbg(LOG_INFO, DEBUG_BOOT, "Hash Dir Path: %s", magma_environment.hashpath);
				}
				break;
			case 'w':
				if (optarg) {
					magma_environment.bandwidth = atol(optarg);
					dbg(LOG_INFO, DEBUG_BOOT, "Declared Bandwidth: %dKbit/s", magma_environment.bandwidth);
				}
				break;
			case 'r':
				if (optarg) {
					if (magma_environment.bootstrap) {
						dbg(LOG_ERR, DEBUG_BOOT, "Bootstrap and remote server can't be specified together. Exiting now.");
						exit(1);
					}
					g_free_null(magma_environment.bootserver);
					char *portp = NULL;
					if ((portp = rindex(optarg,':')) != NULL) {
						*portp = '\0';
						portp++;
						magma_environment.bootport = atoi(portp);
					} else {
						magma_environment.bootport = MAGMA_PORT;
					}
					magma_environment.bootserver = g_strdup(optarg);
					magma_environment.bootstrap = 0;
					dbg(LOG_INFO, DEBUG_BOOT, "Remote boot server: %s:%u", magma_environment.bootserver, magma_environment.bootport);
				}
				break;
			case 'k':
				if (optarg) {
					magma_environment.secretkey = g_strdup(optarg);
					dbg(LOG_INFO, DEBUG_BOOT, "Secret Key is [%s]", magma_environment.secretkey);
				}
				break;
			case '?':
				if (isprint(optopt)) {
					dbg(LOG_ERR, DEBUG_ERR, "Unknown option -%c", optopt);
					magma_usage(NULL);
				} else {
					dbg(LOG_INFO, DEBUG_BOOT, "Unknown option character \\x%x", optopt);
				}
				break;
			default:
				break;
		}
	}

	magma_expand_log_channels(&magma_environment);

	GResolver *resolver = g_resolver_get_default();

	/*
	 * try to replace default nickname with a valid one from the DNS
	 */
	if (!strlen(magma_environment.nickname)) {
		char *hostname = malloc(HOST_NAME_MAX);
		if (hostname != NULL) {
			if (gethostname(hostname, HOST_NAME_MAX) == 0) {
				g_free_null(magma_environment.nickname);
				magma_environment.nickname = g_strdup(hostname);
			}
			g_free_null(hostname);
		}
	}
	
	/*
	 * try to replace default server name with a valid one from the DNS
	 */
	if (!strlen(magma_environment.servername)) {
		/*
		struct hostent *h = gethostbyname(magma_environment.nickname);
		if (h != NULL) {
			g_free_null(magma_environment.servername);
			magma_environment.servername = g_strdup(h->h_name);
			if (index(magma_environment.servername, '.') == NULL) {
				// server name should be a fully qualified name!!!
				magma_usage("Server Fully Qualified Name is not Fully Qualified!");
			}
		}
		*/

		GList *addr = g_resolver_lookup_by_name(resolver, magma_environment.nickname, NULL, NULL);
		gchar *addr_string = g_list_nth_data(addr, 0);

		if (!addr_string) {
			gchar *string = g_strdup_printf(
				"No FQDN provided and magmad was unable to resolve one from %s",
				magma_environment.nickname);
			magma_usage(string);
		} else {
			if (!index(magma_environment.servername, '.')) {
				magma_usage("Server Fully Qualified Name is not Fully Qualified!");
			}
		}
	}
	
	/*
	 * Without a valid IP address the server can't start.
	 * Try to resolve magma_environment.servername and exit
	 * if the operation fails
	 */
	if (inet_aton(magma_environment.ipaddr, NULL) == 0) {
		GList *addr = g_resolver_lookup_by_name(resolver, magma_environment.servername, NULL, NULL);
		gchar *addr_string = g_list_nth_data(addr, 0);

		if (!addr_string) {
			gchar *string = g_strdup_printf("No IP address provided and can't resolve %s", magma_environment.servername);
			magma_usage(string);
		} else {
			magma_environment.ipaddr = addr_string;
		}
	}

	/*
	 * if neither boot server or bootstrap has been specified, the
	 * server should load its state from last saved lava topology
	 */
	if (!magma_environment.bootstrap && !magma_environment.bootserver) {
		if (!magma_environment.nickname || !strlen(magma_environment.nickname)) {
			magma_usage("Please specify server nickname to allow status loading from disk!");
		}
	} else if (magma_environment.secretkey == NULL ) {
		magma_usage("No secret key specified! Network can't be created or joined!");
	}

	g_object_unref(resolver);
}
Пример #6
0
/*
 * next_token
 * Given a string, return the next token. The string is modified to return
 * the remainder of the string after the identified token.
 * A token is found either as characters delimited by one or many spaces.
 * Or as a pair of double-quotes(") with any characters in between.
 * if there are trailing spaces after the token, trail is set to one.
 * If string is NULL or "", NULL is returned.
 * If empty token found, s0 is NULL
 * NOTE: token must be freed after use.
 */
static int
next_token(char **s0, char **token0, int *trail0)
{
  char *s;
  char *st;
  char *token = NULL;
  size_t len;
  int quote=0;
  int trail=0;

  s = *s0;
  if (s==NULL){
    fprintf(stderr, "%s: null string\n", __FUNCTION__);
    return -1;
  }
  for (s=*s0; *s; s++){ /* First iterate through delimiters */
    if (index(CLIGEN_DELIMITERS, *s) == NULL)
      break;
    trail++;
  }
  if (*s && index(CLIGEN_QUOTES, *s) != NULL){
    quote++;
    s++;
  }
  st=s; /* token starts */
  for (; *s; s++){ /* Then find token */
    if (quote){
      if (index(CLIGEN_QUOTES, *s) != NULL)
	break;
    }
    else
      if (index(CLIGEN_DELIMITERS, *s) != NULL)
	break;
  }
  if (quote && *s){
    s++;
    // fprintf(stderr, "s=\"%s\" %d %s\n", s, *s, index(CLIGEN_DELIMITERS, *s));
    if (*s && index(CLIGEN_DELIMITERS, *s) == NULL){
	;//	cligen_reason("Quote token error");
    }
    len = (s-st)-1;
  }
  else{
      if (quote){ /* Here we signalled error before but it is removed */
	  st--;
      }
    len = (s-st);
    if (!len){
      token = NULL;
      *s0 = NULL;
      goto done;
    }
  }
  if ((token=malloc(len+1)) == NULL){
    fprintf(stderr, "%s: malloc: %s\n", __FUNCTION__, strerror(errno));
    return -1;
  }
  memcpy(token, st, len);
  token[len] = '\0';
  *s0 = s;
 done:
  *trail0 = trail;
  *token0 = token;
  return 0;
}
Пример #7
0
 FilePath::const_iterator FilePath::cbegin() const
 {
   return index();
 }
Пример #8
0
QVariant BookmarksModel::data(int i, int role) const
{
	return data(index(i, 0), role);
}
Пример #9
0
QVariant UrlRetrievalModel::data(int row, const QByteArray &role) const {
    return data(index(row), m_roles.key(role));
}
Пример #10
0
void GMMExpectationMaximization::autoInitializeByEqualIntervals(uint num_gaussians,uint col,const MatrixX & dataset)
{
  uint data_count = dataset.rows();
  uint dim = dataset.cols();

  std::vector<std::vector<uint> > index(num_gaussians);
  for(uint g = 0; g < num_gaussians; g++)
    index[g].reserve(data_count / num_gaussians);

  m_weights.clear();
  m_weights.resize(num_gaussians);
  m_means.clear();
  m_means.resize(num_gaussians,VectorX::Zero(dim));
  m_covs.clear();
  m_covs.resize(num_gaussians,MatrixX::Zero(dim,dim));

  // find max and min value for column col
  Real cmax = dataset(0,col);
  Real cmin = dataset(0,col);
  for(uint n = 1; n < data_count; n++)
  {
    if (dataset(n,col) > cmax) cmax = dataset(n,col);
    if (dataset(n,col) < cmin) cmin = dataset(n,col);
  }
  Real cspan = cmax - cmin;

  for(uint n = 0; n < data_count; n++) 
  {
    // compute gaussian index to which this point belongs
    uint gi = uint((dataset(n,col) - cmin) / (cspan + 1.0) * Real(num_gaussians));

    // sum the points to obtain means
    m_means[gi] += dataset.row(n);

    index[gi].push_back(n);
  }

  for (uint g = 0; g < num_gaussians; g++)
  {
    uint popsize = index[g].size();
    // avoid division by zero: if no samples are available, initialize to something from somewhere
    if (popsize == 0)
    {
      m_means[g] = dataset.row(g % data_count);
      m_covs[g] = MatrixX::Identity(dim,dim);
      m_weights[g] = 1.0f / Real(num_gaussians);
      continue;
    }

    // average by popsize
    m_means[g] /= Real(popsize);
    // same weight for all gaussians
    m_weights[g] = 1.0f / Real(num_gaussians);
     
    // compute covariance matrix
    for (uint p = 0; p < popsize; p++)
    {
      const Eigen::VectorXf & r = dataset.row(index[g][p]);
      const Eigen::VectorXf & m = m_means[g];
      m_covs[g] += (r - m) * (r - m).transpose();
    }

    m_covs[g] /= Real(popsize);
    m_covs[g] += MatrixX::Identity(dim,dim) * m_epsilon;
  }
}
Пример #11
0
bool IndDBase::load_phenotypes( const std::string & filename )
{

  if ( ! attached() ) Helper::halt( "no attached INDDB" );

  if ( ! Helper::fileExists(filename) ) 
    {
      plog.warn("could not find phenotype file " + filename );
      return false;
    }

  // Expect a variant of FAM file format
  
  InFile f( filename );

  std::map<std::string,int> phe_codes1;
  std::map<int,int> phe_codes2;
  std::vector<std::string> phe_codes;
  std::map<std::string,mType> type_codes;
  
  std::map<std::string,std::string> mis_codes;
  
  int expected_col_count = -1;
  int inserted = 0;
  
  sql.begin();

  drop_index();
 
  while ( ! f.eof() )
    {
      
      std::string s = f. readLine();
      
      if ( s == "" ) continue;
      
      // Meta-information? 
      
      if ( s.size() > 2 && s.substr(0,2) == "##" )
	{
	  
	  std::vector<std::string> tok = Helper::quoted_parse( s.substr(2) );
	  
	  // need at least a name
	  if ( tok.size() < 1 ) continue;	  
	  std::string name = tok[0];

	  // defaults
	  std::string type = "Integer"; 
	  std::string miss = "0";
	  std::string desc = "Dichotomous phenotype";	  
	  if ( tok.size() >= 2 ) type = tok[1];
	  if ( tok.size() >= 3 ) miss = tok[2];
	  if ( tok.size() >= 4 ) desc = tok[3];
	  
	  int code = insert_phenotype( name, type, miss, desc );

	  phe_codes1[ name ] = code;
	  mis_codes[ name ] = miss;
	  
	  if ( Helper::is_int( type ) ) type_codes[ name ] = META_INT;
	  else if ( Helper::is_float( type ) ) type_codes[ name ] = META_FLOAT;
	  else type_codes[ name ] = META_TEXT;

	}

      // Or header line?
      
      else if ( s.substr(0,1) == "#" )
	{
	  
	  // #ID phe1 phe2 phe3
	  
	  std::vector<std::string> tok = Helper::parse( s , " \t");
	  
	  if ( tok.size() < 2 ) { plog.warn("malformed phenotype file"); continue; } 
	  if ( tok[0] != "#ID" ) { plog.warn("malformed phenotype file"); continue; } 
	  
	  for ( int i = 1 ; i < tok.size(); i++ )
	    {
	      std::map<std::string,int>::iterator k = phe_codes1.find( tok[i] );	      

	      if ( k == phe_codes1.end() ) 
		Helper::halt( tok[i] + " in header of phenotype file but not defined" );
	      
	      phe_codes2[ i ] = k->second;
	      phe_codes.push_back( tok[i] );
	      
	    }
	  expected_col_count = tok.size();
	}
      
      // Or data ? 
      
      else 
	{
	  
	  // Skip, if we haven't seen a header
	  if ( expected_col_count == -1 ) continue;
	 
	  std::vector<std::string> tok = Helper::parse( s , " \t");
	  
	  if ( tok.size() != expected_col_count ) 
	    {
	      plog.warn("row in phenotype file with wrong number of fields");
	      continue;
	    }
	  
	  int indiv_id = fetch_id( tok[0] );
	  
	  // if individual does not exist, create

	  if ( indiv_id == 0 ) 
	    {
	      std::string period = ".";

	      sql.bind_text( stmt_insert_individual , ":name" , tok[0] );
	      sql.bind_text( stmt_insert_individual , ":fid" , period );
	      sql.bind_text( stmt_insert_individual , ":fid" , period );
	      sql.bind_text( stmt_insert_individual , ":iid" , period );
	      sql.bind_text( stmt_insert_individual , ":pat" , period );
	      sql.bind_text( stmt_insert_individual , ":mat" , period );
	      sql.bind_text( stmt_insert_individual , ":sex" , period );
	      
	      sql.step( stmt_insert_individual );
	      sql.reset( stmt_insert_individual );
	      
	      // and grab the ID
	      indiv_id = fetch_id( tok[0] );

	    }
	  
	  //
	  // Insert actual phenotypes
	  //
	  
	  for ( int i = 1; i < tok.size(); i++ )
	    {

	      // skip undefined phenotypes
	      if ( phe_codes2[i] == 0 ) continue;

	      // skip missing values
	      if ( tok[i] == mis_codes[ phe_codes[i-1] ] ) continue;
	      
	      mType mt = type_codes[ phe_codes[ i-1 ] ];
	      
	      // skip invalid values for numerics (as MT will be registered)
	      
 	      if ( mt == META_INT )
 		{    
 		  int x;
 		  if ( Helper::str2int( tok[i] , x ) )
 		    insert( indiv_id , phe_codes2[i] , x );
 		}
 	      else if ( mt == META_FLOAT )
 		{
 		  double x;
 		  if ( Helper::str2dbl( tok[i] , x ) )
 		    insert( indiv_id , phe_codes2[i] , x );
 		}
 	      else 
 		{
 		  insert( indiv_id , phe_codes2[i] , tok[i] );
 		}


	    }
	  ++inserted;	    
	}
    }
  
  f.close();

  index();
  
  sql.commit();

  plog << "Processed " << inserted << " rows\n";
  
  if ( inserted && GP && GP->has_project_file() ) 
    GP->fIndex.append_to_projectfile( Helper::fullpath( filename ) , "PHE" );
    
  return true;
}
Пример #12
0
void RecentRequestsTableModel::sort(int column, Qt::SortOrder order)
{
    qSort(list.begin(), list.end(), RecentRequestEntryLessThan(column, order));
    Q_EMIT dataChanged(index(0, 0, QModelIndex()), index(list.size() - 1, NUMBER_OF_COLUMNS - 1, QModelIndex()));
}
Пример #13
0
/*
 * Evil wildcarding resource string lookup.
 * This walks the supplied env string table and returns a match.
 * The start point can be remembered for incremental searches.
 */
static int
res_find(int *line, int *startln,
    const char *name, int *unit, const char *resname, const char *value,
    const char **ret_name, int *ret_namelen, int *ret_unit,
    const char **ret_resname, int *ret_resnamelen, const char **ret_value)
{
	int n = 0, hit, i = 0;
	char r_name[32];
	int r_unit;
	char r_resname[32];
	char r_value[128];
	const char *s, *cp;
	char *p;

#ifndef __rtems__
	if (checkmethod) {
		hintp = NULL;

		switch (hintmode) {
		case 0:		/* loader hints in environment only */
			break;
		case 1:		/* static hints only */
			hintp = static_hints;
			checkmethod = 0;
			break;
		case 2:		/* fallback mode */
			if (dynamic_kenv) {
				mtx_lock(&kenv_lock);
				cp = kenvp[0];
				for (i = 0; cp != NULL; cp = kenvp[++i]) {
					if (!strncmp(cp, "hint.", 5)) {
						use_kenv = 1;
						checkmethod = 0;
						break;
					}
				}
				mtx_unlock(&kenv_lock);
			} else {
				cp = kern_envp;
				while (cp) {
					if (strncmp(cp, "hint.", 5) == 0) {
						cp = NULL;
						hintp = kern_envp;
						break;
					}
					while (*cp != '\0')
						cp++;
					cp++;
					if (*cp == '\0') {
						cp = NULL;
						hintp = static_hints;
						break;
					}
				}
			}
			break;
		default:
			break;
		}
		if (hintp == NULL) {
			if (dynamic_kenv) {
				use_kenv = 1;
				checkmethod = 0;
			} else
				hintp = kern_envp;
		}
	}

	if (use_kenv) {
		mtx_lock(&kenv_lock);
		i = 0;
		cp = kenvp[0];
		if (cp == NULL) {
			mtx_unlock(&kenv_lock);
			return (ENOENT);
		}
	} else
#endif /* __rtems__ */
		cp = hintp;
	while (cp) {
		hit = 1;
		(*line)++;
		if (strncmp(cp, "hint.", 5) != 0)
			hit = 0;
		else
			n = sscanf(cp, "hint.%32[^.].%d.%32[^=]=%127s",
			    r_name, &r_unit, r_resname, r_value);
		if (hit && n != 4) {
			printf("CONFIG: invalid hint '%s'\n", cp);
			/* XXX: abuse bogus index() declaration */
			p = index(cp, 'h');
			*p = 'H';
			hit = 0;
		}
		if (hit && startln && *startln >= 0 && *line < *startln)
			hit = 0;
		if (hit && name && strcmp(name, r_name) != 0)
			hit = 0;
		if (hit && unit && *unit != r_unit)
			hit = 0;
		if (hit && resname && strcmp(resname, r_resname) != 0)
			hit = 0;
		if (hit && value && strcmp(value, r_value) != 0)
			hit = 0;
		if (hit)
			break;
		if (use_kenv) {
#ifndef __rtems__
			cp = kenvp[++i];
			if (cp == NULL)
				break;
#else /* __rtems__ */
			(void) i;
#endif /* __rtems__ */
		} else {
			while (*cp != '\0')
				cp++;
			cp++;
			if (*cp == '\0') {
				cp = NULL;
				break;
			}
		}
	}
#ifndef __rtems__
	if (use_kenv)
		mtx_unlock(&kenv_lock);
#endif /* __rtems__ */
	if (cp == NULL)
		return ENOENT;

	s = cp;
	/* This is a bit of a hack, but at least is reentrant */
	/* Note that it returns some !unterminated! strings. */
	s = index(s, '.') + 1;		/* start of device */
	if (ret_name)
		*ret_name = s;
	s = index(s, '.') + 1;		/* start of unit */
	if (ret_namelen && ret_name)
		*ret_namelen = s - *ret_name - 1; /* device length */
	if (ret_unit)
		*ret_unit = r_unit;
	s = index(s, '.') + 1;		/* start of resname */
	if (ret_resname)
		*ret_resname = s;
	s = index(s, '=') + 1;		/* start of value */
	if (ret_resnamelen && ret_resname)
		*ret_resnamelen = s - *ret_resname - 1; /* value len */
	if (ret_value)
		*ret_value = s;
	if (startln)			/* line number for anchor */
		*startln = *line + 1;
	return 0;
}
Пример #14
0
	QModelIndex FolderSelectionModel::mapFromSource(const QModelIndex &sourceIndex) const {
		return index(sourceIndex.row()+1, sourceIndex.column());
	}
Пример #15
0
 void updateLayerVisibility( const QString& layerId )
 {
   int row = mOrder.indexOf( layerId );
   if ( row != -1 )
     emit dataChanged( index( row ), index( row ) );
 }
Пример #16
0
int UrlRetrievalModel::match(int start, const QByteArray &role, const QVariant &value, int flags) const {
    const QModelIndexList idxs = match(index(start), m_roles.key(role), value, 1, Qt::MatchFlags(flags));
    return idxs.isEmpty() ? -1 : idxs.first().row();
}
CrystVector_long DiffractionDataSingleCrystal::SortReflectionBySinThetaOverLambda(const REAL maxSTOL)
{
   TAU_PROFILE("DiffractionDataSingleCrystal::SortReflectionBySinThetaOverLambda()","void ()",TAU_DEFAULT);
   VFN_DEBUG_ENTRY("DiffractionDataSingleCrystal::SortReflectionBySinThetaOverLambda()",5)
   // ScatteringData::SortReflectionBySinThetaOverLambda only sorts H,K,L and multiplicity.
   CrystVector_long index=this->ScatteringData::SortReflectionBySinThetaOverLambda(maxSTOL);

   if(mObsIntensity.numElements()==mNbRefl)
   {
      CrystVector_REAL tmpObs,tmpSigma,tmpWeight;
      tmpObs=mObsIntensity;
      tmpSigma=mObsSigma;
      tmpWeight=mWeight;
      for(long i=0;i<mNbRefl;i++)
      {
         mObsIntensity(i)=tmpObs(index(i));
         mObsSigma(i)=tmpSigma(index(i));
         mWeight(i)=tmpWeight(index(i));
      }
      // Keep a copy as squared F(hkl), to enable fourier maps
      // :TODO: stop using mObsIntensity and just keep mFhklObsSq ?
      mFhklObsSq=mObsIntensity;
      mClockFhklObsSq.Click();

      if(mGroupOption.GetChoice()==2)
      {
         CrystVector_long tmp;//,oldgroup(mNbGroup);;
         tmp=mGroupIndex;
         for(long i=0;i<mNbRefl;i++) mGroupIndex(i)=tmp(index(i));
         /*
         for(long i=0;i<mNbRefl;i++)
            cout<<mIntH(i)<<" "<<mIntK(i)<<" "<<mIntL(i)<<" "
                <<mObsIntensity(i)<<" "<<mObsSigma(i)<<" "<<mWeight(i)<< ":"<<mGroupIndex(i)<<endl;
         */
         // Now re-index the groups of reflections in
         // ascending order
         {
            index.resize(mNbGroup);
            index=-1;
            long group=0;
            CrystVector_REAL oldGroupIobs, oldGroupWeight,oldGroupSigma;
            oldGroupIobs  =mGroupIobs;
            oldGroupWeight=mGroupWeight;
            oldGroupSigma=mGroupSigma;
            for(long i=0;i<mNbRefl;i++)
            {
               if(index(mGroupIndex(i))==-1)// first reflection of a group ?
               {
                  mGroupIobs(group)=oldGroupIobs(mGroupIndex(i));
                  mGroupSigma(group)=oldGroupSigma(mGroupIndex(i));
                  mGroupWeight(group)=oldGroupWeight(mGroupIndex(i));
                  //oldgroup(group)=mGroupIndex(i);
                  index(mGroupIndex(i))=group++;
               }
               mGroupIndex(i)=index(mGroupIndex(i));
            }
         }
         /*
         cout<<mIntH.numElements()<<","
             <<mIntK.numElements()<<","
             <<mIntL.numElements()<<","
             <<oldgroup.numElements()<<","<<mGroupIndex.numElements()<<endl;
         for(long i=0;i<mNbRefl;i++)
            cout<<mIntH(i)<<" "<<mIntK(i)<<" "<<mIntL(i)<<endl
                <<"             :"<<oldgroup(mGroupIndex(i))<<"->"<<mGroupIndex(i)<<endl;
         */
         // Now re-group the reflections
         index=SortSubs(mGroupIndex);
         {
            CrystVector_long oldH,oldK,oldL,oldMult;
            oldH=mH;
            oldK=mK;
            oldL=mL;
            oldMult=mMultiplicity;
            tmpObs=mObsIntensity;
            tmpSigma=mObsSigma;
            tmpWeight=mWeight;
            for(long i=0;i<mNbRefl;i++)
            {
               const long subs=index(i);
               mH(i)=oldH(subs);
               mK(i)=oldK(subs);
               mL(i)=oldL(subs);
               mMultiplicity(i)=oldMult(subs);
               mObsIntensity(i)=tmpObs(subs);
               mObsSigma(i)=tmpSigma(subs);
               mWeight(i)=tmpWeight(subs);
            }
            mClockHKL.Click();
            this->PrepareHKLarrays();
            this->CalcSinThetaLambda();
         }

         // re-write mGroupIndex so that it marks the
         // last reflection of each group.
         index=mGroupIndex;
         mGroupIndex.resize(mNbGroup);
         long group=0;
         for(long i=0;i<mNbRefl;i++)
            if(index(i)!=group)
               mGroupIndex(group++)=i;
         mGroupIndex(mNbGroup-1)=mNbRefl;
      }
   }
   else
   {// if there are no observed values, enter dummy ones
      mObsIntensity.resize(mNbRefl);
      mObsSigma.resize(mNbRefl);
      mWeight.resize(mNbRefl);
      mObsIntensity=100.;
      mObsSigma=1.;
      mWeight=1.;
      mFhklObsSq.resize(0);
      mClockFhklObsSq.Click();
   }
   VFN_DEBUG_EXIT("DiffractionDataSingleCrystal::SortReflectionBySinThetaOverLambda()",5)
   return index;
}
Пример #18
0
ExampleSetModel::ExampleSetType ExampleSetModel::getType(int i) const
{
    if (i < 0 || i >= rowCount())
        return InvalidExampleSet;
    QModelIndex modelIndex = index(i, 0);
    QVariant variant = data(modelIndex, Qt::UserRole + 2); /*Qt version uniqueId*/
    if (variant.isValid())
        return QtExampleSet;
    return ExtraExampleSet;
}

int ExampleSetModel::getQtId(int i) const
{
    QTC_ASSERT(i >= 0, return -1);
    QModelIndex modelIndex = index(i, 0);
    QVariant variant = data(modelIndex, Qt::UserRole + 2);
    QTC_ASSERT(variant.isValid(), return -1);
    QTC_ASSERT(variant.canConvert<int>(), return -1);
    return variant.toInt();
}

int ExampleSetModel::getExtraExampleSetIndex(int i) const
{
    QTC_ASSERT(i >= 0, return -1);
    QModelIndex modelIndex = index(i, 0);
    QVariant variant = data(modelIndex, Qt::UserRole + 3);
    QTC_ASSERT(variant.isValid(), return -1);
    QTC_ASSERT(variant.canConvert<int>(), return -1);
    return variant.toInt();
}
Пример #19
0
/*
//  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
//  PURPOSE:  Processes messages for the main window.
*/
LRESULT CALLBACK MainWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	PNHMainWindow data;

	switch (message) 
	{
		case WM_CREATE:
			/* set window data */
			data = (PNHMainWindow)malloc(sizeof(NHMainWindow));
			if( !data ) panic("out of memory");
			ZeroMemory(data, sizeof(NHMainWindow));
			data->mapAcsiiModeSave = MAP_MODE_ASCII12x16;
			SetWindowLong(hWnd, GWL_USERDATA, (LONG)data);

			GetNHApp()->hMainWnd = hWnd;
		break;

		case WM_MSNH_COMMAND:
			onMSNHCommand(hWnd, wParam, lParam);
		break;

        case WM_KEYDOWN: 
		{
			data = (PNHMainWindow)GetWindowLong(hWnd, GWL_USERDATA);

			/* translate arrow keys into nethack commands */
            switch (wParam) 
            { 
			case VK_LEFT:
				if( STATEON(VK_CONTROL) ) {
					/* scroll map window one line left */
					SendMessage(
						mswin_hwnd_from_winid(WIN_MAP),
						WM_HSCROLL,
						MAKEWPARAM(SB_LINEUP, 0),
						(LPARAM)NULL
					);
				} else {
					NHEVENT_KBD(KEYTABLE(KEY_W));
				}
			return 0;

			case VK_RIGHT:
				if( STATEON(VK_CONTROL) ) {
					/* scroll map window one line right */
					SendMessage(
						mswin_hwnd_from_winid(WIN_MAP),
						WM_HSCROLL,
						MAKEWPARAM(SB_LINEDOWN, 0),
						(LPARAM)NULL
					);
				} else {
					NHEVENT_KBD(KEYTABLE(KEY_E));
				}
			return 0;

			case VK_UP:
				if( STATEON(VK_CONTROL) ) {
					/* scroll map window one line up */
					SendMessage(
						mswin_hwnd_from_winid(WIN_MAP),
						WM_VSCROLL,
						MAKEWPARAM(SB_LINEUP, 0),
						(LPARAM)NULL
					);
				} else {
					NHEVENT_KBD(KEYTABLE(KEY_N));
				}
			return 0;

			case VK_DOWN:
				if( STATEON(VK_CONTROL) ) {
					/* scroll map window one line down */
					SendMessage(
						mswin_hwnd_from_winid(WIN_MAP),
						WM_VSCROLL,
						MAKEWPARAM(SB_LINEDOWN, 0),
						(LPARAM)NULL
					);
				} else {
					NHEVENT_KBD(KEYTABLE(KEY_S));
				}
			return 0;

			case VK_HOME:
				if( STATEON(VK_CONTROL) ) {
					/* scroll map window to upper left corner */
					SendMessage(
						mswin_hwnd_from_winid(WIN_MAP),
						WM_VSCROLL,
						MAKEWPARAM(SB_THUMBTRACK, 0),
						(LPARAM)NULL
					);

					SendMessage(
						mswin_hwnd_from_winid(WIN_MAP),
						WM_HSCROLL,
						MAKEWPARAM(SB_THUMBTRACK, 0),
						(LPARAM)NULL
					);
				} else {
					NHEVENT_KBD(KEYTABLE(KEY_NW));
				}
			return 0;

			case VK_END:
				if( STATEON(VK_CONTROL) ) {
					/* scroll map window to lower right corner */
					SendMessage(
						mswin_hwnd_from_winid(WIN_MAP),
						WM_VSCROLL,
						MAKEWPARAM(SB_THUMBTRACK, ROWNO),
						(LPARAM)NULL
					);

					SendMessage(
						mswin_hwnd_from_winid(WIN_MAP),
						WM_HSCROLL,
						MAKEWPARAM(SB_THUMBTRACK, COLNO),
						(LPARAM)NULL
					);
				} else {
					NHEVENT_KBD(KEYTABLE(KEY_SW));
				}
			return 0;

			case VK_PRIOR:
				if( STATEON(VK_CONTROL) ) {
					/* scroll map window one page up */
					SendMessage(
						mswin_hwnd_from_winid(WIN_MAP),
						WM_VSCROLL,
						MAKEWPARAM(SB_PAGEUP, 0),
						(LPARAM)NULL
					);
				} else {
					NHEVENT_KBD(KEYTABLE(KEY_NE));
				}
			return 0;

			case VK_NEXT:
				if( STATEON(VK_CONTROL) ) {
					/* scroll map window one page down */
					SendMessage(
						mswin_hwnd_from_winid(WIN_MAP),
						WM_VSCROLL,
						MAKEWPARAM(SB_PAGEDOWN, 0),
						(LPARAM)NULL
					);
				} else {
					NHEVENT_KBD(KEYTABLE(KEY_SE));
				}
			return 0;

			case VK_DECIMAL:
			case VK_DELETE:
				NHEVENT_KBD(KEYTABLE(KEY_WAITLOOK));
			return 0;

			case VK_INSERT:
				NHEVENT_KBD(KEYTABLE(KEY_INV));
			return 0;

			case VK_SUBTRACT:
				NHEVENT_KBD(KEYTABLE(KEY_MINUS));
			return 0;

			case VK_ADD:
				NHEVENT_KBD(KEYTABLE(KEY_PLUS));
			return 0;

			case VK_CLEAR: /* This is the '5' key */
				NHEVENT_KBD(KEYTABLE(KEY_GOINTERESTING));
			return 0;

			case VK_F4:
				if( IS_MAP_FIT_TO_SCREEN(iflags.wc_map_mode) ) {
					mswin_select_map_mode(
						IS_MAP_ASCII(iflags.wc_map_mode)? 
							data->mapAcsiiModeSave :
							MAP_MODE_TILES
					);
				} else {
					mswin_select_map_mode(
						IS_MAP_ASCII(iflags.wc_map_mode)?
							MAP_MODE_ASCII_FIT_TO_SCREEN :
							MAP_MODE_TILES_FIT_TO_SCREEN
					);
				}
			return 0;

			case VK_F5:
				if( IS_MAP_ASCII(iflags.wc_map_mode) ) {
					if( IS_MAP_FIT_TO_SCREEN(iflags.wc_map_mode) ) {
						mswin_select_map_mode(MAP_MODE_TILES_FIT_TO_SCREEN);
					} else {
						mswin_select_map_mode(MAP_MODE_TILES);
					}
				} else {
					if( IS_MAP_FIT_TO_SCREEN(iflags.wc_map_mode) ) {
						mswin_select_map_mode(MAP_MODE_ASCII_FIT_TO_SCREEN);
					} else {
						mswin_select_map_mode(data->mapAcsiiModeSave);
					}
				}
			return 0;

			default: {
				WORD c;
				BYTE kbd_state[256];

				c = 0;
				ZeroMemory(kbd_state, sizeof(kbd_state));
				GetKeyboardState(kbd_state);

				if( ToAscii( wParam, (lParam>>16)&0xFF, kbd_state, &c, 0) ) {
					NHEVENT_KBD( c&0xFF );
					return 0;
				} else {
					return 1;
				}
			}

			} /* end switch */
		} break;

        case WM_SYSCHAR: /* Alt-char pressed */
        {
            /*
              If not nethackmode, don't handle Alt-keys here.
              If no Alt-key pressed it can never be an extended command 
            */
	    if (GetNHApp()->regNetHackMode && ((lParam & 1<<29) != 0))
            {
                unsigned char c = (unsigned char)(wParam & 0xFF);
		unsigned char scancode = (lParam >> 16) & 0xFF;
                if (index(extendedlist, tolower(c)) != 0)
		{
		    NHEVENT_KBD(M(tolower(c)));
		} else if (scancode == (SCANLO + SIZE(scanmap)) - 1) {
		    NHEVENT_KBD(M('?'));
		}
		return 0;
            }
            return DefWindowProc(hWnd, message, wParam, lParam);
        } 
Пример #20
0
QVariant ExampleSetModel::getDisplayName(int i) const
{
    if (i < 0 || i >= rowCount())
        return QVariant();
    return data(index(i, 0), Qt::UserRole + 1);
}
Пример #21
0
void AMSamplePlatePre2013ItemModel::onDatabaseItemRemoved(const QString &tableName, int id) {
	if(tableName != sampleTableName_)
		return;

	emit dataChanged(index(id), index(id));
}
Пример #22
0
int
main (int argc, char **argv)
{
  char *command_line = NULL;
  char input_buffer[MAX_INPUT_BUFFER];
  char *address = NULL; /* comma seperated str with addrs/ptrs (sorted) */
  char **addresses = NULL;
  int n_addresses = 0;
  char *msg = NULL;
  char *temp_buffer = NULL;
  int non_authoritative = FALSE;
  int result = STATE_UNKNOWN;
  double elapsed_time;
  long microsec;
  struct timeval tv;
  int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
  output chld_out, chld_err;
  size_t i;

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  /* Set signal handling and alarm */
  if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) {
    usage_va(_("Cannot catch SIGALRM"));
  }

  /* Parse extra opts if any */
  argv=np_extra_opts (&argc, argv, progname);

  if (process_arguments (argc, argv) == ERROR) {
    usage_va(_("Could not parse arguments"));
  }

  /* get the command to run */
  xasprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);

  alarm (timeout_interval);
  gettimeofday (&tv, NULL);

  if (verbose)
    printf ("%s\n", command_line);

  /* run the command */
  if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
    msg = (char *)_("nslookup returned an error status");
    result = STATE_WARNING;
  }

  /* scan stdout */
  for(i = 0; i < chld_out.lines; i++) {
    if (addresses == NULL)
      addresses = malloc(sizeof(*addresses)*10);
    else if (!(n_addresses % 10))
      addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10));

    if (verbose)
      puts(chld_out.line[i]);

    if (strcasestr (chld_out.line[i], ".in-addr.arpa")) {
      if ((temp_buffer = strstr (chld_out.line[i], "name = ")))
        addresses[n_addresses++] = strdup (temp_buffer + 7);
      else {
        msg = (char *)_("Warning plugin error");
        result = STATE_WARNING;
      }
    }

    /* bug ID: 2946553 - Older versions of bind will use all available dns 
                         servers, we have to match the one specified */
    if (strstr (chld_out.line[i], "Server:") && strlen(dns_server) > 0) {
      temp_buffer = strchr (chld_out.line[i], ':');
      temp_buffer++;

      /* Strip leading tabs */
      for (; *temp_buffer != '\0' && *temp_buffer == '\t'; temp_buffer++)
        /* NOOP */;

      strip(temp_buffer);
      if (temp_buffer==NULL || strlen(temp_buffer)==0) {
        die (STATE_CRITICAL,
             _("DNS CRITICAL - '%s' returned empty server string\n"),
             NSLOOKUP_COMMAND);
      }

      if (strcmp(temp_buffer, dns_server) != 0) {
        die (STATE_CRITICAL, _("DNS CRITICAL - No response from DNS %s\n"), dns_server);
      }
    }

    /* the server is responding, we just got the host name... */
    if (strstr (chld_out.line[i], "Name:"))
      parse_address = TRUE;
    else if (parse_address == TRUE && (strstr (chld_out.line[i], "Address:") ||
             strstr (chld_out.line[i], "Addresses:"))) {
      temp_buffer = index (chld_out.line[i], ':');
      temp_buffer++;

      /* Strip leading spaces */
      for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
        /* NOOP */;

      strip(temp_buffer);
      if (temp_buffer==NULL || strlen(temp_buffer)==0) {
        die (STATE_CRITICAL,
             _("DNS CRITICAL - '%s' returned empty host name string\n"),
             NSLOOKUP_COMMAND);
      }

      addresses[n_addresses++] = strdup(temp_buffer);
    }
    else if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) {
      non_authoritative = TRUE;
    }


    result = error_scan (chld_out.line[i]);
    if (result != STATE_OK) {
      msg = strchr (chld_out.line[i], ':');
      if(msg) msg++;
      break;
    }
  }

  /* scan stderr */
  for(i = 0; i < chld_err.lines; i++) {
    if (verbose)
      puts(chld_err.line[i]);

    if (error_scan (chld_err.line[i]) != STATE_OK) {
      result = max_state (result, error_scan (chld_err.line[i]));
      msg = strchr(input_buffer, ':');
      if(msg) msg++;
    }
  }

  if (addresses) {
    int i,slen;
    char *adrp;
    qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp);
    for(i=0, slen=1; i < n_addresses; i++) {
      slen += strlen(addresses[i])+1;
    }
    adrp = address = malloc(slen);
    for(i=0; i < n_addresses; i++) {
      if (i) *adrp++ = ',';
      strcpy(adrp, addresses[i]);
      adrp += strlen(addresses[i]);
    }
    *adrp = 0;
  } else
    die (STATE_CRITICAL,
         _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
         NSLOOKUP_COMMAND);

  /* compare to expected address */
  if (result == STATE_OK && expected_address_cnt > 0) {
    result = STATE_CRITICAL;
    temp_buffer = "";
    for (i=0; i<expected_address_cnt; i++) {
      /* check if we get a match and prepare an error string */
      if (strcmp(address, expected_address[i]) == 0) result = STATE_OK;
      xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
    }
    if (result == STATE_CRITICAL) {
      /* Strip off last semicolon... */
      temp_buffer[strlen(temp_buffer)-2] = '\0';
      xasprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
    }
  }

  /* check if authoritative */
  if (result == STATE_OK && expect_authority && non_authoritative) {
    result = STATE_CRITICAL;
    xasprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
  }

  microsec = deltime (tv);
  elapsed_time = (double)microsec / 1.0e6;

  if (result == STATE_OK) {
    result = get_status(elapsed_time, time_thresholds);
    if (result == STATE_OK) {
      printf ("DNS %s: ", _("OK"));
    } else if (result == STATE_WARNING) {
      printf ("DNS %s: ", _("WARNING"));
    } else if (result == STATE_CRITICAL) {
      printf ("DNS %s: ", _("CRITICAL"));
    }
    printf (ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
    printf (_(". %s returns %s"), query_address, address);
    if ((time_thresholds->warning != NULL) && (time_thresholds->critical != NULL)) {
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s",
                                  TRUE, time_thresholds->warning->end,
                                  TRUE, time_thresholds->critical->end,
                                  TRUE, 0, FALSE, 0));
    } else if ((time_thresholds->warning == NULL) && (time_thresholds->critical != NULL)) {
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s",
                                  FALSE, 0,
                                  TRUE, time_thresholds->critical->end,
                                  TRUE, 0, FALSE, 0));
    } else if ((time_thresholds->warning != NULL) && (time_thresholds->critical == NULL)) {
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s",
                                  TRUE, time_thresholds->warning->end,
                                  FALSE, 0,
                                  TRUE, 0, FALSE, 0));
    } else
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
  }
  else if (result == STATE_WARNING)
    printf (_("DNS WARNING - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else if (result == STATE_CRITICAL)
    printf (_("DNS CRITICAL - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else
    printf (_("DNS UNKNOWN - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);

  return result;
}
Пример #23
0
void BookmarksModel::entryChanged(BookmarkNode *item)
{
    QModelIndex idx = index(item);
    emit dataChanged(idx, idx);
}
Пример #24
0
int comm_rank_from_coords(const Topology *topo, const int *coords)
{
  return topo->ranks[index(topo->ndim, topo->dims, coords)];
}
Пример #25
0
int internal__hydra_connect(char *host, int port, int protocol, int type) {
  int s, ret = -1, ipv6 = 0;

#ifdef AF_INET6
  struct sockaddr_in6 target6;
  struct sockaddr_in6 sin6;
#endif
  struct sockaddr_in target;
  struct sockaddr_in sin;
  char *buf, *tmpptr = NULL;
  int err = 0;

#ifdef AF_INET6
  memset(&target6, 0, sizeof(target6));
  memset(&sin6, 0, sizeof(sin6));
  if ((host[0] == 16 && proxy_string_ip[0] != 4) || proxy_string_ip[0] == 16)
    ipv6 = 1;
#endif

#ifdef AF_INET6
  if (ipv6)
    s = socket(AF_INET6, protocol, type);
  else
#endif
    s = socket(PF_INET, protocol, type);
  if (s >= 0) {
    if (src_port != 0) {
      int bind_ok = 0;

#ifdef AF_INET6
      if (ipv6) {
        sin6.sin6_family = AF_INET6;
        sin6.sin6_port = htons(src_port);
      } else
#endif
      {
        sin.sin_family = PF_INET;
        sin.sin_port = htons(src_port);
        sin.sin_addr.s_addr = INADDR_ANY;
      }

      //we will try to find a free port down to 512
      while (!bind_ok && src_port >= 512) {
#ifdef AF_INET6
        if (ipv6)
          ret = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
        else
#endif
          ret = bind(s, (struct sockaddr *) &sin, sizeof(sin));

        if (ret == -1) {
          if (verbose)
            perror("internal_hydra_connect error");
          if (errno == EADDRINUSE) {
            src_port--;
#ifdef AF_INET6
            if (ipv6)
              sin6.sin6_port = htons(src_port);
            else
#endif
              sin.sin_port = htons(src_port);
          } else {
            if (errno == EACCES && (getuid() > 0)) {
              fprintf(stderr, "[ERROR] You need to be root to test this service\n");
              close(s);
              return -1;
            }
          }
        } else
          bind_ok = 1;
      }
    }
    if (use_proxy > 0) {
      if (proxy_string_ip[0] == 4) {
        memcpy(&target.sin_addr.s_addr, &proxy_string_ip[1], 4);
        target.sin_family = AF_INET;
        target.sin_port = htons(proxy_string_port);
      }
#ifdef AF_INET6
      if (proxy_string_ip[0] == 16) {
        memcpy(&target6.sin6_addr, &proxy_string_ip[1], 16);
        target6.sin6_family = AF_INET6;
        target6.sin6_port = htons(proxy_string_port);
      }
#endif
    } else {
      if (host[0] == 4) {
        memcpy(&target.sin_addr.s_addr, &host[1], 4);
        target.sin_family = AF_INET;
        target.sin_port = htons(port);
      }
#ifdef AF_INET6
      if (host[0] == 16) {
        memcpy(&target6.sin6_addr, &host[1], 16);
        target6.sin6_family = AF_INET6;
        target6.sin6_port = htons(port);
      }
#endif
    }
    signal(SIGALRM, alarming);
    do {
      if (fail > 0)
        sleep(WAIT_BETWEEN_CONNECT_RETRY);
      alarm_went_off = 0;
      alarm(waittime);
#ifdef AF_INET6
#ifdef SO_BINDTODEVICE
      if (host[17] != 0) {
        setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, &host[17], strlen(&host[17]) + 1);
      }
#else
#ifdef IP_FORCE_OUT_IFP
      if (host[17] != 0) {
        setsockopt(s, SOL_SOCKET, IP_FORCE_OUT_IFP, &host[17], strlen(&host[17]) + 1);
      }
#endif
#endif

      if (ipv6)
        ret = connect(s, (struct sockaddr *) &target6, sizeof(target6));
      else
#endif
        ret = connect(s, (struct sockaddr *) &target, sizeof(target));
      alarm(0);
      if (ret < 0 && alarm_went_off == 0) {
        fail++;
        if (verbose ) {
          if (do_retry && fail <= MAX_CONNECT_RETRY)
            fprintf(stderr, "Process %d: Can not connect [unreachable], retrying (%d of %d retries)\n", (int) getpid(), fail, MAX_CONNECT_RETRY);
          else
            fprintf(stderr, "Process %d: Can not connect [unreachable]\n", (int) getpid());
        }
      }
    } while (ret < 0 && fail <= MAX_CONNECT_RETRY && do_retry);
    if (ret < 0 && fail > MAX_CONNECT_RETRY) {
      if (debug)
        printf("DEBUG_CONNECT_UNREACHABLE\n");

/* we wont quit here, thats up to the module to decide what to do 
 *              fprintf(stderr, "Process %d: Can not connect [unreachable], process exiting\n", (int)getpid());
 *              hydra_child_exit(1);
 */
      extern_socket = -1;
      close(s);
      ret = -1;
      return ret;
    }
    ret = s;
    extern_socket = s;
    if (debug)
      printf("DEBUG_CONNECT_OK\n");

    err = 0;
    if (use_proxy == 2) {
      if ((buf = malloc(4096)) == NULL) {
        fprintf(stderr, "[ERROR] could not malloc()\n");
        close(s);
        return -1;
      }
      memset(&target, 0, sizeof(target));
      if (host[0] == 4) {
        memcpy(&target.sin_addr.s_addr, &host[1], 4);
        target.sin_family = AF_INET;
        target.sin_port = htons(port);
      }
#ifdef AF_INET6
      memset(&target6, 0, sizeof(target6));
      if (host[0] == 16) {
        memcpy(&target6.sin6_addr, &host[1], 16);
        target6.sin6_family = AF_INET6;
        target6.sin6_port = htons(port);
      }
#endif

      if (hydra_strcasestr(proxy_string_type, "connect") || hydra_strcasestr(proxy_string_type, "http")) {
        if (proxy_authentication == NULL)
          if (host[0] == 16)
            snprintf(buf, 4096, "CONNECT [%s]:%d HTTP/1.0\r\n\r\n", hydra_address2string(host), port);
          else
            snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\n\r\n", hydra_address2string(host), port);
        else if (host[0] == 16)
          snprintf(buf, 4096, "CONNECT [%s]:%d HTTP/1.0\r\nProxy-Authorization: Basic %s\r\n\r\n", hydra_address2string(host), port, proxy_authentication);
        else
          snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\nProxy-Authorization: Basic %s\r\n\r\n", hydra_address2string(host), port, proxy_authentication);

        send(s, buf, strlen(buf), 0);
        recv(s, buf, 4096, 0);
        if (strncmp("HTTP/", buf, 5) == 0 && (tmpptr = index(buf, ' ')) != NULL && *++tmpptr == '2') {
          if (debug)
            printf("DEBUG_CONNECT_PROXY_OK\n");
        } else {
          if (debug)
            printf("DEBUG_CONNECT_PROXY_FAILED (Code: %c%c%c)\n", *tmpptr, *(tmpptr + 1), *(tmpptr + 2));
          if (verbose)
            fprintf(stderr, "[ERROR] CONNECT call to proxy failed with code %c%c%c\n", *tmpptr, *(tmpptr + 1), *(tmpptr + 2));
          err = 1;
        }
//        free(buf);
      } else {
        if (hydra_strcasestr(proxy_string_type, "socks5")) {
//          char buf[1024];
          size_t cnt, wlen;

          /* socks v5 support */
          buf[0] = SOCKS_V5;
          buf[1] = 1;
          if (proxy_authentication == NULL)
            buf[2] = SOCKS_NOAUTH;
          else
            buf[2] = SOCKS_PASSAUTH;
          cnt = hydra_send(s, buf, 3, 0);
          if (cnt != 3) {
            hydra_report(stderr, "[ERROR] SOCKS5 proxy write failed (%zu/3)\n", cnt);
            err = 1;
          } else {
            cnt = hydra_recv(s, buf, 2);
            if (cnt != 2) {
              hydra_report(stderr, "[ERROR] SOCKS5 proxy read failed (%zu/2)\n", cnt);
              err = 1;
            }
            if ((unsigned int) buf[1] == SOCKS_NOMETHOD) {
              hydra_report(stderr, "[ERROR] SOCKS5 proxy authentication method negotiation failed\n");
              err = 1;
            }
            /* SOCKS_DOMAIN not supported here, do we need it ? */
            if (err != 1) {
              /* send user/pass */
              if (proxy_authentication != NULL) {
                //format was checked previously
                char *login = strtok(proxy_authentication, ":");
                char *pass = strtok(NULL, ":");

                snprintf(buf, sizeof(buf), "\x01%c%s%c%s", (char) strlen(login), login, (char) strlen(pass), pass);

                cnt = hydra_send(s, buf, strlen(buf), 0);
                if (cnt != strlen(buf)) {
                  hydra_report(stderr, "[ERROR] SOCKS5 proxy write failed (%zu/3)\n", cnt);
                  err = 1;
                } else {
                  cnt = hydra_recv(s, buf, 2);
                  if (cnt != 2) {
                    hydra_report(stderr, "[ERROR] SOCKS5 proxy read failed (%zu/2)\n", cnt);
                    err = 1;
                  }
                  if (buf[1] != 0) {
                    hydra_report(stderr, "[ERROR] SOCKS5 proxy authentication failure\n");
                    err = 1;
                  } else {
                    if (debug)
                      hydra_report(stderr, "[DEBUG] SOCKS5 proxy authentication success\n");
                  }
                }
              }
#ifdef AF_INET6
              if (ipv6) {
                /* Version 5, connect: IPv6 address */
                buf[0] = SOCKS_V5;
                buf[1] = SOCKS_CONNECT;
                buf[2] = 0;
                buf[3] = SOCKS_IPV6;
                memcpy(buf + 4, &target6.sin6_addr, sizeof target6.sin6_addr);
                memcpy(buf + 20, &target6.sin6_port, sizeof target6.sin6_port);
                wlen = 22;
              } else {
#endif
                /* Version 5, connect: IPv4 address */
                buf[0] = SOCKS_V5;
                buf[1] = SOCKS_CONNECT;
                buf[2] = 0;
                buf[3] = SOCKS_IPV4;
                memcpy(buf + 4, &target.sin_addr, sizeof target.sin_addr);
                memcpy(buf + 8, &target.sin_port, sizeof target.sin_port);
                wlen = 10;
#ifdef AF_INET6
              }
#endif
              cnt = hydra_send(s, buf, wlen, 0);
              if (cnt != wlen) {
                hydra_report(stderr, "[ERROR] SOCKS5 proxy write failed (%zu/%zu)\n", cnt, wlen);
                err = 1;
              } else {
                cnt = hydra_recv(s, buf, 10);
                if (cnt != 10) {
                  hydra_report(stderr, "[ERROR] SOCKS5 proxy read failed (%zu/10)\n", cnt);
                  err = 1;
                }
                if (buf[1] != 0) {
                  /* 0x05 = connection refused by destination host */
                  if (buf[1] == 5)
                    hydra_report(stderr, "[ERROR] SOCKS proxy request failed\n");
                  else
                    hydra_report(stderr, "[ERROR] SOCKS error %d\n", buf[1]);
                  err = 1;
                }
              }
            }
          }
        } else {
          if (hydra_strcasestr(proxy_string_type, "socks4")) {
            if (ipv6) {
              hydra_report(stderr, "[ERROR] SOCKS4 proxy does not support IPv6\n");
              err = 1;
            } else {
//              char buf[1024];
              size_t cnt, wlen;

              /* socks v4 support */
              buf[0] = SOCKS_V4;
              buf[1] = SOCKS_CONNECT;   /* connect */
              memcpy(buf + 2, &target.sin_port, sizeof target.sin_port);
              memcpy(buf + 4, &target.sin_addr, sizeof target.sin_addr);
              buf[8] = 0;       /* empty username */
              wlen = 9;
              cnt = hydra_send(s, buf, wlen, 0);
              if (cnt != wlen) {
                hydra_report(stderr, "[ERROR] SOCKS4 proxy write failed (%zu/%zu)\n", cnt, wlen);
                err = 1;
              } else {
                cnt = hydra_recv(s, buf, 8);
                if (cnt != 8) {
                  hydra_report(stderr, "[ERROR] SOCKS4 proxy read failed (%zu/8)\n", cnt);
                  err = 1;
                }
                if (buf[1] != 90) {
                  /* 91 = 0x5b = request rejected or failed */
                  if (buf[1] == 91)
                    hydra_report(stderr, "[ERROR] SOCKS proxy request failed\n");
                  else
                    hydra_report(stderr, "[ERROR] SOCKS error %d\n", buf[1]);
                  err = 1;
                }
              }
            }
          } else {
            hydra_report(stderr, "[ERROR] Unknown proxy type: %s, valid type are \"connect\", \"socks4\" or \"socks5\"\n", proxy_string_type);
            err = 1;
          }
        }
      }
      free(buf);
    }
    if (err) {
      close(s);
      extern_socket = -1;
      ret = -1;
      return ret;
    }
    fail = 0;
    return ret;
  }
  return ret;
}
Пример #26
0
void build_request(const char *url)
{
  char tmp[10];
  int i;

  bzero(host,MAXHOSTNAMELEN);
  bzero(request,REQUEST_SIZE);

  if(force_reload && proxyhost!=NULL && http10<1) http10=1;
  if(method==METHOD_HEAD && http10<1) http10=1;
  if(method==METHOD_OPTIONS && http10<2) http10=2;
  if(method==METHOD_TRACE && http10<2) http10=2;

  switch(method)
  {
	  default:
	  case METHOD_GET: strcpy(request,"GET");break;
	  case METHOD_HEAD: strcpy(request,"HEAD");break;
	  case METHOD_OPTIONS: strcpy(request,"OPTIONS");break;
	  case METHOD_TRACE: strcpy(request,"TRACE");break;
  }
		  
  strcat(request," ");

  if(NULL==strstr(url,"://"))
  {
	  fprintf(stderr, "\n%s: is not a valid URL.\n",url);
	  exit(2);
  }
  if(strlen(url)>1500)
  {
         fprintf(stderr,"URL is too long.\n");
	 exit(2);
  }
  if(proxyhost==NULL)
	   if (0!=strncasecmp("http://",url,7)) 
	   { fprintf(stderr,"\nOnly HTTP protocol is directly supported, set --proxy for others.\n");
             exit(2);
           }
  /* protocol/host delimiter */
  i=strstr(url,"://")-url+3;
  /* printf("%d\n",i); */

  if(strchr(url+i,'/')==NULL) {
                                fprintf(stderr,"\nInvalid URL syntax - hostname don't ends with '/'.\n");
                                exit(2);
                              }
  if(proxyhost==NULL)
  {
   /* get port from hostname */
   if(index(url+i,':')!=NULL &&
      index(url+i,':')<index(url+i,'/'))
   {
	   strncpy(host,url+i,strchr(url+i,':')-url-i);
	   bzero(tmp,10);
	   strncpy(tmp,index(url+i,':')+1,strchr(url+i,'/')-index(url+i,':')-1);
	   /* printf("tmp=%s\n",tmp); */
	   proxyport=atoi(tmp);
	   if(proxyport==0) proxyport=80;
   } else
   {
     strncpy(host,url+i,strcspn(url+i,"/"));
   }
   // printf("Host=%s\n",host);
   strcat(request+strlen(request),url+i+strcspn(url+i,"/"));
  } else
  {
   // printf("ProxyHost=%s\nProxyPort=%d\n",proxyhost,proxyport);
   strcat(request,url);
  }
  if(http10==1)
	  strcat(request," HTTP/1.0");
  else if (http10==2)
	  strcat(request," HTTP/1.1");
  strcat(request,"\r\n");
  if(http10>0)
	  strcat(request,"User-Agent: WebBench "PROGRAM_VERSION"\r\n");
  if(proxyhost==NULL && http10>0)
  {
	  strcat(request,"Host: ");
	  strcat(request,host);
	  strcat(request,"\r\n");
  }
  if(force_reload && proxyhost!=NULL)
  {
	  strcat(request,"Pragma: no-cache\r\n");
  }
  if(http10>1)
	  strcat(request,"Connection: close\r\n");
  /* add empty line at end */
  if(http10>0) strcat(request,"\r\n"); 
  // printf("Req=%s\n",request);
}
Пример #27
0
static char *
XkbRF_SubstituteVars(char *name, XkbRF_MultiDefsPtr mdefs)
{
char 	*str, *outstr, *orig, *var;
int	len, ndx;

    orig= name;
    str= index(name,'%');
    if (str==NULL)
	return name;
    len= strlen(name);
    while (str!=NULL) {
	char pfx= str[1];
	int   extra_len= 0;
	if ((pfx=='+')||(pfx=='|')||(pfx=='_')||(pfx=='-')) {
	    extra_len= 1;
	    str++;
	}
	else if (pfx=='(') {
	    extra_len= 2;
	    str++;
	}
	var = str + 1;
	str = get_index(var + 1, &ndx);
	if (ndx == -1) {
	    str = index(str,'%');
	    continue;
        }
	if ((*var=='l') && mdefs->layout[ndx] && *mdefs->layout[ndx])
	    len+= strlen(mdefs->layout[ndx])+extra_len;
	else if ((*var=='m')&&mdefs->model)
	    len+= strlen(mdefs->model)+extra_len;
	else if ((*var=='v') && mdefs->variant[ndx] && *mdefs->variant[ndx])
	    len+= strlen(mdefs->variant[ndx])+extra_len;
	if ((pfx=='(')&&(*str==')')) {
	    str++;
	}
	str= index(&str[0],'%');
    }
    name= (char *)_XkbAlloc(len+1);
    str= orig;
    outstr= name;
    while (*str!='\0') {
	if (str[0]=='%') {
	    char pfx,sfx;
	    str++;
	    pfx= str[0];
	    sfx= '\0';
	    if ((pfx=='+')||(pfx=='|')||(pfx=='_')||(pfx=='-')) {
		str++;
	    }
	    else if (pfx=='(') {
		sfx= ')';
		str++;
	    }
	    else pfx= '\0';

	    var = str;
	    str = get_index(var + 1, &ndx);
	    if (ndx == -1) {
	        continue;
            }
	    if ((*var=='l') && mdefs->layout[ndx] && *mdefs->layout[ndx]) {
		if (pfx) *outstr++= pfx;
		strcpy(outstr,mdefs->layout[ndx]);
		outstr+= strlen(mdefs->layout[ndx]);
		if (sfx) *outstr++= sfx;
	    }
	    else if ((*var=='m')&&(mdefs->model)) {
		if (pfx) *outstr++= pfx;
		strcpy(outstr,mdefs->model);
		outstr+= strlen(mdefs->model);
		if (sfx) *outstr++= sfx;
	    }
	    else if ((*var=='v') && mdefs->variant[ndx] && *mdefs->variant[ndx]) {
		if (pfx) *outstr++= pfx;
		strcpy(outstr,mdefs->variant[ndx]);
		outstr+= strlen(mdefs->variant[ndx]);
		if (sfx) *outstr++= sfx;
	    }
	    if ((pfx=='(')&&(*str==')'))
		str++;
	}
	else {
	    *outstr++= *str++;
	}
    }
    *outstr++= '\0';
    if (orig!=name)
	_XkbFree(orig);
    return name;
}
Пример #28
0
void
__gnat_localtime_tzoff (const time_t *timer, const int *is_historic, long *off)
{
    struct tm tp;

    /* AIX, HPUX, Sun Solaris */
#if defined (_AIX) || defined (__hpux__) || defined (sun)
    {
        (*Lock_Task) ();

        localtime_r (timer, &tp);
        *off = (long) -timezone;

        (*Unlock_Task) ();

        /* Correct the offset if Daylight Saving Time is in effect */

        if (tp.tm_isdst > 0)
            *off = *off + 3600;
    }

    /* VxWorks */
#elif defined (__vxworks)
#include <stdlib.h>
    {
        (*Lock_Task) ();

        localtime_r (timer, &tp);

        /* Try to read the environment variable TIMEZONE. The variable may not have
           been initialize, in that case return an offset of zero (0) for UTC. */

        char *tz_str = getenv ("TIMEZONE");

        if ((tz_str == NULL) || (*tz_str == '\0'))
            *off = 0;
        else
        {
            char *tz_start, *tz_end;

            /* The format of the data contained in TIMEZONE is N::U:S:E where N is the
               name of the time zone, U are the minutes difference from UTC, S is the
               start of DST in mmddhh and E is the end of DST in mmddhh. Extracting
               the value of U involves setting two pointers, one at the beginning and
               one at the end of the value. The end pointer is then set to null in
               order to delimit a string slice for atol to process. */

            tz_start = index (tz_str, ':') + 2;
            tz_end = index (tz_start, ':');
            tz_end = '\0';

            /* The Ada layer expects an offset in seconds. Note that we must reverse
               the sign of the result since west is positive and east is negative on
               VxWorks targets. */

            *off = -atol (tz_start) * 60;

            /* Correct the offset if Daylight Saving Time is in effect */

            if (tp.tm_isdst > 0)
                *off = *off + 3600;
        }

        (*Unlock_Task) ();
    }

    /* Darwin, Free BSD, Linux, where component tm_gmtoff is present in
       struct tm */

#elif defined (__APPLE__) \
  || defined (__DragonFly__) \
  || defined (__FreeBSD__) \
  || defined (__OpenBSD__) \
  || defined (linux) \
  || defined (__GLIBC__)
    {
        localtime_r (timer, &tp);
        *off = tp.tm_gmtoff;
    }

    /* Default: treat all time values in GMT */

#else
    *off = 0;

#endif
}
Пример #29
0
int
main (int argc, char** argv)
{
  int k = 6;

  double thresh = DBL_MAX;     // No threshold, disabled by default

  if (argc < 2)
  {
    pcl::console::print_error 
      ("Need at least three parameters! Syntax is: %s <query_vfh_model.pcd> [options] {kdtree.idx} {training_data.h5} {training_data.list}\n", argv[0]);
    pcl::console::print_info ("    where [options] are:  -k      = number of nearest neighbors to search for in the tree (default: "); 
    pcl::console::print_value ("%d", k); pcl::console::print_info (")\n");
    pcl::console::print_info ("                          -thresh = maximum distance threshold for a model to be considered VALID (default: "); 
    pcl::console::print_value ("%f", thresh); pcl::console::print_info (")\n\n");
    return (-1);
  }

  // this won't be needed for flann > 1.6.10
  flann::ObjectFactory<flann::IndexParams, flann_algorithm_t>::instance().register_<flann::LinearIndexParams>(FLANN_INDEX_LINEAR);

  std::string extension (".pcd");
  transform (extension.begin (), extension.end (), extension.begin (), (int(*)(int))tolower);

  // Load the test histogram
  std::vector<int> pcd_indices = pcl::console::parse_file_extension_argument (argc, argv, ".pcd");
  vfh_model histogram;
  if (!loadHist (argv[pcd_indices.at (0)], histogram))
  {
    pcl::console::print_error ("Cannot load test file %s\n", argv[pcd_indices.at (0)]);
    return (-1);
  }

  pcl::console::parse_argument (argc, argv, "-thresh", thresh);
  // Search for the k closest matches
  pcl::console::parse_argument (argc, argv, "-k", k);
  pcl::console::print_highlight ("Using "); pcl::console::print_value ("%d", k); pcl::console::print_info (" nearest neighbors.\n");

  std::string kdtree_idx_file_name = "kdtree.idx";
  std::string training_data_h5_file_name = "training_data.h5";
  std::string training_data_list_file_name = "training_data.list";

  std::vector<vfh_model> models;
  flann::Matrix<int> k_indices;
  flann::Matrix<float> k_distances;
  flann::Matrix<float> data;
  // Check if the data has already been saved to disk
  if (!boost::filesystem::exists ("training_data.h5") || !boost::filesystem::exists ("training_data.list"))
  {
    pcl::console::print_error ("Could not find training data models files %s and %s!\n", 
        training_data_h5_file_name.c_str (), training_data_list_file_name.c_str ());
    return (-1);
  }
  else
  {
    loadFileList (models, training_data_list_file_name);
    flann::load_from_file (data, training_data_h5_file_name, "training_data");
    pcl::console::print_highlight ("Training data found. Loaded %d VFH models from %s/%s.\n", 
        (int)data.rows, training_data_h5_file_name.c_str (), training_data_list_file_name.c_str ());
  }

  // Check if the tree index has already been saved to disk
  if (!boost::filesystem::exists (kdtree_idx_file_name))
  {
    pcl::console::print_error ("Could not find kd-tree index in file %s!", kdtree_idx_file_name.c_str ());
    return (-1);
  }
  else
  {
    flann::Index<flann::ChiSquareDistance<float> > index (data, flann::SavedIndexParams ("kdtree.idx"));
    index.buildIndex ();
    nearestKSearch (index, histogram, k, k_indices, k_distances);
  }

  // Output the results on screen
  pcl::console::print_highlight ("The closest %d neighbors for %s are:\n", k, argv[pcd_indices[0]]);
  for (int i = 0; i < k; ++i)
    pcl::console::print_info ("    %d - %s (%d) with a distance of: %f\n", 
        i, models.at (k_indices[0][i]).first.c_str (), k_indices[0][i], k_distances[0][i]);

  // Load the results
  pcl::visualization::PCLVisualizer p (argc, argv, "VFH Cluster Classifier");
  int y_s = (int)floor (sqrt ((double)k));
  int x_s = y_s + (int)ceil ((k / (double)y_s) - y_s);
  double x_step = (double)(1 / (double)x_s);
  double y_step = (double)(1 / (double)y_s);
  pcl::console::print_highlight ("Preparing to load "); 
  pcl::console::print_value ("%d", k); 
  pcl::console::print_info (" files ("); 
  pcl::console::print_value ("%d", x_s);    
  pcl::console::print_info ("x"); 
  pcl::console::print_value ("%d", y_s); 
  pcl::console::print_info (" / ");
  pcl::console::print_value ("%f", x_step); 
  pcl::console::print_info ("x"); 
  pcl::console::print_value ("%f", y_step); 
  pcl::console::print_info (")\n");

  int viewport = 0, l = 0, m = 0;
  for (int i = 0; i < k; ++i)
  {
    std::string cloud_name = models.at (k_indices[0][i]).first;
    boost::replace_last (cloud_name, "_vfh", "");

    p.createViewPort (l * x_step, m * y_step, (l + 1) * x_step, (m + 1) * y_step, viewport);
    l++;
    if (l >= x_s)
    {
      l = 0;
      m++;
    }

    sensor_msgs::PointCloud2 cloud;
    pcl::console::print_highlight (stderr, "Loading "); pcl::console::print_value (stderr, "%s ", cloud_name.c_str ());
    if (pcl::io::loadPCDFile (cloud_name, cloud) == -1)
      break;

    // Convert from blob to PointCloud
    pcl::PointCloud<pcl::PointXYZ> cloud_xyz;
    pcl::fromROSMsg (cloud, cloud_xyz);

    if (cloud_xyz.points.size () == 0)
      break;

    pcl::console::print_info ("[done, "); 
    pcl::console::print_value ("%d", (int)cloud_xyz.points.size ()); 
    pcl::console::print_info (" points]\n");
    pcl::console::print_info ("Available dimensions: "); 
    pcl::console::print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());

    // Demean the cloud
    Eigen::Vector4f centroid;
    pcl::compute3DCentroid (cloud_xyz, centroid);
    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz_demean (new pcl::PointCloud<pcl::PointXYZ>);
    pcl::demeanPointCloud<pcl::PointXYZ> (cloud_xyz, centroid, *cloud_xyz_demean);
    // Add to renderer*
    p.addPointCloud (cloud_xyz_demean, cloud_name, viewport);
    
    // Check if the model found is within our inlier tolerance
    std::stringstream ss;
    ss << k_distances[0][i];
    if (k_distances[0][i] > thresh)
    {
      p.addText (ss.str (), 20, 30, 1, 0, 0, ss.str (), viewport);  // display the text with red

      // Create a red line
      pcl::PointXYZ min_p, max_p;
      pcl::getMinMax3D (*cloud_xyz_demean, min_p, max_p);
      std::stringstream line_name;
      line_name << "line_" << i;
      p.addLine (min_p, max_p, 1, 0, 0, line_name.str (), viewport);
      p.setShapeRenderingProperties (pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 5, line_name.str (), viewport);
    }
    else
      p.addText (ss.str (), 20, 30, 0, 1, 0, ss.str (), viewport);

    // Increase the font size for the score*
    p.setShapeRenderingProperties (pcl::visualization::PCL_VISUALIZER_FONT_SIZE, 18, ss.str (), viewport);

    // Add the cluster name
    p.addText (cloud_name, 20, 10, cloud_name, viewport);
  }
  // Add coordianate systems to all viewports
  p.addCoordinateSystem (0.1, 0);

  p.spin ();
  return (0);
}
Пример #30
0
/*
 * Give our OK for a hook to be added. The hook name is of the
 * form "<family>/<type>/<proto>" where the three components may
 * be decimal numbers or else aliases from the above lists.
 *
 * Connecting a hook amounts to opening the socket.  Disconnecting
 * the hook closes the socket and destroys the node as well.
 */
static int
ng_ksocket_newhook(node_p node, hook_p hook, const char *name0)
{
	struct thread *td = curthread->td_proc ? curthread : &thread0;	/* XXX broken */
	const priv_p priv = NG_NODE_PRIVATE(node);
	char *s1, *s2, name[NG_HOOKSIZ];
	int family, type, protocol, error;

	/* Check if we're already connected */
	if (priv->hook != NULL)
		return (EISCONN);

	if (priv->flags & KSF_CLONED) {
		if (priv->flags & KSF_EMBRYONIC) {
			/* Remove ourselves from our parent's embryo list */
			LIST_REMOVE(priv, siblings);
			priv->flags &= ~KSF_EMBRYONIC;
		}
	} else {
		/* Extract family, type, and protocol from hook name */
		ksnprintf(name, sizeof(name), "%s", name0);
		s1 = name;
		if ((s2 = index(s1, '/')) == NULL)
			return (EINVAL);
		*s2++ = '\0';
		family = ng_ksocket_parse(ng_ksocket_families, s1, 0);
		if (family == -1)
			return (EINVAL);
		s1 = s2;
		if ((s2 = index(s1, '/')) == NULL)
			return (EINVAL);
		*s2++ = '\0';
		type = ng_ksocket_parse(ng_ksocket_types, s1, 0);
		if (type == -1)
			return (EINVAL);
		s1 = s2;
		protocol = ng_ksocket_parse(ng_ksocket_protos, s1, family);
		if (protocol == -1)
			return (EINVAL);

		/* Create the socket */
		error = socreate(family, &priv->so, type, protocol, td);
		if (error != 0)
			return (error);

		/* XXX call soreserve() ? */

	}

	/* OK */
	priv->hook = hook;

	/*
	 * In case of misconfigured routing a packet may reenter
	 * ksocket node recursively. Decouple stack to avoid possible
	 * panics about sleeping with locks held.
	 */
	NG_HOOK_FORCE_QUEUE(hook);

	return(0);
}