Beispiel #1
0
int main(int argc, char **argv){
	t01_test_mime();
	
	END();
}
Beispiel #2
0
LOCAL MACRO* initMacros(char* macro)
{
    MACRO* head;
    MACRO* cur;
    int    i;
    char   mc_name[9];
    char   mc_value[20];

    head= NULL;

    if(!macro) return NULL;
    if(END(macro)) return NULL;

    do {
        while(!END(macro) && (*macro==' ')) macro++;
        if(END(macro)) return head;

        i= 0;
        while(!END(macro) && (*macro!=' ') && (*macro!='=') && (i<8))
            mc_name[i++]= *(macro++);
        if(END(macro)) return head;
        while(!END(macro) && (*macro!='=')) macro++;
        mc_name[i]= '\0';
        macro++;

        while(!END(macro) && (*macro==' ')) macro++;
        if(END(macro)) return head;

        i= 0;
        while(!END(macro) && (*macro!=' ')  && (*macro!=',') && (i<19))
            mc_value[i++]= *(macro++);
        mc_value[i]= '\0';

        cur= (MACRO*) malloc(sizeof(MACRO));
        if(!cur) return head;

        strcpy(cur->name, mc_name);
        strcpy(cur->value, mc_value);
        cur->nxt= head;
        head= cur;

        while(!END(macro) && (*macro!=',')) macro++;
    } while(!END(macro) && (*(macro++)==','));
    return head;
}
/** Returns status of ticket by filling 'buf' with a NetID if the ticket
 *  is valid and buf is large enough and returning 1.  If not, 0 is
 *  returned.
 */
int cas_validate(
    char *ticket, char *service, char *outbuf, int outbuflen, pam_cas_config_t *config)
{
  int b, ret, total;
  SSL_CTX *ctx = NULL;
  BIO * bio = NULL;
  SSL *ssl = NULL;
  char buf[4096];
  char *full_request = NULL, *str;
  char netid[CAS_LEN_NETID];
  char parsebuf[128];

  debug = config->debug;

  if (config->ssl)
  {
    DEBUG_LOG("We use SSL as configured\n", "");
    /* Set up the SSL library */
    ERR_load_BIO_strings();
    SSL_load_error_strings();
    OpenSSL_add_all_algorithms();
#if defined(OpenSSL_add_ssl_algorithms)
    OpenSSL_add_ssl_algorithms();
#endif

    /* Set up the SSL context */
    ctx = SSL_CTX_new(SSLv23_client_method());
    if ( ! ctx ) 
    {
      DEBUG_LOG("Cannot create SSL context", "");
      END(CAS_SSL_ERROR_INIT);
    }

    /* Load the trust store */
    if(! SSL_CTX_load_verify_locations(ctx, config->trusted_ca, NULL))
    {
      DEBUG_LOG("Error loading certificate store : %s\n", ERR_reason_error_string(ERR_get_error()));
      END(CAS_SSL_ERROR_CERT_LOAD);
    }

    /* Setup the connection */
    bio = BIO_new_ssl_connect(ctx);

    /* Set the SSL_MODE_AUTO_RETRY flag :
       if the server suddenly wants a new handshake, OpenSSL handles it in the background */
    BIO_get_ssl(bio, & ssl);
    SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);

    /* Create and setup the connection */
    DEBUG_LOG("We connect to host %s\n", config->host);
    BIO_set_conn_hostname(bio, config->host);
    BIO_set_conn_port(bio, config->port);
    if(BIO_do_connect(bio) <= 0)
    {
      DEBUG_LOG("Error attempting to connect : %s\n", ERR_reason_error_string(ERR_get_error()));
      END(CAS_SSL_ERROR_CONN);
    }

    /* Check the certificate */
    if (SSL_get_verify_result(ssl) != X509_V_OK)
    {
      DEBUG_LOG("Certificate verification error: %ld\n", SSL_get_verify_result(ssl));
      END(CAS_SSL_ERROR_CERT_VALID);
    }
  }
  else  /* no ssl */
  {    
    bio = BIO_new_connect(config->host);
    BIO_set_conn_port(bio, config->port);
    if(BIO_do_connect(bio) <= 0)
    {
      DEBUG_LOG("Error attempting to connect : %s\n", config->host);
      END(CAS_ERROR_CONN);
    }
  }

  /* build request */
  full_request = malloc(strlen(CAS_METHOD) + strlen(" ")
    + strlen(config->uriValidate) + strlen("?ticket=") + strlen(ticket) + 
    + strlen("&service=") + strlen(service) + strlen(" ") 
    + strlen(GENERIC_HEADERS) + strlen ("\r\n")
#ifdef HEADER_HOST_NAME
    + strlen(HEADER_HOST_NAME) + strlen (": ") + strlen (config->host)
#endif
    + strlen("\r\n\r\n") + 1);
  if (full_request == NULL)
  {
      DEBUG_LOG("Error memory allocation%s\n", "");
      END(CAS_ERROR_MEMORY_ALLOC);
  }
#ifdef HEADER_HOST_NAME
  sprintf(full_request, "%s %s?ticket=%s&service=%s %s\r\n%s: %s\r\n\r\n",
	  CAS_METHOD, config->uriValidate, ticket, service, GENERIC_HEADERS,
          HEADER_HOST_NAME,config->host);
#else
  sprintf(full_request, "%s %s?ticket=%s&service=%s %s\r\n\r\n",
	  CAS_METHOD, config->uriValidate, ticket, service, GENERIC_HEADERS);
#endif

  /* send request */
  DEBUG_LOG("---- request :\n%s\n", full_request);
  if (BIO_write(bio, full_request, strlen(full_request)) != strlen(full_request))
  {
    DEBUG_LOG("Unable to correctly send request to %s\n", config->host);
    END(CAS_ERROR_HTTP);
  }

  /* Read the response */
  total = 0;
  b = 0;
  do 
  {
    b = BIO_read(bio, buf + total, (sizeof(buf) - 1) - total);
    total += b;
  } while (b > 0);
  buf[total] = '\0';

  if (b != 0 || total >= sizeof(buf) - 1)
  {
    DEBUG_LOG("Unexpected read error or response too large from %s\n", config->host);
    DEBUG_LOG("b = %d\n", b);
    DEBUG_LOG("total = %d\n", total);
    DEBUG_LOG("buf = %s\n", buf);
    END(CAS_ERROR_HTTP);		// unexpected read error or response too large
  }

  DEBUG_LOG("---- response :\n%s\n", buf);
  str = (char *)strstr(buf, "\r\n\r\n");  // find the end of the header

  if (!str)
  {
    DEBUG_LOG("no header in response%s\n", "");
    END(CAS_ERROR_HTTP);			  // no header
  }

  /*
   * 'str' now points to the beginning of the body, which should be an
   * XML document
   */

  // make sure that the authentication succeeded
  
  if (!element_body(
    str, "cas:authenticationSuccess", 1, parsebuf, sizeof(parsebuf))) {
    END(CAS_BAD_TICKET);
  }

  // retrieve the NetID
  if (!element_body(str, "cas:user", 1, netid, sizeof(netid))) {
    DEBUG_LOG("unable to determine username%s\n", "");
    END(CAS_PROTOCOL_FAILURE);
  }


  // check the first proxy (if present)
  if ((config->proxies) && (config->proxies[0]))
    if (element_body(str, "cas:proxies", 1, parsebuf, sizeof(parsebuf)))
      if (element_body(str, "cas:proxy", 1, parsebuf, sizeof(parsebuf)))
        if (!arrayContains(config->proxies, parsebuf)) {
          DEBUG_LOG("bad proxy: %s\n", parsebuf);
          END(CAS_BAD_PROXY);
        }

  /*
   * without enough space, fail entirely, since a partial NetID could
   * be dangerous
   */
  if (outbuflen < strlen(netid) + 1) 
  {
    syslog(LOG_ERR, "output buffer too short");
    DEBUG_LOG("output buffer too short%s\n", "");
    END(CAS_PROTOCOL_FAILURE);
  }

  strcpy(outbuf, netid);
  SUCCEED;

   /* cleanup and return */

end:
  if (ctx)
    SSL_CTX_free(ctx);
  if (bio)
    BIO_free_all(bio);
  if (full_request)
    free(full_request);
  return ret;
}
Beispiel #4
0
inline int OutputDebugStringF(const char* pszFormat, ...)
{
    int ret = 0;
    if (fPrintToConsole)
    {
        // print to console
        va_list arg_ptr;
        va_start(arg_ptr, pszFormat);
        ret = vprintf(pszFormat, arg_ptr);
        va_end(arg_ptr);
    }
    else
    {
        // print to debug.log
        static FILE* fileout = NULL;

        if (!fileout)
        {
            char pszFile[MAX_PATH+100];
            GetDataDir(pszFile);
            strlcat(pszFile, "/debug.log", sizeof(pszFile));
            fileout = fopen(pszFile, "a");
            if (fileout) setbuf(fileout, NULL); // unbuffered
        }
        if (fileout)
        {
            static bool fStartedNewLine = true;

            // Debug print useful for profiling
            if (fLogTimestamps && fStartedNewLine)
                fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
            if (pszFormat[strlen(pszFormat) - 1] == '\n')
                fStartedNewLine = true;
            else
                fStartedNewLine = false;

            va_list arg_ptr;
            va_start(arg_ptr, pszFormat);
            ret = vfprintf(fileout, pszFormat, arg_ptr);
            va_end(arg_ptr);
        }
    }

#ifdef __WXMSW__
    if (fPrintToDebugger)
    {
        static CCriticalSection cs_OutputDebugStringF;

        // accumulate a line at a time
        CRITICAL_BLOCK(cs_OutputDebugStringF)
        {
            static char pszBuffer[50000];
            static char* pend;
            if (pend == NULL)
                pend = pszBuffer;
            va_list arg_ptr;
            va_start(arg_ptr, pszFormat);
            int limit = END(pszBuffer) - pend - 2;
            int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
            va_end(arg_ptr);
            if (ret < 0 || ret >= limit)
            {
                pend = END(pszBuffer) - 2;
                *pend++ = '\n';
            }
            else
                pend += ret;
            *pend = '\0';
            char* p1 = pszBuffer;
            char* p2;
            while (p2 = strchr(p1, '\n'))
            {
                p2++;
                char c = *p2;
                *p2 = '\0';
                OutputDebugStringA(p1);
                *p2 = c;
                p1 = p2;
            }
            if (p1 != pszBuffer)
                memmove(pszBuffer, p1, pend - p1 + 1);
            pend -= (p1 - pszBuffer);
        }
    }
#endif
    return ret;
}
Beispiel #5
0
uint256 CBlock::BuildMerkleTree(bool* fMutated) const
{
    /* WARNING! If you're reading this because you're learning about crypto
       and/or designing a new system that will use merkle trees, keep in mind
       that the following merkle tree algorithm has a serious flaw related to
       duplicate txids, resulting in a vulnerability (CVE-2012-2459).

       The reason is that if the number of hashes in the list at a given time
       is odd, the last one is duplicated before computing the next level (which
       is unusual in Merkle trees). This results in certain sequences of
       transactions leading to the same merkle root. For example, these two
       trees:

                    A               A
                  /  \            /   \
                B     C         B       C
               / \    |        / \     / \
              D   E   F       D   E   F   F
             / \ / \ / \     / \ / \ / \ / \
             1 2 3 4 5 6     1 2 3 4 5 6 5 6

       for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
       6 are repeated) result in the same root hash A (because the hash of both
       of (F) and (F,F) is C).

       The vulnerability results from being able to send a block with such a
       transaction list, with the same merkle root, and the same block hash as
       the original without duplication, resulting in failed validation. If the
       receiving node proceeds to mark that block as permanently invalid
       however, it will fail to accept further unmodified (and thus potentially
       valid) versions of the same block. We defend against this by detecting
       the case where we would hash two identical hashes at the end of the list
       together, and treating that identically to the block having an invalid
       merkle root. Assuming no double-SHA256 collisions, this will detect all
       known ways of changing the transactions without affecting the merkle
       root.
    */
    vMerkleTree.clear();
    vMerkleTree.reserve(vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.
    for (std::vector<CTransaction>::const_iterator it(vtx.begin()); it != vtx.end(); ++it)
        vMerkleTree.push_back(it->GetHash());
    int j = 0;
    bool mutated = false;
    for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
    {
        for (int i = 0; i < nSize; i += 2)
        {
            int i2 = std::min(i+1, nSize-1);
            if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) {
                // Two identical hashes at the end of the list at a particular level.
                mutated = true;
            }
            vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
                                       BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
        }
        j += nSize;
    }
    if (fMutated) {
        *fMutated = mutated;
    }
    return (vMerkleTree.empty() ? uint256() : vMerkleTree.back());
}
/* Test assumptions in su_select_port implementation */
int test_select(void)
{
  su_socket_t s;
  su_sockaddr_t su;
  socklen_t sulen = sizeof su.su_sin;
  size_t bytes;
  fd_set *rset, *wset;
  struct timeval tv;

  BEGIN();

  s = su_socket(AF_INET, SOCK_DGRAM, 0); TEST_1(s != -1);

  memset(&su, 0, sulen);
  su.su_len = sulen;
  su.su_family = AF_INET;
  TEST(su_inet_pton(AF_INET, "127.0.0.1", &su.su_sin.sin_addr), 1);
  TEST(bind(s, &su.su_sa, sulen), 0);
  TEST(getsockname(s, &su.su_sa, &sulen), 0);

  tv.tv_sec = 0; tv.tv_usec = 1000;
  TEST(select(0, NULL, NULL, NULL, &tv), 0);

  bytes = howmany(s);
  TEST_1(rset = malloc(bytes));
  TEST_1(wset = malloc(bytes));

  FD_ZERO_TO(s, rset); FD_ZERO_TO(s, wset); FD_SET(s, wset);
  tv.tv_sec = 0, tv.tv_usec = 1000;
  TEST(select(s + 1, NULL, wset, NULL, &tv), 1);
  TEST_1(FD_ISSET(s, wset));

  FD_ZERO_TO(s, rset); FD_ZERO_TO(s, wset);
  FD_SET(s, rset); FD_SET(s, wset);
  tv.tv_sec = 0, tv.tv_usec = 1000;
  TEST(select(s + 1, rset, wset, NULL, &tv), 1);
  TEST_1(!FD_ISSET(s, rset));
  TEST_1(FD_ISSET(s, wset));

  FD_ZERO_TO(s, rset); FD_ZERO_TO(s, wset);
  FD_SET(s, rset); FD_SET(s, wset);
  tv.tv_sec = 0, tv.tv_usec = 1000;
  TEST(select(s + 1, rset, NULL, NULL, &tv), 0);
  TEST_1(!FD_ISSET(s, rset));

  FD_ZERO_TO(s, rset); FD_ZERO_TO(s, wset);
  FD_SET(s, rset); FD_CLR(s, wset);
  tv.tv_sec = 0, tv.tv_usec = 1000;
  TEST(select(s + 1, rset, wset, NULL, &tv), 0);
  TEST_1(!FD_ISSET(s, rset));
  TEST_1(!FD_ISSET(s, wset));

  TEST(su_sendto(s, "foo", 3, 0, &su, sulen), 3);

  FD_ZERO_TO(s, rset); FD_ZERO_TO(s, wset);
  FD_SET(s, rset); FD_CLR(s, wset);
  tv.tv_sec = 0, tv.tv_usec = 1000;
  TEST(select(s + 1, rset, wset, NULL, &tv), 1);
  TEST_1(FD_ISSET(s, rset));
  TEST_1(!FD_ISSET(s, wset));

  FD_ZERO_TO(s, rset); FD_ZERO_TO(s, wset);
  FD_SET(s, rset); FD_SET(s, wset);
  tv.tv_sec = 0, tv.tv_usec = 1000;
  TEST(select(s + 1, rset, wset, NULL, &tv), 2);
  TEST_1(FD_ISSET(s, rset));
  TEST_1(FD_ISSET(s, wset));

  su_close(s);

  free(wset);
  free(rset);

  END();
}
static int test_sockaddr(void)
{
  su_localinfo_t hints[1] = {{ LI_CANONNAME }};
  su_localinfo_t *li, *res = NULL;
  int s;
  su_sockaddr_t  su[1], a[1], b[1];

  BEGIN();

  hints->li_family = AF_INET;

  TEST(su_getlocalinfo(hints, &res), 0);

  for (li = res; li; li = li->li_next) {
    if (li->li_addrlen != res->li_addrlen ||
	memcmp(li->li_addr, res->li_addr, li->li_addrlen) != 0)
      TEST_1(su_cmp_sockaddr(li->li_addr, res->li_addr) != 0);
    else
      TEST_1(su_cmp_sockaddr(li->li_addr, res->li_addr) == 0);
  }

  memset(su, 0, sizeof su);
  TEST(su_getlocalip(su), 0);

  if (res->li_family == AF_INET)
    TEST(su_cmp_sockaddr(res->li_addr, su), 0);

  TEST_1(su_gli_strerror(ELI_NOERROR));
  TEST_1(su_gli_strerror(ELI_NOADDRESS));
  TEST_1(su_gli_strerror(ELI_FAMILY));
  TEST_1(su_gli_strerror(ELI_MEMORY));
  TEST_1(su_gli_strerror(ELI_RESOLVER));
  TEST_1(su_gli_strerror(ELI_SYSTEM));
  TEST_1(su_gli_strerror(-100));

  li = su_copylocalinfo(res); TEST_1(li);
  su_freelocalinfo(li);

  s = su_socket(res->li_family, SOCK_DGRAM, 0); TEST_1(s != -1);
  TEST(su_setblocking(s, 0), 0);
  TEST(su_setblocking(s, 1), 0);
  TEST(su_close(s), 0);

  su_freelocalinfo(res), res = NULL;

#if SU_HAVE_IN6
  hints->li_family = AF_INET6;
  hints->li_flags &= ~LI_CANONNAME;
  hints->li_flags |= LI_V4MAPPED;

  TEST(su_getlocalinfo(hints, &res), 0);
  for (li = res; li; li = li->li_next)
    TEST(li->li_family, AF_INET6);

  su_freelocalinfo(res), res = NULL;
#endif

  hints->li_flags |= LI_NUMERIC;
  TEST(su_getlocalinfo(hints, &res), 0);
  su_freelocalinfo(res), res = NULL;

  res = NULL;
  hints->li_flags |= LI_NAMEREQD;
  su_getlocalinfo(hints, &res);
  su_freelocalinfo(res), res = NULL;

  memset(a, 0, sizeof *a);
  memset(b, 0, sizeof *b);

  TEST_1(su_match_sockaddr(a, b));
  b->su_family = AF_INET;
  TEST_1(su_match_sockaddr(a, b));
  a->su_port = htons(12);
  TEST_1(!su_match_sockaddr(a, b));
  b->su_port = htons(12);
  TEST_1(su_match_sockaddr(a, b));
  a->su_sin.sin_addr.s_addr = htonl(0x7f000001);
  TEST_1(su_match_sockaddr(a, b));
  a->su_family = AF_INET;
  TEST_1(!su_match_sockaddr(a, b));
  b->su_sin.sin_addr.s_addr = htonl(0x7f000001);
  TEST_1(su_match_sockaddr(a, b));
  a->su_sin.sin_addr.s_addr = 0;
  TEST_1(su_match_sockaddr(a, b));
#if SU_HAVE_IN6
  a->su_family = AF_INET6;
  TEST_1(!su_match_sockaddr(a, b));
  b->su_family = AF_INET6;
  TEST_1(su_match_sockaddr(a, b));
  b->su_sin6.sin6_addr.s6_addr[15] = 1;
  TEST_1(su_match_sockaddr(a, b));
  TEST_1(!su_match_sockaddr(b, a));
  a->su_sin6.sin6_addr.s6_addr[15] = 2;
  TEST_1(!su_match_sockaddr(a, b));
  a->su_family = 0;
  TEST_1(su_match_sockaddr(a, b));
  TEST_1(!su_match_sockaddr(b, a));
#endif
  END();
}
Beispiel #8
0
int test_sip(void)
{
  /* sip urls */
  su_home_t home[1] = { SU_HOME_INIT(home) };
  url_t sip[1] = { URL_INIT_AS(sip) };
  url_t *u, url[1];
  char *tst, *s;
  char sipurl0[] =
    "sip:pekka%2Epessi@nokia%2Ecom;method=%4D%45%53%53%41%47%45"
    "?body=CANNED%20MSG";
  char sipurl[] =
    "sip:user:pass@host:32;param=1"
    "?From=foo@bar&To=bar@baz#unf";
  char sip2url[] =
    "sip:user/path;tel-param:pass@host:32;param=1%3d%3d1"
    "?From=foo@bar&body=CANNED%20MSG&To=bar@baz#unf";
  char sip2[sizeof(sipurl) + 32];
  char sipsurl[] =
    "sips:user:pass@host:32;param=1"
    "?From=foo@bar&To=bar@baz#unf";
  size_t i, j;
  url_t *a, *b;

  BEGIN();

  TEST_S(url_scheme(url_sip), "sip");
  TEST_S(url_scheme(url_sips), "sips");

  memset(url, 255, sizeof url);

  TEST(url_d(url, sipurl0), 0);

  TEST(url->url_type, url_sip);
  TEST(url->url_root, 0);
  TEST_S(url->url_scheme, "sip");
  TEST_S(url->url_user, "pekka.pessi");
  TEST_P(url->url_password, NULL);
  TEST_S(url->url_host, "nokia.com");
  TEST_P(url->url_port, NULL);
  TEST_P(url->url_path, NULL);
  TEST_S(url->url_params, "method=MESSAGE");
  TEST_S(url->url_headers, "body=CANNED%20MSG");
  TEST_P(url->url_fragment, NULL);

  TEST_S(url_query_as_header_string(home, url->url_headers),
	 "\n\nCANNED MSG");

  sip->url_user = "******";
  sip->url_password = "******";
  sip->url_host = "host";
  sip->url_port = "32";
  sip->url_params = "param=1";
  sip->url_headers = "From=foo@bar&To=bar@baz";
  sip->url_fragment = "unf";

  memset(url, 255, sizeof url);

  TEST_1(tst = su_strdup(home, sipurl));
  TEST_1(url_d(url, tst) == 0);
  TEST_1(url_cmp(sip, url) == 0);
  TEST(url->url_type, url_sip);
  TEST_1(u = url_hdup(home, url));
  TEST(u->url_type, url_sip);
  TEST_1(url_cmp(sip, u) == 0);
  TEST(url_e(sip2, sizeof(sip2), u), strlen(sipurl));
  TEST_1(strcmp(sip2, sipurl) == 0);
  TEST_SIZE(snprintf(sip2, sizeof(sip2), URL_PRINT_FORMAT,
		     URL_PRINT_ARGS(sip)), strlen(sipurl));
  TEST_1(strcmp(sip2, sipurl) == 0);

  url_digest(hash1, sizeof(hash1), url, NULL);
  url_digest(hash2, sizeof(hash2), (url_t const *)sipurl, NULL);
  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);

  TEST_1(tst = su_strdup(home, sip2url));
  TEST_1(url_d(url, tst) == 0);
  TEST_S(url->url_user, "user/path;tel-param");
  TEST_S(url->url_params, "param=1%3D%3D1");

  TEST_S(url_query_as_header_string(home, url->url_headers),
	 "From:foo@bar\nTo:bar@baz\n\nCANNED MSG");

  url_digest(hash1, sizeof(hash1), url, NULL);
  url_digest(hash2, sizeof(hash2), (url_t *)sip2url, NULL);
  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);

  sip->url_type = url_sips; sip->url_scheme = "sips";

  TEST_1(tst = su_strdup(home, sipsurl));
  TEST_1(url_d(url, tst) == 0);
  TEST_1(url_cmp(sip, url) == 0);
  TEST(url->url_type, url_sips);

  /* Test url_dup() */
  for (i = 0; i <= sizeof(sipsurl); i++) {
    char buf[sizeof(sipsurl) + 1];
    url_t dst[1];

    buf[i] = '\377';
    TEST_SIZE(url_dup(buf, i, dst, url), sizeof(sipsurl) - 1 - strlen("sips"));
    TEST(buf[i], '\377');
  }

  url_digest(hash1, sizeof(hash1), url, NULL);
  url_digest(hash2, sizeof(hash2), (url_t *)sipsurl, NULL);
  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);

  u = url_hdup(home, (url_t*)"SIP:[email protected]:55"); TEST_1(u);
  TEST(u->url_type, url_sip);

  u = url_hdup(home, (url_t*)"SIP:[email protected]:"); TEST_1(u);
  TEST(u->url_type, url_sip);

  TEST_P(url_hdup(home, (url_t*)"sip:[email protected]::55"), NULL);
  TEST_P(url_hdup(home, (url_t*)"sip:[email protected]:55:"), NULL);
  TEST_P(url_hdup(home, (url_t*)"sip:[email protected]:sip"), NULL);

  u = url_hdup(home, (url_t*)"SIP:#**00**#;foo=/[email protected]"); TEST_1(u);
  TEST(u->url_type, url_sip);
  TEST_S(u->url_user, "#**00**#;foo=/bar");

  TEST_1(!url_hdup(home, (url_t*)"SIP:#**00**#;foo=/bar@#127.0.0.1"));
  TEST_1(!url_hdup(home, (url_t*)"SIP:#**00**#;foo=/bar;127.0.0.1"));

  for (i = 32; i <= 256; i++) {
    char pu[512];
    char param[512];

    for (j = 0; j < i; j++)
      param[j] = 'x';
    param[j] = '\0';
    memcpy(param, "x=", 2);

    snprintf(pu, sizeof(pu), "sip:test@host;%s", param);
    u = url_hdup(home, (url_t*)pu); TEST_1(u);
    s = url_as_string(home, u);
    TEST_S(pu, s);
  }

  s = su_strdup(home, "ttl;transport=tcp;ttl=15;ttl=;method=INVITE;ttl");
  TEST_1(s);
  s = url_strip_param_string(s, "ttl");
  TEST_S(s, "transport=tcp;method=INVITE");

  u = url_hdup(home, (void*)"sip:u:p@host:5060;maddr=127.0.0.1;transport=tcp");
  TEST_1(u);
  TEST_1(url_have_transport(u));
  TEST_1(url_strip_transport(u));
  TEST_P(u->url_params, NULL);
  TEST_1(!url_have_transport(u));

  u = url_hdup(home, (void*)"sip:u:p@host:5060;user=phone;ttl=1;isfocus");
  TEST_1(u);
  TEST_1(url_have_transport(u));
  TEST_1(url_strip_transport(u));
  TEST_S(u->url_params, "user=phone;isfocus");
  TEST_1(!url_have_transport(u));

  u = url_hdup(home, (void*)"sip:u:p@host:5060;maddr=127.0.0.1;user=phone");
  TEST_1(u);
  TEST_1(url_have_transport(u));
  TEST_1(url_strip_transport(u));
  TEST_S(u->url_params, "user=phone");
  TEST_1(!url_have_transport(u));

  u = url_hdup(home, (void*)"sip:u:p@host:5060;user=phone;transport=tcp");
  TEST_1(u);
  TEST_1(url_have_transport(u));
  TEST_1(url_strip_transport(u));
  TEST_S(u->url_params, "user=phone");
  TEST_1(!url_have_transport(u));

  u = url_hdup(home, (void*)"sip:u:p@host;user=phone;;");
  TEST_1(u);
  /* We don't have transport params */
  TEST_1(!url_have_transport(u));
  /* ...but we still strip empty params */
  TEST_1(url_strip_transport(u));
  TEST_S(u->url_params, "user=phone");
  TEST_1(!url_have_transport(u));

  u = url_hdup(home, (void*)"sip:u:p@host:5060;ttl=1;isfocus;transport=udp;");
  TEST_1(u);
  TEST_1(url_have_transport(u));
  TEST_1(url_strip_transport(u));
  TEST_S(u->url_params, "isfocus");
  TEST_1(!url_have_transport(u));

  u = url_hdup(home, (void *)"sip:%22foo%[email protected]:5060");
  TEST_1(u);
  TEST_S(u->url_user, "%22foo%22");

  a = url_hdup(home, (void *)"sip:172.21.55.55:5060");
  b = url_hdup(home, (void *)"sip:172.21.55.55");
  TEST_1(a); TEST_1(b);
  TEST_1(url_cmp(a, b) == 0);
  TEST(url_cmp_all(a, b), 0);

  a = url_hdup(home, (void *)"sips:172.21.55.55:5060");
  b = url_hdup(home, (void *)"sips:172.21.55.55");
  TEST_1(a); TEST_1(b);
  TEST_1(url_cmp(a, b) != 0);
  TEST_1(url_cmp_all(a, b) < 0);

  a = url_hdup(home, (void *)"sips:172.21.55.55:5061");
  b = url_hdup(home, (void *)"sips:172.21.55.55");
  TEST_1(a); TEST_1(b);
  TEST_1(url_cmp(a, b) == 0);
  TEST(url_cmp_all(a, b), 0);

  a = url_hdup(home, (void *)"sip:my.domain:5060");
  b = url_hdup(home, (void *)"sip:my.domain");
  TEST_1(a); TEST_1(b);
  TEST_1(url_cmp(a, b) > 0);
  TEST_1(url_cmp_all(a, b) > 0);

  a = url_hdup(home, (void *)"sips:my.domain:5061");
  b = url_hdup(home, (void *)"sips:my.domain");
  TEST_1(a); TEST_1(b);
  TEST_1(url_cmp(a, b) > 0);
  TEST_1(url_cmp_all(a, b) > 0);

  a = url_hdup(home, (void *)"sip:my.domain");
  b = url_hdup(home, (void *)"SIP:MY.DOMAIN");
  TEST_1(a); TEST_1(b);
  TEST_1(url_cmp(a, b) == 0);
  TEST_1(url_cmp_all(a, b) == 0);

  su_home_deinit(home);

  END();
}
Beispiel #9
0
/* test unquoting and canonizing */
int test_quote(void)
{
  su_home_t home[1] = { SU_HOME_INIT(home) };
  url_t *u;
  char s[] = "%73ip:q%74est%01:%01%02%00@host%2enokia.com;%70aram=%01%02";
  char c[] = "sip:qtest%01:%01%02%[email protected];param=%01%02";
  char *d;

#define RESERVED        ";/?:@&=+$,"
#define DELIMS          "<>#%\""
#define UNWISE		"{}|\\^[]`"
#define EXCLUDED	RESERVED DELIMS UNWISE

  char escaped[1 + 3 * 23 + 1];

#define UNRESERVED    "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
                      "abcdefghijklmnopqrstuvwxyz" \
                      "0123456789" \
                      "-_.!~*'()"

  char unreserved[26 + 26 + 10 + 9 + 1];

  BEGIN();

  d = url_as_string(home, (url_t *)"sip:[email protected]");
  TEST_S(d, "sip:[email protected]");

  TEST(strlen(EXCLUDED), 23);
  TEST(strlen(UNRESERVED), 71);

  TEST_1(!url_reserved_p("foo"));
  TEST_1(!url_reserved_p(""));
  TEST_1(url_reserved_p("foobar:bar"));

  TEST_SIZE(url_esclen("a" EXCLUDED, ""),
	    1 + strlen(RESERVED) + 3 * strlen(DELIMS UNWISE));
  TEST_SIZE(url_esclen("a" EXCLUDED, DELIMS UNWISE),
	    1 + strlen(RESERVED) + 3 * strlen(DELIMS UNWISE));
  TEST_SIZE(url_esclen("a" EXCLUDED, EXCLUDED), 1 + 3 * strlen(EXCLUDED));
  TEST_SIZE(url_esclen("a" EXCLUDED, NULL), 1 + 3 * strlen(EXCLUDED));

  TEST_S(url_escape(escaped, "a" EXCLUDED, NULL),
	 "a%3B%2F%3F%3A%40%26%3D%2B%24%2C"
	 "%3C%3E%23%25%22"
	 "%7B%7D%7C%5C%5E%5B%5D%60");
  TEST_S(url_unescape(escaped, escaped), "a" EXCLUDED);

  TEST_SIZE(url_esclen(UNRESERVED, NULL), strlen(UNRESERVED));
  TEST_S(url_escape(unreserved, UNRESERVED, NULL), UNRESERVED);
  TEST_S(url_unescape(unreserved, UNRESERVED), UNRESERVED);

  d = "%53ip:%75@%48";		/* Sip:u@H */
  u = url_hdup(home, (url_t *)d); TEST_1(u);
  url_digest(hash1, sizeof(hash1), u, NULL);
  url_digest(hash2, sizeof(hash2), (url_t const *)d, NULL);
  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);

  d = "sip:u@h";
  u = url_hdup(home, (url_t *)d); TEST_1(u);
  url_digest(hash1, sizeof(hash1), u, NULL);
  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);
  url_digest(hash2, sizeof(hash2), (url_t const *)d, NULL);
  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);

  u = url_hdup(home, (url_t *)s); TEST_1(u);
  d = url_as_string(home, u); TEST_1(d);
  TEST_S(d, c);

  d = "sip:&=+$,;?/:&=+$,@[::1]:56001;param=+$,/:@&;another=@%40%2F"
    "?header=" RESERVED "&%3b%2f%3f%3a%40%26%3d%2b%24%2c";
  u = url_hdup(home, (url_t *)d); TEST_1(u);
  TEST_S(u->url_user, "&=+$,;?/");
  TEST_S(u->url_host, "[::1]");
  TEST_S(u->url_params, "param=+$,/:@&;another=@%40/");
  TEST_S(u->url_headers, "header=" RESERVED "&%3B%2F%3F%3A%40%26%3D%2B%24%2C");
  url_digest(hash1, sizeof(hash1), u, NULL);
  url_digest(hash2, sizeof(hash2), (url_t const *)d, NULL);
  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);

  u = url_hdup(home, (url_t *)s); TEST_1(u);
  d = url_as_string(home, u); TEST_1(d);
  TEST_S(d, c);

  d = "http://&=+$,;:&=+$,;@host:8080/foo%2F%3B%3D"
    ";param=+$,%2f%3b%3d/bar;param=:@&;another=@"
    "?query=" RESERVED;
  u = url_hdup(home, (url_t *)d); TEST_1(u);
  TEST_S(u->url_user, "&=+$,;"); TEST_S(u->url_password, "&=+$,;");
  TEST_S(u->url_path, "foo%2F%3B%3D;param=+$,%2F%3B%3D/bar;param=:@&;another=@");
  url_digest(hash1, sizeof(hash1), u, NULL);
  url_digest(hash2, sizeof(hash2), (url_t const *)d, NULL);
  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);

  u = url_hdup(home, (url_t *)s); TEST_1(u);
  d = url_as_string(home, u); TEST_1(d);
  TEST_S(d, c);

  url_digest(hash1, sizeof(hash1), u, NULL);
  url_digest(hash2, sizeof(hash2), (url_t const *)s, NULL);
  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);

  url_digest(hash2, sizeof(hash2), (url_t const *)c, NULL);
  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);

  END();
}
static int register_test(root_test_t *rt)
{
  int i;
  int s;
  char msg[3] = "foo";

  BEGIN();

  TEST_1((s = su_socket(rt->rt_family, SOCK_DGRAM, 0)) != -1);

  for (i = 0; i < 5; i++) {
    rt->rt_ep[i]->registered =
      su_root_register(rt->rt_root, rt->rt_ep[i]->wait,
		       wakeups[i], rt->rt_ep[i], 0);
    TEST(rt->rt_ep[i]->registered, i + 1 + SU_HAVE_PTHREADS);
  }

  for (i = 0; i < 5; i++) {
    test_ep_t *ep = rt->rt_ep[i];
    TEST(su_sendto(s, msg, sizeof(msg), 0, ep->addr, ep->addrlen),
	 sizeof(msg));
    test_run(rt);
    TEST(rt->rt_received, i);
    TEST(rt->rt_wakeup, i);
  }

  for (i = 0; i < 5; i++) {
    TEST(su_root_unregister(rt->rt_root, rt->rt_ep[i]->wait,
			    wakeups[i], rt->rt_ep[i]),
	 rt->rt_ep[i]->registered);
  }


  for (i = 0; i < 5; i++) {
    rt->rt_ep[i]->registered =
      su_root_register(rt->rt_root, rt->rt_ep[i]->wait,
		       wakeups[i], rt->rt_ep[i], 1);
    TEST_1(rt->rt_ep[i]->registered > 0);
  }

  for (i = 0; i < 5; i++) {
    test_ep_t *ep = rt->rt_ep[i];
    TEST(su_sendto(s, msg, sizeof(msg), 0, ep->addr, ep->addrlen),
	 sizeof(msg));
    test_run(rt);
    TEST(rt->rt_received, i);
    TEST(rt->rt_wakeup, i);
  }

  for (i = 0; i < 5; i++) {
    TEST(su_root_deregister(rt->rt_root, rt->rt_ep[i]->registered),
	 rt->rt_ep[i]->registered);
  }

  for (i = 0; i < 5; i++) {
    test_ep_t *ep = rt->rt_ep[i];
    TEST_1(su_wait_create(ep->wait, ep->s, SU_WAIT_IN|SU_WAIT_ERR) != -1);
    ep->registered =
      su_root_register(rt->rt_root, ep->wait,
		       wakeups[i], ep, 1);
    TEST_1(ep->registered > 0);
  }

  for (i = 0; i < 5; i++) {
    test_ep_t *ep = rt->rt_ep[i];
    TEST(su_sendto(s, msg, sizeof(msg), 0, ep->addr, ep->addrlen),
	 sizeof(msg));
    test_run(rt);
    TEST(rt->rt_received, i);
    TEST(rt->rt_wakeup, i);
  }

  for (i = 0; i < 5; i++) {
    TEST(su_root_unregister(rt->rt_root, rt->rt_ep[i]->wait,
			    wakeups[i], rt->rt_ep[i]),
	 rt->rt_ep[i]->registered);
  }

  END();
}
Beispiel #11
0
int test_any(void)
{
  /* Test any (*) urls */
  url_t any[1] = { URL_INIT_AS(any) };
  su_home_t home[1] = { SU_HOME_INIT(home) };
  url_t *u, url[1];
  char *tst;

  BEGIN();

  TEST_S(url_scheme(url_any), "*");
  TEST_S(url_scheme(url_mailto), "mailto");
  TEST_S(url_scheme(url_im), "im");
  TEST_S(url_scheme(url_cid), "cid");
  TEST_S(url_scheme(url_msrp), "msrp");
  TEST_S(url_scheme(url_msrps), "msrps");

  TEST_1(tst = su_strdup(home, "*"));
  TEST(url_d(url, tst), 0);
  TEST(url_cmp(any, url), 0);
  TEST(url->url_type, url_any);
  TEST_1(u = url_hdup(home, url));
  TEST(u->url_type, url_any);
  TEST(url_cmp(any, u), 0);

  url_digest(hash1, sizeof(hash1), url, NULL);
  url_digest(hash2, sizeof(hash2), (url_t *)"*", NULL);
  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);

  {
    char buf[6];

    TEST_1(u = url_hdup(home, (void *)"error"));
    TEST_SIZE(url_xtra(u), 6);
    TEST_SIZE(url_dup(buf, 6, url, u), 6);
    TEST_S(buf, "error");
  }

  {
    TEST_1(u = url_hdup(home, (void *)"scheme:test"));
    TEST(u->url_type, url_unknown);
  }

  {
    TEST_1(u = url_hdup(home, (void *)"*;param=foo?query=bar"));
    TEST(u->url_type, url_unknown);
    TEST_S(u->url_host, "*");
    TEST_S(u->url_params, "param=foo");
    TEST_S(u->url_headers, "query=bar");
  }

  {
    TEST_1(u = url_hdup(home, (void *)"#foo"));
    TEST(u->url_type, url_unknown);
    TEST_S(u->url_fragment, "foo");
  }

  {
    url_t u[1];
    char b2[6] = "";

    memset(u, 0xff, sizeof u);
    TEST(url_d(u, b2), 0);
    TEST(u->url_type, url_unknown);
  }

  su_home_deinit(home);

  END();
}
Beispiel #12
0
int main(int argc, char **argv){
	
	END();
}
Beispiel #13
0
/*			Generate Outout
**			===============
*/
PRIVATE void WSRC_gen_html ARGS2(HTStream *, me, BOOL, source_file)

{
    if (me->par_value[PAR_DATABASE_NAME]) {
	char * shortname = 0;
	int l;
	StrAllocCopy(shortname, me->par_value[PAR_DATABASE_NAME]);
	l = strlen(shortname);
	if ( l > 4 && !strcasecomp(shortname + l -4, ".src")) {
	    shortname[l-4] = 0; /* Chop of .src -- boring! */
	}

	START(HTML_HEAD);
	PUTC('\n');
	START(HTML_TITLE);
	PUTS(shortname);
	PUTS(source_file ? gettext(" WAIS source file") : INDEX_SEGMENT);
	END(HTML_TITLE);
	PUTC('\n');
	END(HTML_HEAD);

	START(HTML_H1);
	PUTS(shortname);
	PUTS(source_file ? gettext(" description") : INDEX_SEGMENT);
	END(HTML_H1);
	PUTC('\n');
	FREE(shortname);
    }

    START(HTML_DL);		/* Definition list of details */

    if (source_file) {
	START(HTML_DT);
	PUTS(gettext("Access links"));
	MAYBE_END(HTML_DT);
	START(HTML_DD);
	if (me->par_value[PAR_IP_NAME] &&
	    me->par_value[PAR_DATABASE_NAME]) {

	    char * WSRC_address = NULL;
	    char * www_database;
	    www_database = HTEscape(me->par_value[PAR_DATABASE_NAME],
		URL_XALPHAS);
	    HTSprintf0(&WSRC_address, "%s//%s%s%s/%s",
		STR_WAIS_URL,
		me->par_value[PAR_IP_NAME],
		me->par_value[PAR_TCP_PORT] ? ":" : "",
		me->par_value[PAR_TCP_PORT] ? me->par_value[PAR_TCP_PORT] :"",
		www_database);

	    HTStartAnchor(me->target, NULL, WSRC_address);
	    PUTS(gettext("Direct access"));
	    END(HTML_A);
	    /** Proxy will be used if defined, so let user know that - FM **/
	    PUTS(gettext(" (or via proxy server, if defined)"));

	    FREE(www_database);
	    FREE(WSRC_address);

	} else {
	    give_parameter(me, PAR_IP_NAME);
	    give_parameter(me, PAR_DATABASE_NAME);
	}
	MAYBE_END(HTML_DD);

    } /* end if source_file */

    if (me->par_value[PAR_MAINTAINER]) {
	START(HTML_DT);
	PUTS(gettext("Maintainer"));
	MAYBE_END(HTML_DT);
	START(HTML_DD);
	PUTS(me->par_value[PAR_MAINTAINER]);
	MAYBE_END(HTML_DD);
    }
    if (me->par_value[PAR_IP_NAME]) {
	START(HTML_DT);
	PUTS(gettext("Host"));
	MAYBE_END(HTML_DT);
	START(HTML_DD);
	PUTS(me->par_value[PAR_IP_NAME]);
	MAYBE_END(HTML_DD);
    }

    END(HTML_DL);

    if (me->par_value[PAR_DESCRIPTION]) {
	START(HTML_PRE);		/* Preformatted description */
	PUTS(me->par_value[PAR_DESCRIPTION]);
	END(HTML_PRE);
    }

    (*me->target->isa->_free)(me->target);

    return;
} /* generate html */
Beispiel #14
0
int main(int argc, char **argv){
	t01_create_and_free();
	t02_several_add_methods();
	
	END();
}
Beispiel #15
0
psm2_error_t
ips_tidcache_acquire(struct ips_tid *tidc,
		const void *buf, uint32_t *length,
		uint32_t *tid_array, uint32_t *tidcnt,
		uint32_t *tidoff)
{
	cl_qmap_t *p_map = &tidc->tid_cachemap;
	cl_map_item_t *p_item;
	unsigned long start = (unsigned long)buf;
	unsigned long end = start + (*length);
	uint32_t idx, nbytes;
	psm2_error_t err;

	/*
	 * Before every tid caching search, we need to update the
	 * tid caching if there is invalidation event, otherwise,
	 * the cached address may be invalidated and we might have
	 * wrong matching.
	 */
	if ((*tidc->invalidation_event) & HFI1_EVENT_TID_MMU_NOTIFY) {
		err = ips_tidcache_invalidation(tidc);
		if (err)
			return err;
	}

	/*
	 * Now we can do matching from the caching, because obsolete
	 * address in caching has been removed or identified.
	 */
retry:
	p_item = ips_cl_qmap_search(p_map, start, end);
	idx = 2*IPS_TIDINFO_GET_TID(p_item->payload.tidinfo) +
		IPS_TIDINFO_GET_TIDCTRL(p_item->payload.tidinfo);

	/*
	 * There is tid matching.
	 */
	if (idx) {
		/*
		 * if there is a caching match, but the tid has been
		 * invalidated, we can't match this tid, and we also
		 * can't register this address, we need to wait this
		 * tid to be freed.
		 */
		if (INVALIDATE(idx) != 0)
			return PSM2_OK_NO_PROGRESS;

		/*
		 * if the page offset within the tid is not less than
		 * 128K, the address offset within the page is not 64B
		 * multiple, PSM can't handle this tid with any offset
		 * mode. We need to free this tid and re-register with
		 * the asked page address.
		 */
		if (((start - START(idx)) >= 131072) && ((*tidoff) & 63)) {
			/*
			 * If the tid is currently used, retry later.
			 */
			if (REFCNT(idx) != 0)
				return PSM2_OK_NO_PROGRESS;

			/*
			 * free this tid.
			 */
			tidc->tid_array[0] = p_map->root[idx].payload.tidinfo;
			err = ips_tidcache_remove(tidc, 1);
			if (err)
				return err;

			/* try to match a node again */
			goto retry;
		}
	}

	/*
	 * If there is no match node, or 'start' falls out of node range,
	 * whole or partial buffer from 'start' is not registered yet.
	 */
	if (!idx || START(idx) > start) {
		if (!idx)
			nbytes = end - start;
		else
			nbytes = START(idx) - start;

		/*
		 * Because we don't have any match tid yet, if
		 * there is an error, we return from here, PSM
		 * will try later.
		 */
		err = ips_tidcache_register(tidc, start, nbytes, &idx);
		if (err)
			return err;
	}

	/*
	 * sanity check.
	 */
	psmi_assert(START(idx) <= start);
	psmi_assert(INVALIDATE(idx) == 0);

	*tidoff += start - START(idx);
	*tidcnt = 1;

	tid_array[0] = p_map->root[idx].payload.tidinfo;
	REFCNT(idx)++;
	if (REFCNT(idx) == 1)
		IDLE_REMOVE(idx);
	start = END(idx);

	while (start < end) {
		p_item = ips_cl_qmap_successor(p_map, &p_map->root[idx]);
		idx = 2*IPS_TIDINFO_GET_TID(p_item->payload.tidinfo) +
			IPS_TIDINFO_GET_TIDCTRL(p_item->payload.tidinfo);
		if (!idx || START(idx) != start) {
			if (!idx)
				nbytes = end - start;
			else
				nbytes = (START(idx) > end) ?
					(end - start) :
					(START(idx) - start);

			/*
			 * Because we already have at least one match tid,
			 * if it is error to register new pages, we break
			 * here and return the tids we already have.
			 */
			err = ips_tidcache_register(tidc, start, nbytes, &idx);
			if (err)
				break;
		} else if (INVALIDATE(idx) != 0) {
			/*
			 * the tid has been invalidated, it is still in
			 * caching because it is still being used, but
			 * any new usage is not allowed, we ignore it and
			 * return the tids we already have.
			 */
			psmi_assert(REFCNT(idx) != 0);
			break;
		}

		/*
		 * sanity check.
		 */
		psmi_assert(START(idx) == start);
		psmi_assert(INVALIDATE(idx) == 0);

		tid_array[(*tidcnt)++] = p_map->root[idx].payload.tidinfo;
		REFCNT(idx)++;
		if (REFCNT(idx) == 1)
			IDLE_REMOVE(idx);
		start = END(idx);
	}

	if (start < end)
		*length = start - (unsigned long)buf;
	/* otherwise, all pages are registered */
	psmi_assert((*tidcnt) > 0);

	return PSM2_OK;
}
Beispiel #16
0
int test_http(void)
{
  /* http urls */
  su_home_t home[1] = { SU_HOME_INIT(home) };
  url_t http[1] = { URL_INIT_AS(http) };
  url_t *u, url[1];
  char *tst;
  char httpurl[] =
    "http://*****:*****@host:32/foo;param=1/bar;param=3"
    "?From=foo@bar&To=bar@baz#unf";
  char http2[sizeof(httpurl) + 32];

  char queryonly[] =
    "http://some.host?query";

  BEGIN();

  TEST_S(url_scheme(url_http), "http");
  TEST_S(url_scheme(url_https), "https");

  http->url_root = '/';
  http->url_user = "******";
  http->url_password = "******";
  http->url_host = "host";
  http->url_port = "32";
  http->url_path = "foo;param=1/bar;param=3";
  http->url_headers = "From=foo@bar&To=bar@baz";
  http->url_fragment = "unf";

  TEST_1(tst = su_strdup(home, httpurl));
  TEST_1(url_d(url, tst) == 0);
  TEST_1(url_cmp(http, url) == 0);
  TEST(url->url_type, url_http);
  TEST_1(u = url_hdup(home, url));
  TEST(u->url_type, url_http);
  TEST_1(url_cmp(http, u) == 0);
  TEST_SIZE(url_e(http2, sizeof(http2), u), strlen(httpurl));
  TEST_1(strcmp(http2, httpurl) == 0);
  TEST_SIZE(snprintf(http2, sizeof(http2), URL_PRINT_FORMAT,
		     URL_PRINT_ARGS(http)), strlen(httpurl));
  TEST_1(strcmp(http2, httpurl) == 0);

  url_digest(hash1, sizeof(hash1), http, NULL);
  url_digest(hash2, sizeof(hash2), (url_t *)httpurl, NULL);
  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);

  memset(url, 0, sizeof url);
  TEST_1(tst = su_strdup(home, queryonly));
  TEST(url_d(url, tst), 0);
  TEST_S(url->url_host, "some.host");
  TEST_S(url->url_headers, "query");
  TEST_S(url->url_params, NULL);

  TEST_1(u = url_hdup(home, (void *)"http://[::1]/test;ing?here"));
  TEST_S(u->url_host, "[::1]");
  TEST_S(u->url_path, "test;ing");
  TEST_S(u->url_headers, "here");

  url_digest(hash1, sizeof(hash1), u, NULL);
  url_digest(hash2, sizeof(hash2), (url_t *)"http://[::1]/test;ing?here",
	     NULL);
  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);

  su_home_deinit(home);

  END();
}
Beispiel #17
0
int test_sendrecv(void)
{
  su_socket_t s, l, a;
  ssize_t n;
  su_sockaddr_t su, csu;
  socklen_t sulen = sizeof su.su_sin, csulen = sizeof csu.su_sin;
  char b1[8], b2[8], b3[8];
  su_iovec_t sv[3], rv[3];

  sv[0].siv_base = "one!one!", sv[0].siv_len = 8;
  sv[1].siv_base = "two!two!", sv[1].siv_len = 8;
  sv[2].siv_base = "third!", sv[2].siv_len = 6;

  rv[0].siv_base = b1, rv[0].siv_len = 8;
  rv[1].siv_base = b2, rv[1].siv_len = 8;
  rv[2].siv_base = b3, rv[2].siv_len = 8;

  BEGIN();

  s = su_socket(AF_INET, SOCK_DGRAM, 0); TEST_1(s != -1);
  su_setblocking(s, 1);

  memset(&su, 0, sulen);
  su.su_len = sulen;
  su.su_family = AF_INET;
  TEST(su_inet_pton(AF_INET, "127.0.0.1", &su.su_sin.sin_addr), 1);

  TEST(bind(s, &su.su_sa, sulen), 0);
  TEST(getsockname(s, &su.su_sa, &sulen), 0);

  n = su_vsend(s, sv, 3, 0, &su, sulen); TEST(n, 8 + 8 + 6);
  n = su_vrecv(s, rv, 3, 0, &su, &sulen); TEST(n, 8 + 8 + 6);

  TEST_M(rv[0].siv_base, sv[0].siv_base, sv[0].siv_len);
  TEST_M(rv[1].siv_base, sv[1].siv_base, sv[1].siv_len);
  TEST_M(rv[2].siv_base, sv[2].siv_base, sv[2].siv_len);

  su_close(s);

  l = su_socket(AF_INET, SOCK_STREAM, 0); TEST_1(l != -1);
  s = su_socket(AF_INET, SOCK_STREAM, 0); TEST_1(s != -1);

  memset(&su, 0, sulen);
  su.su_len = sulen;
  su.su_family = AF_INET;
  TEST(su_inet_pton(AF_INET, "127.0.0.1", &su.su_sin.sin_addr), 1);

  TEST(bind(l, &su.su_sa, sulen), 0);
  TEST(bind(s, &su.su_sa, sulen), 0);

  TEST(getsockname(l, &su.su_sa, &sulen), 0);
  TEST(listen(l, 5), 0);

  TEST(su_setblocking(s, 1), 0);

  TEST(connect(s, &su.su_sa, sulen), 0);
  a = accept(l, &csu.su_sa, &csulen); TEST_1(a != -1);

  TEST(su_setblocking(a, 1), 0);

  n = su_vsend(s, sv, 3, 0, NULL, 0); TEST(n, 8 + 8 + 6);
  n = su_vrecv(a, rv, 3, 0, NULL, NULL); TEST(n, 8 + 8 + 6);

  TEST_M(rv[0].siv_base, sv[0].siv_base, sv[0].siv_len);
  TEST_M(rv[1].siv_base, sv[1].siv_base, sv[1].siv_len);
  TEST_M(rv[2].siv_base, sv[2].siv_base, sv[2].siv_len);

  n = send(a, "", 0, 0); TEST(n, 0);
  n = su_vsend(a, sv, 3, 0, NULL, 0); TEST(n, 8 + 8 + 6);

  {
    su_wait_t w[1] = { SU_WAIT_INIT };

    TEST(su_wait_create(w, s, SU_WAIT_IN | SU_WAIT_HUP), 0);

    TEST(su_wait(w, 0, 500), SU_WAIT_TIMEOUT);

    TEST(su_wait(w, 1, 500), 0);
    TEST(su_wait_events(w, s), SU_WAIT_IN);

    TEST_SIZE(su_getmsgsize(s), 8 + 8 + 6);
    n = su_vrecv(s, rv, 3, 0, NULL, NULL); TEST(n, 8 + 8 + 6);

    TEST(su_wait(w, 1, 100), SU_WAIT_TIMEOUT);

    shutdown(a, 2);

    TEST(su_wait(w, 1, 100), 0);
#if SU_HAVE_WINSOCK
    TEST_1(su_wait_events(w, s) & SU_WAIT_HUP);
#else
    TEST_1(su_wait_events(w, s));
    n = su_vrecv(s, rv, 3, 0, NULL, NULL); TEST(n, 0);
#endif

    su_wait_destroy(w);
  }

  su_close(a);

  su_close(l);
  su_close(s);

  END();
}
Beispiel #18
0
/* Attempt to mmap a region of memory of size LEN bytes somewhere
   between LO and HI.  Returns the address of the region on success, 0
   otherwise.  MAPS is the current address space map, with NMAPS
   elements.  FD is the mmap file descriptor argument. */
static Address constrained_mmap(size_t len, Address lo, Address hi,
                                const dyninstmm_t *maps, int nmaps, int fd)
{
    const dyninstmm_t *mlo, *mhi, *p;
    Address beg, end, try;
#if defined (os_linux)  && defined(arch_power)
// DYNINSTheap_loAddr should already be defined in DYNINSTos_malloc.
// Redefining here, just in case constrained_mmap is called from a different call path.
    DYNINSTheap_loAddr = getpagesize();
#endif

    if (lo > DYNINSTheap_hiAddr) return 0;

    if (lo < DYNINSTheap_loAddr) lo = DYNINSTheap_loAddr;
    if (hi > DYNINSTheap_hiAddr) hi = DYNINSTheap_hiAddr;

    /* Round down to nearest page boundary */
    lo = lo & ~(psize-1);
    hi = hi & ~(psize-1);

    /* Round up to nearest page boundary */
    if (len % psize) {
        len += psize;
        len = len & ~(psize-1);
    }

    assert(lo < hi);
    /* Find lowest (mlo) and highest (mhi) segments between lo and
       hi.  If either lo or hi occurs within a segment, they are
       shifted out of it toward the other bound. */
    mlo = maps;
    mhi = &maps[nmaps-1];
    while (mlo <= mhi) {
        beg = BEG(mlo);
        end = END(mlo);

        if (lo < beg)
            break;

        if (lo >= beg && lo < end)
            /* lo occurs in this segment.  Shift lo to end of segment. */
            lo = end; /* still a page boundary */

        ++mlo;
    }

    while (mhi >= mlo) {
        beg = BEG(mhi);
        end = END(mhi);

        if (hi > end)
            break;
        if (hi >= beg && hi <= end)
            /* hi occurs in this segment (or just after it).  Shift
               hi to beginning of segment. */
            hi = beg; /* still a page boundary */

        --mhi;
    }
    if (lo >= hi)
        return 0;

    /* We've set the bounds of the search, now go find some free space. */

    /* Pathological cases in which the range (lo,hi) is entirely
       above or below the rest of the address space, or there are no
       segments between lo and hi.  Return no matter what from
       here. */
    if (BEG(mlo) >= hi || END(mhi) <= lo) {
        return trymmap(len, lo, hi, psize, fd);
    }
    assert(lo < BEG(mlo) && hi > END(mhi));
    /* Try to mmap in space before mlo */
    try = trymmap(len, lo, BEG(mlo), psize, fd);
    if (try) {
        return try;
    }

    /* Try to mmap in space between mlo and mhi.  Try nothing here if
       mlo and mhi are the same. */
    for (p = mlo; p < mhi; p++) {
        try = trymmap(len, END(p), BEG(p+1), psize, fd);
        if (try)
            return try;
    }

    /* Try to mmap in space between mhi and hi */
    try = trymmap(len, END(mhi), hi, psize, fd);
    if (try)
        return try;

    /* We've tried everything */
    return 0;
}
#undef BEG
#undef END


static int heap_memmapCompare(const void *A, const void *B)
{
    const dyninstmm_t *a = (const dyninstmm_t *)A;
    const dyninstmm_t *b = (const dyninstmm_t *)B;
    if (a->pr_vaddr < b->pr_vaddr) return -1;
    if (a->pr_vaddr > b->pr_vaddr) return 1;
    return 0;
}

void *DYNINSTos_malloc(size_t nbytes, void *lo_addr, void *hi_addr)
{
    void *heap;
    size_t size = nbytes;
    heapList_t *node = (heapList_t *)malloc(sizeof(heapList_t));

    /* initialize page size */
    if (psize == -1) psize = getpagesize();

    /* buffer size must be aligned */
    if (size % DYNINSTheap_align != 0) {
        free(node);
        return ((void *)-1);
    }

    /* use malloc() if appropriate */
    if (DYNINSTheap_useMalloc(lo_addr, hi_addr)) {

        Address ret_heap;
        int size_heap = size + DYNINSTheap_align;
        heap = malloc(size_heap);
        if (heap == NULL) {
            free(node);
#ifdef DEBUG
            fprintf(stderr, "Failed to MALLOC\n");
#endif
            return NULL;
        }
        ret_heap = heap_alignUp((Address)heap, DYNINSTheap_align);

        /* malloc buffer must meet range constraints */
        if (ret_heap < (Address)lo_addr ||
                ret_heap + size - 1 > (Address)hi_addr) {
            free(heap);
            free(node);
#ifdef DEBUG
            fprintf(stderr, "MALLOC'd area fails range constraints\n");
#endif
            return NULL;
        }

        /* define new heap */
        node->heap.ret_addr = (void *)ret_heap;
        node->heap.addr = heap;
        node->heap.len = size_heap;
        node->heap.type = HEAP_TYPE_MALLOC;


    } else { /* use mmap() for allocation */
        Address lo = (Address) lo_addr;
        Address hi = (Address) hi_addr;
        int fd;
        unsigned nmaps;
        dyninstmm_t *maps;

        /* What if we need to allocate memory not in the area we can mmap? */
#if defined (os_linux)  && defined(arch_power)
        DYNINSTheap_loAddr = getpagesize();
#endif
        if ((hi < DYNINSTheap_loAddr) || (lo > DYNINSTheap_hiAddr)) {
            free(node);
#ifdef DEBUG
            fprintf(stderr, "CAN'T MMAP IN RANGE GIVEN\n");
#endif
            return NULL;
        }


        /* Get memory map and sort it.  maps will point to malloc'd memory
           that we must free. */
        if (0 > DYNINSTgetMemoryMap(&nmaps, &maps)) {
            free(node);
#ifdef DEBUG
            fprintf(stderr, "failed MMAP\n");
#endif
            return NULL;
        }
        qsort(maps, (size_t)nmaps, (size_t)sizeof(dyninstmm_t), &heap_memmapCompare);
        heap_checkMappings(nmaps, maps); /* sanity check */

        /*DYNINSTheap_printMappings(nmaps, maps);*/

        fd = DYNINSTheap_mmapFdOpen();
        if (0 > fd) {
            free(node);
            free(maps);
            return NULL;
        }
        heap = (void*) constrained_mmap(size, lo, hi, maps, nmaps, fd);
        free(maps);
        DYNINSTheap_mmapFdClose(fd);
        if (!heap) {
            free(node);
#ifdef DEBUG
            fprintf(stderr, "failed MMAP(2)\n");
#endif
            return NULL;
        }

        /* define new heap */
        node->heap.ret_addr = heap;
        node->heap.addr = heap;
        node->heap.len = size;
        node->heap.type = HEAP_TYPE_MMAP;
    }

    /* insert new heap into heap list */
    node->prev = NULL;
    node->next = Heaps;
    if (Heaps) Heaps->prev = node;
    Heaps = node;

    return node->heap.ret_addr;
}

int DYNINSTos_free(void *buf)
{
    int ret = 0;
    heapList_t *t;
    /*
    fprintf(stderr, "*** DYNINSTos_free(0x%08x)\n", buf);
    */
    for (t = Heaps; t != NULL; t = t->next) {
        /* lookup heap by (returned) address */
        heap_t *heap = &t->heap;
        if (heap->ret_addr != buf) continue;

        /* remove heap from list */
        if (t->next) t->next->prev = t->prev;
        if (t->prev) t->prev->next = t->next;
        if (Heaps == t) Heaps = t->next;

        /* deallocate heap */
        switch (heap->type) {
        case HEAP_TYPE_MMAP:
            if (!unmap_region(heap->addr, heap->len)) {
                perror("DYNINSTos_free(munmap)");
                ret = -1;
            }
            break;
        case HEAP_TYPE_MALLOC:
            free(heap->addr);
            break;
        default:
            fprintf(stderr, "DYNINSTos_free(): unknown inferior heap type\n");
            ret = -1;
            break;
        }

        /* free list element */
        free(t);
        break;
    }

    return ret;
}
Beispiel #19
0
int test_md5(void)
{
  BEGIN();

  su_md5_t md5[1], md5i[1];
  uint8_t digest[SU_MD5_DIGEST_SIZE];
  char hexdigest[2 * SU_MD5_DIGEST_SIZE + 1];

  struct { char *input; uint8_t digest[SU_MD5_DIGEST_SIZE]; } suite[] = {
    { (""),
	{ 0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04,
	  0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e } },
    { ("a"), { 0x0c, 0xc1, 0x75, 0xb9, 0xc0, 0xf1, 0xb6, 0xa8,
	       0x31, 0xc3, 0x99, 0xe2, 0x69, 0x77, 0x26, 0x61 } },
    { ("abc"), { 0x90, 0x01, 0x50, 0x98, 0x3c, 0xd2, 0x4f, 0xb0,
		 0xd6, 0x96, 0x3f, 0x7d, 0x28, 0xe1, 0x7f, 0x72 } },
    { ("message digest"),
      { 0xf9, 0x6b, 0x69, 0x7d, 0x7c, 0xb7, 0x93, 0x8d,
	0x52, 0x5a, 0x2f, 0x31, 0xaa, 0xf1, 0x61, 0xd0 } },
    { ("abcdefghijklmnopqrstuvwxyz"),
      { 0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00,
	0x7d, 0xfb, 0x49, 0x6c, 0xca, 0x67, 0xe1, 0x3b } },
    { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
      { 0xd1, 0x74, 0xab, 0x98, 0xd2, 0x77, 0xd9, 0xf5,
	0xa5, 0x61, 0x1c, 0x2c, 0x9f, 0x41, 0x9d, 0x9f } },

    { "1234567890123456789012345678901234567890"
      "1234567890123456789012345678901234567890",
      { 0x57, 0xed, 0xf4, 0xa2, 0x2b, 0xe3, 0xc9, 0x55,
	0xac, 0x49, 0xda, 0x2e, 0x21, 0x07, 0xb6, 0x7a } }};

  su_md5_init(md5);
  su_md5_update(md5, suite[0].input, 0);
  su_md5_digest(md5, digest);
  TEST_M(digest, suite[0].digest, SU_MD5_DIGEST_SIZE);
  su_md5_deinit(md5);

  su_md5_init(md5);
  su_md5_strupdate(md5, suite[1].input);
  su_md5_digest(md5, digest);
  TEST_M(digest, suite[1].digest, SU_MD5_DIGEST_SIZE);
  su_md5_deinit(md5);

  su_md5_init(md5);
  su_md5_iupdate(md5, suite[2].input, 3);
  su_md5_digest(md5, digest);
  TEST_M(digest, suite[2].digest, SU_MD5_DIGEST_SIZE);
  su_md5_deinit(md5);

  su_md5_init(md5);
  su_md5_striupdate(md5, suite[3].input);
  su_md5_digest(md5, digest);
  TEST_M(digest, suite[3].digest, SU_MD5_DIGEST_SIZE);
  su_md5_deinit(md5);

  su_md5_init(md5);
  su_md5_iupdate(md5, suite[4].input, 13);
  su_md5_striupdate(md5, suite[4].input + 13);
  su_md5_digest(md5, digest);
  TEST_M(digest, suite[4].digest, SU_MD5_DIGEST_SIZE);
  su_md5_deinit(md5);

  su_md5_init(md5);
  su_md5_update(md5, suite[5].input, 13);
  su_md5_strupdate(md5, suite[5].input + 13);
  su_md5_digest(md5, digest);
  TEST_M(digest, suite[5].digest, SU_MD5_DIGEST_SIZE);
  su_md5_deinit(md5);

  su_md5_init(md5);
  su_md5_update(md5, suite[6].input, 13);
  su_md5_strupdate(md5, suite[6].input + 13);
  su_md5_digest(md5, digest);
  TEST_M(digest, suite[6].digest, SU_MD5_DIGEST_SIZE);
  su_md5_deinit(md5);

  su_md5_init(md5);
  su_md5_str0update(md5, NULL);
  su_md5_hexdigest(md5, hexdigest);
  TEST_S(hexdigest, "93b885adfe0da089cdf634904fd59f71");
  su_md5_deinit(md5);

  su_md5_init(md5);
  su_md5_stri0update(md5, NULL);
  su_md5_stri0update(md5, "ABBADABBADOO");
  su_md5_hexdigest(md5, hexdigest);
  TEST_S(hexdigest, "101e6dd7cfabdb5c74f44b4c545c05cc");

  su_md5_init(md5);
  su_md5_update(md5, "\0abbadabbadoo\0", 14);
  su_md5_hexdigest(md5, hexdigest);
  TEST_S(hexdigest, "101e6dd7cfabdb5c74f44b4c545c05cc");
  su_md5_deinit(md5);

  /* Calculate md5 sum of 512 MB of zero */
  if (getenv("EXPENSIVE_CHECKS")) {
    char zerokilo[1024] = { '\0' };
    int i;

    su_md5_init(md5);
    su_md5_iupdate(md5, zerokilo, 19);
    for (i = 1; i < 512 * 1024; i++)
      su_md5_update(md5, zerokilo, 1024);
    *md5i = *md5;

    su_md5_update(md5, zerokilo, 1024 - 19);
    su_md5_hexdigest(md5, hexdigest);
    TEST_S(hexdigest, "aa559b4e3523a6c931f08f4df52d58f2");
    su_md5_deinit(md5);

    su_md5_iupdate(md5i, zerokilo, 1024 - 19);
    su_md5_hexdigest(md5i, hexdigest);
    TEST_S(hexdigest, "aa559b4e3523a6c931f08f4df52d58f2");
  }
  END();
}
/* Load the given section: NULL on error. */
static void *PERBIT(load_section)(ElfPERBIT(Ehdr) *hdr,
			    const char *secname,
			    unsigned long *size,
			    int conv)
{
	ElfPERBIT(Shdr) *sechdrs;
	unsigned int i;
	char *secnames;

	/* Grab section headers and strings so we can tell who is who */
	sechdrs = (void *)hdr + END(hdr->e_shoff, conv);
	secnames = (void *)hdr
		+ END(sechdrs[END(hdr->e_shstrndx, conv)].sh_offset, conv);

	/* Find the section they want */
	for (i = 1; i < END(hdr->e_shnum, conv); i++) {
		if (streq(secnames+END(sechdrs[i].sh_name, conv), secname)) {
			*size = END(sechdrs[i].sh_size, conv);
			return (void *)hdr + END(sechdrs[i].sh_offset, conv);
		}
	}
	*size = 0;
	return NULL;
}

static void PERBIT(load_symbols)(struct module *module)
{
	struct PERBIT(kernel_symbol) *ksyms;
	char *ksymstrings;
	unsigned long i, size;
Beispiel #21
0
u8 *process_list(u8 *myname, DWORD *mypid, DWORD *size) {
#ifdef WIN32
    PROCESSENTRY32  Process;
    MODULEENTRY32   Module;
    HANDLE          snapProcess,
                    snapModule;
    DWORD           retpid = 0;
    int             len;
    BOOL            b;
    u8              tmpbuff[60],
                    *process_name,
                    *module_name,
                    *module_print,
                    *tmp;

    if(mypid) retpid = *mypid;
    if(!myname && !retpid) {
        printf(
            "  pid/addr/size       process/module name\n"
            "  ---------------------------------------\n");
    }

#define START(X,Y) \
            snap##X = CreateToolhelp32Snapshot(Y, Process.th32ProcessID); \
            X.dwSize = sizeof(X); \
            for(b = X##32First(snap##X, &X); b; b = X##32Next(snap##X, &X)) { \
                X.dwSize = sizeof(X);
#define END(X) \
            } \
            CloseHandle(snap##X);

    Process.th32ProcessID = 0;
    START(Process, TH32CS_SNAPPROCESS)
        process_name = Process.szExeFile;

        if(!myname && !retpid) {
            printf("  %-10lu ******** %s\n",
                Process.th32ProcessID,
                process_name);
        }
        if(myname && stristr(process_name, myname)) {
            retpid = Process.th32ProcessID;
        }

        START(Module, TH32CS_SNAPMODULE)
            module_name = Module.szExePath; // szModule?

            len = strlen(module_name);
            if(len >= 60) {
                tmp = strrchr(module_name, '\\');
                if(!tmp) tmp = strrchr(module_name, '/');
                if(!tmp) tmp = module_name;
                len -= (tmp - module_name);
                sprintf(tmpbuff,
                    "%.*s...%s",
                    54 - len,
                    module_name,
                    tmp);
                module_print = tmpbuff;
            } else {
                module_print = module_name;
            }

            if(!myname && !retpid) {
                printf("    %p %08lx %s\n",
                    Module.modBaseAddr,
                    Module.modBaseSize,
                    module_print);
            }
            if(!retpid) {
                if(myname && stristr(module_name, myname)) {
                    retpid = Process.th32ProcessID;
                }
            }
            if(retpid && mypid && (Process.th32ProcessID == retpid)) {
                printf("- %p %08lx %s\n",
                    Module.modBaseAddr,
                    Module.modBaseSize,
                    module_print);
                *mypid = retpid;
                if(size) *size = Module.modBaseSize;
                return(Module.modBaseAddr);
            }

        END(Module)

    END(Process)

#undef START
#undef END

#else

    //system("ps -eo pid,cmd");
    printf("\n"
        "- use ps to know the pids of your processes, like:\n"
        "  ps -eo pid,cmd\n");

#endif

    return(NULL);
}
Beispiel #22
0
/*
**	Output an element in HTML
**	Returns YES if OK, else NO
*/
PRIVATE BOOL HTDirNode_print (HTDir *dir, HTDirNode *node)
{
    char *tp = NULL;
    HTStructured *target = dir->target;
    if (dir->show & HT_DS_ICON) {
	HTFormat format = NULL;
	HTEncoding encoding = NULL;
	double q=1.0;
	HTIconNode * icon;
	if (node->mode == HT_IS_FILE)
	    HTBind_getFormat(node->fname, &format, &encoding, NULL, NULL, &q);
	icon = HTIcon_find(node->mode, format, encoding);

	/* Are we having a hot or a cold icon? */
	if (!(dir->show & HT_DS_HOTI)) {
	    if (icon) {
		char * alt = HTIcon_alternative(icon, YES);
		HTMLPutImg(target, HTIcon_url(icon), alt, NULL);
		HT_FREE(alt);
		PUTC(' ');
	    }
	}

	/* Start the anchor element */
	if (dir->base) {
	    char *escaped = expand_name(node->fname, node->mode);
	    char *full;
	    if ((full = (char *) HT_MALLOC(strlen(escaped)+strlen(dir->base)+1)) == NULL)
		HT_OUTOFMEM("HTDirNode_print");
	    strcpy(full, dir->base);
	    strcat(full, escaped);
	    HTStartAnchor(target, NULL, full);
	    HT_FREE(escaped);
	    HT_FREE(full);
	} else {
	    char *escaped = expand_name(node->fname, node->mode);
	    HTStartAnchor(target, NULL, escaped);
	    HT_FREE(escaped);
	}

	if (dir->show & HT_DS_HOTI) {
	    char * alt = HTIcon_alternative(icon, YES);
	    HTMLPutImg(target, HTIcon_url(icon), alt, NULL);
	    PUTC(' ');
	}
    } else {
	if (dir->base) {
	    char *escaped = expand_name(node->fname, node->mode);
	    char *full;
	    if ((full = (char *) HT_MALLOC(strlen(escaped)+strlen(dir->base)+1)) == NULL)
		HT_OUTOFMEM("HTDirNode_print");
	    strcpy(full, dir->base);
	    strcat(full, escaped);
	    HTStartAnchor(target, NULL, escaped);
	    HT_FREE(escaped);
	    HT_FREE(full);
	} else {
	    char *escaped = HTEscape(node->fname, URL_XPALPHAS);
	    HTStartAnchor(target, NULL, escaped);
	    HT_FREE(escaped);
	}
    }
    
    /* Insert the anchor text and end anchor */
    {
	char *in = node->fname;
	char *out = dir->fnbuf;
	int l = dir->curfw;
	while (l-- > 0 && *in && (*out++ = *in++));
	if (*in)
	    *(out-1) = '>';
	else if (node->mode == HT_IS_DIR) {
	    *out++ = '/';
	    l--;
	}
	*out = '\0';
	PUTS(dir->fnbuf);
	END(HTML_A);
	out = dir->fnbuf;
	while (l-- >= 0) *out++ = ' ';
	LeftStr(&out, " ", HT_DLEN_SPACE);
	*out = '\0';
	PUTS(dir->fnbuf);
    }

    /* Print the rest of it */
    tp = dir->lnbuf;
    if (node->date) {
	RightStr(&tp, node->date, HT_DLEN_DATE);
	LeftStr(&tp, " ", HT_DLEN_SPACE);
    }
    if (node->size) {
	RightStr(&tp, node->size, HT_DLEN_SIZE);
	LeftStr(&tp, " ", HT_DLEN_SPACE);
    }
    if (node->note) {
	LeftStr(&tp, node->note, HT_DLEN_DES);
	LeftStr(&tp, " ", HT_DLEN_SPACE);
    }
    *tp = '\0';
    PUTS(dir->lnbuf);
    PUTC('\n');
    return YES;
}
Beispiel #23
0
#include "string.h"
#include "usb.h"
#include "backlight.h"
#include "mpr121.h"

#define I_VDDIO 0 /* index in the table */

struct imx233_button_map_t imx233_button_map[] =
{
    [I_VDDIO] = IMX233_BUTTON_(VDDIO, VDDIO(3640), "vddio"), /* we need VDDIO for relative */
    IMX233_BUTTON_(HOLD, GPIO(0, 4), "jack", INVERTED),
    IMX233_BUTTON(VOL_DOWN, GPIO(2, 7), "vol_down", INVERTED),
    IMX233_BUTTON(VOL_UP, GPIO(2, 8), "vol_up", INVERTED),
    IMX233_BUTTON_(JACK, LRADC_REL(5, 3520, I_VDDIO), "jack"),
    IMX233_BUTTON(POWER, PSWITCH(1), "power"),
    IMX233_BUTTON_(END, END(), "")
};

static struct mpr121_config_t config =
{
    .ele =
    {
        [0] = {.tth = 5, .rth = 4 },
        [1] = {.tth = 5, .rth = 4 },
        [2] = {.tth = 5, .rth = 4 },
        [3] = {.tth = 5, .rth = 4 },
        [4] = {.tth = 4, .rth = 3 },
        [5] = {.tth = 4, .rth = 3 },
        [6] = {.tth = 5, .rth = 4 },
        [7] = {.tth = 5, .rth = 4 },
        [8] = {.gpio = ELE_GPIO_OUTPUT_OPEN_LED },
Beispiel #24
0
/*	HTDir_new
**	---------
**    	Creates a structured stream object and sets up the initial HTML stuff
**	Returns the dir object if OK, else NULL
*/
PUBLIC HTDir * HTDir_new (HTRequest * request, HTDirShow show, HTDirKey key)
{    
    HTDir *dir;
    char *title = NULL;
    if (!request) return NULL;

    /* Create object */
    if ((dir = (HTDir *) HT_CALLOC(1, sizeof (HTDir))) == NULL ||
	(dir->fnbuf = (char *) HT_MALLOC(MaxFileW+HT_DLEN_SPACE)) == NULL)
	HT_OUTOFMEM("HTDir_new");
    dir->target = HTMLGenerator(request, NULL, WWW_HTML,
			       HTRequest_outputFormat(request),
			       HTRequest_outputStream(request));
    HTRequest_setOutputConnected(request, YES);
    HTAnchor_setFormat(HTRequest_anchor(request), WWW_HTML);
    dir->request = request;
    dir->show = show;
    dir->key = key;
    if (key==HT_DK_NONE)
	dir->curfw = MaxFileW;
    else {
	dir->curfw = MinFileW;
	dir->array = HTArray_new(256);
    }

    /* We're all OK */
    HTRequest_addError(request, ERR_INFO, NO, HTERR_OK, NULL, 0, "HTDir_new");

    /* Find the length of the fields */
    {
	int len = HT_DLEN_SPACE+1;
	if (show & HT_DS_SIZE) len += (HT_DLEN_SIZE+HT_DLEN_SPACE);
	if (show & HT_DS_DATE) len += (HT_DLEN_DATE+HT_DLEN_SPACE);
	if (show & HT_DS_DES) len += HT_DLEN_DES;
	if ((dir->lnbuf = (char *) HT_MALLOC(len)) == NULL)
	    HT_OUTOFMEM("HTDir_new");
    }

    /* Find the title and the base URL */
    {
	char *addr = HTAnchor_address((HTAnchor *) HTRequest_anchor(request));
	char *path = HTParse(addr, "", PARSE_PATH+PARSE_PUNCTUATION);
	char *ptr;
	if ((ptr = strchr(path, ';')) || (ptr = strchr(path, '?')))
	    *ptr = '\0';
	StrAllocCopy(title, path);
	HTUnEscape(title);				 	    /* Title */
	if((ptr=strrchr(path, '/')) && (ptr<path+strlen(path)-1 || ptr==path)){
	    StrAllocCopy(dir->base, ++ptr);
	    StrAllocCat(dir->base, "/");
	}
	HTTRACE(PROT_TRACE, "HTDir_new... base is `%s\'\n" _ dir->base ? dir->base : "");
	HT_FREE(addr);
	HT_FREE(path);
    }

    /* Start the HTML stuff */
    {
	HTStructured *target = dir->target;
	START(HTML_HTML);
	START(HTML_HEAD);
	START(HTML_TITLE);
	PUTS("Current index is ");
	PUTS(title);
	END(HTML_TITLE);
	END(HTML_HEAD);
	START(HTML_BODY);
	START(HTML_H1);
	PUTS("Index of ");
	PUTS(title);
	END(HTML_H1);
    }
    HT_FREE(title);
    return dir;
}
int do_sync_pull(const char *rpath, const char *lpath, int show_progress, int copy_attrs)
{
    unsigned mode, time;
    struct stat st;

    int fd;

    fd = adb_connect("sync:");
    if(fd < 0) {
        fprintf(stderr,"error: %s\n", adb_error());
        return 1;
    }

    if(sync_readtime(fd, rpath, &time, &mode)) {
        return 1;
    }
    if(mode == 0) {
        fprintf(stderr,"remote object '%s' does not exist\n", rpath);
        return 1;
    }

    if(S_ISREG(mode) || S_ISLNK(mode) || S_ISCHR(mode) || S_ISBLK(mode)) {
        if(stat(lpath, &st) == 0) {
            if(S_ISDIR(st.st_mode)) {
                    /* if we're copying a remote file to a local directory,
                    ** we *really* want to copy to localdir + "/" + remotefilename
                    */
                const char *name = adb_dirstop(rpath);
                if(name == 0) {
                    name = rpath;
                } else {
                    name++;
                }
                int  tmplen = strlen(name) + strlen(lpath) + 2;
                char *tmp = reinterpret_cast<char*>(malloc(tmplen));
                if(tmp == 0) return 1;
                snprintf(tmp, tmplen, "%s/%s", lpath, name);
                lpath = tmp;
            }
        }
        BEGIN();
        if (sync_recv(fd, rpath, lpath, show_progress)) {
            return 1;
        } else {
            if (copy_attrs && set_time_and_mode(lpath, time, mode))
                return 1;
            END();
            sync_quit(fd);
            return 0;
        }
    } else if(S_ISDIR(mode)) {
        BEGIN();
        if (copy_remote_dir_local(fd, rpath, lpath, copy_attrs)) {
            return 1;
        } else {
            END();
            sync_quit(fd);
            return 0;
        }
    } else {
        fprintf(stderr,"remote object '%s' not a file or directory\n", rpath);
        return 1;
    }
}
Beispiel #26
0
uint256 CBlockHeader::GetHash() const
{
    return Hash(BEGIN(nVersion), END(nNonce));
}
Beispiel #27
0
static int
internal_function
FCT (const CHAR *pattern, const CHAR *string, const CHAR *string_end,
     bool no_leading_period, int flags)
{
  register const CHAR *p = pattern, *n = string;
  register UCHAR c;
#ifdef _LIBC
# if WIDE_CHAR_VERSION
  const char *collseq = (const char *)
    _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
# else
  const UCHAR *collseq = (const UCHAR *)
    _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQMB);
# endif
#endif

  while ((c = *p++) != L_('\0'))
    {
      bool new_no_leading_period = false;
      c = FOLD (c);

      switch (c)
	{
	case L_('?'):
	  if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(')
	    {
	      int res;

	      res = EXT (c, p, n, string_end, no_leading_period,
			 flags);
	      if (res != -1)
		return res;
	    }

	  if (n == string_end)
	    return FNM_NOMATCH;
	  else if (*n == L_('/') && (flags & FNM_FILE_NAME))
	    return FNM_NOMATCH;
	  else if (*n == L_('.') && no_leading_period)
	    return FNM_NOMATCH;
	  break;

	case L_('\\'):
	  if (!(flags & FNM_NOESCAPE))
	    {
	      c = *p++;
	      if (c == L_('\0'))
		/* Trailing \ loses.  */
		return FNM_NOMATCH;
	      c = FOLD (c);
	    }
	  if (n == string_end || FOLD ((UCHAR) *n) != c)
	    return FNM_NOMATCH;
	  break;

	case L_('*'):
	  if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(')
	    {
	      int res;

	      res = EXT (c, p, n, string_end, no_leading_period,
			 flags);
	      if (res != -1)
		return res;
	    }

	  if (n != string_end && *n == L_('.') && no_leading_period)
	    return FNM_NOMATCH;

	  for (c = *p++; c == L_('?') || c == L_('*'); c = *p++)
	    {
	      if (*p == L_('(') && (flags & FNM_EXTMATCH) != 0)
		{
		  const CHAR *endp = END (p);
		  if (endp != p)
		    {
		      /* This is a pattern.  Skip over it.  */
		      p = endp;
		      continue;
		    }
		}

	      if (c == L_('?'))
		{
		  /* A ? needs to match one character.  */
		  if (n == string_end)
		    /* There isn't another character; no match.  */
		    return FNM_NOMATCH;
		  else if (*n == L_('/')
			   && __builtin_expect (flags & FNM_FILE_NAME, 0))
		    /* A slash does not match a wildcard under
		       FNM_FILE_NAME.  */
		    return FNM_NOMATCH;
		  else
		    /* One character of the string is consumed in matching
		       this ? wildcard, so *??? won't match if there are
		       less than three characters.  */
		    ++n;
		}
	    }

	  if (c == L_('\0'))
	    /* The wildcard(s) is/are the last element of the pattern.
	       If the name is a file name and contains another slash
	       this means it cannot match, unless the FNM_LEADING_DIR
	       flag is set.  */
	    {
	      int result = (flags & FNM_FILE_NAME) == 0 ? 0 : FNM_NOMATCH;

	      if (flags & FNM_FILE_NAME)
		{
		  if (flags & FNM_LEADING_DIR)
		    result = 0;
		  else
		    {
		      if (MEMCHR (n, L_('/'), string_end - n) == NULL)
			result = 0;
		    }
		}

	      return result;
	    }
	  else
	    {
	      const CHAR *endp;

	      endp = MEMCHR (n, (flags & FNM_FILE_NAME) ? L_('/') : L_('\0'),
			     string_end - n);
	      if (endp == NULL)
		endp = string_end;

	      if (c == L_('[')
		  || (__builtin_expect (flags & FNM_EXTMATCH, 0) != 0
		      && (c == L_('@') || c == L_('+') || c == L_('!'))
		      && *p == L_('(')))
		{
		  int flags2 = ((flags & FNM_FILE_NAME)
				? flags : (flags & ~FNM_PERIOD));
		  bool no_leading_period2 = no_leading_period;

		  for (--p; n < endp; ++n, no_leading_period2 = false)
		    if (FCT (p, n, string_end, no_leading_period2, flags2)
			== 0)
		      return 0;
		}
	      else if (c == L_('/') && (flags & FNM_FILE_NAME))
		{
		  while (n < string_end && *n != L_('/'))
		    ++n;
		  if (n < string_end && *n == L_('/')
		      && (FCT (p, n + 1, string_end, flags & FNM_PERIOD, flags)
			  == 0))
		    return 0;
		}
	      else
		{
		  int flags2 = ((flags & FNM_FILE_NAME)
				? flags : (flags & ~FNM_PERIOD));
		  int no_leading_period2 = no_leading_period;

		  if (c == L_('\\') && !(flags & FNM_NOESCAPE))
		    c = *p;
		  c = FOLD (c);
		  for (--p; n < endp; ++n, no_leading_period2 = false)
		    if (FOLD ((UCHAR) *n) == c
			&& (FCT (p, n, string_end, no_leading_period2, flags2)
			    == 0))
		      return 0;
		}
	    }

	  /* If we come here no match is possible with the wildcard.  */
	  return FNM_NOMATCH;

	case L_('['):
	  {
	    /* Nonzero if the sense of the character class is inverted.  */
	    register bool not;
	    CHAR cold;
	    UCHAR fn;

	    if (posixly_correct == 0)
	      posixly_correct = getenv ("POSIXLY_CORRECT") != NULL ? 1 : -1;

	    if (n == string_end)
	      return FNM_NOMATCH;

	    if (*n == L_('.') && no_leading_period)
	      return FNM_NOMATCH;

	    if (*n == L_('/') && (flags & FNM_FILE_NAME))
	      /* `/' cannot be matched.  */
	      return FNM_NOMATCH;

	    not = (*p == L_('!') || (posixly_correct < 0 && *p == L_('^')));
	    if (not)
	      ++p;

	    fn = FOLD ((UCHAR) *n);

	    c = *p++;
	    for (;;)
	      {
		if (!(flags & FNM_NOESCAPE) && c == L_('\\'))
		  {
		    if (*p == L_('\0'))
		      return FNM_NOMATCH;
		    c = FOLD ((UCHAR) *p);
		    ++p;

		    if (c == fn)
		      goto matched;
		  }
		else if (c == L_('[') && *p == L_(':'))
		  {
		    /* Leave room for the null.  */
		    CHAR str[CHAR_CLASS_MAX_LENGTH + 1];
		    size_t c1 = 0;
#if defined _LIBC || WIDE_CHAR_SUPPORT
		    wctype_t wt;
#endif
		    const CHAR *startp = p;

		    for (;;)
		      {
			if (c1 == CHAR_CLASS_MAX_LENGTH)
			  /* The name is too long and therefore the pattern
			     is ill-formed.  */
			  return FNM_NOMATCH;

			c = *++p;
			if (c == L_(':') && p[1] == L_(']'))
			  {
			    p += 2;
			    break;
			  }
			if (c < L_('a') || c >= L_('z'))
			  {
			    /* This cannot possibly be a character class name.
			       Match it as a normal range.  */
			    p = startp;
			    c = L_('[');
			    goto normal_bracket;
			  }
			str[c1++] = c;
		      }
		    str[c1] = L_('\0');

#if defined _LIBC || WIDE_CHAR_SUPPORT
		    wt = IS_CHAR_CLASS (str);
		    if (wt == 0)
		      /* Invalid character class name.  */
		      return FNM_NOMATCH;

# if defined _LIBC && ! WIDE_CHAR_VERSION
		    /* The following code is glibc specific but does
		       there a good job in speeding up the code since
		       we can avoid the btowc() call.  */
		    if (_ISCTYPE ((UCHAR) *n, wt))
		      goto matched;
# else
		    if (ISWCTYPE (BTOWC ((UCHAR) *n), wt))
		      goto matched;
# endif
#else
		    if ((STREQ (str, L_("alnum")) && ISALNUM ((UCHAR) *n))
			|| (STREQ (str, L_("alpha")) && ISALPHA ((UCHAR) *n))
			|| (STREQ (str, L_("blank")) && ISBLANK ((UCHAR) *n))
			|| (STREQ (str, L_("cntrl")) && ISCNTRL ((UCHAR) *n))
			|| (STREQ (str, L_("digit")) && ISDIGIT ((UCHAR) *n))
			|| (STREQ (str, L_("graph")) && ISGRAPH ((UCHAR) *n))
			|| (STREQ (str, L_("lower")) && ISLOWER ((UCHAR) *n))
			|| (STREQ (str, L_("print")) && ISPRINT ((UCHAR) *n))
			|| (STREQ (str, L_("punct")) && ISPUNCT ((UCHAR) *n))
			|| (STREQ (str, L_("space")) && ISSPACE ((UCHAR) *n))
			|| (STREQ (str, L_("upper")) && ISUPPER ((UCHAR) *n))
			|| (STREQ (str, L_("xdigit")) && ISXDIGIT ((UCHAR) *n)))
		      goto matched;
#endif
		    c = *p++;
		  }
#ifdef _LIBC
		else if (c == L_('[') && *p == L_('='))
		  {
		    UCHAR str[1];
		    uint32_t nrules =
		      _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
		    const CHAR *startp = p;

		    c = *++p;
		    if (c == L_('\0'))
		      {
			p = startp;
			c = L_('[');
			goto normal_bracket;
		      }
		    str[0] = c;

		    c = *++p;
		    if (c != L_('=') || p[1] != L_(']'))
		      {
			p = startp;
			c = L_('[');
			goto normal_bracket;
		      }
		    p += 2;

		    if (nrules == 0)
		      {
			if ((UCHAR) *n == str[0])
			  goto matched;
		      }
		    else
		      {
			const int32_t *table;
# if WIDE_CHAR_VERSION
			const int32_t *weights;
			const int32_t *extra;
# else
			const unsigned char *weights;
			const unsigned char *extra;
# endif
			const int32_t *indirect;
			int32_t idx;
			const UCHAR *cp = (const UCHAR *) str;

			/* This #include defines a local function!  */
# if WIDE_CHAR_VERSION
#  include <locale/weightwc.h>
# else
#  include <locale/weight.h>
# endif

# if WIDE_CHAR_VERSION
			table = (const int32_t *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
			weights = (const int32_t *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
			extra = (const int32_t *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
			indirect = (const int32_t *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
# else
			table = (const int32_t *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
			weights = (const unsigned char *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
			extra = (const unsigned char *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
			indirect = (const int32_t *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
# endif

			idx = findidx (&cp);
			if (idx != 0)
			  {
			    /* We found a table entry.  Now see whether the
			       character we are currently at has the same
			       equivalance class value.  */
			    int len = weights[idx];
			    int32_t idx2;
			    const UCHAR *np = (const UCHAR *) n;

			    idx2 = findidx (&np);
			    if (idx2 != 0 && len == weights[idx2])
			      {
				int cnt = 0;

				while (cnt < len
				       && (weights[idx + 1 + cnt]
					   == weights[idx2 + 1 + cnt]))
				  ++cnt;

				if (cnt == len)
				  goto matched;
			      }
			  }
		      }

		    c = *p++;
		  }
#endif
		else if (c == L_('\0'))
		  /* [ (unterminated) loses.  */
		  return FNM_NOMATCH;
		else
		  {
		    bool is_range = false;

#ifdef _LIBC
		    bool is_seqval = false;

		    if (c == L_('[') && *p == L_('.'))
		      {
			uint32_t nrules =
			  _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
			const CHAR *startp = p;
			size_t c1 = 0;

			while (1)
			  {
			    c = *++p;
			    if (c == L_('.') && p[1] == L_(']'))
			      {
				p += 2;
				break;
			      }
			    if (c == '\0')
			      return FNM_NOMATCH;
			    ++c1;
			  }

			/* We have to handling the symbols differently in
			   ranges since then the collation sequence is
			   important.  */
			is_range = *p == L_('-') && p[1] != L_('\0');

			if (nrules == 0)
			  {
			    /* There are no names defined in the collation
			       data.  Therefore we only accept the trivial
			       names consisting of the character itself.  */
			    if (c1 != 1)
			      return FNM_NOMATCH;

			    if (!is_range && *n == startp[1])
			      goto matched;

			    cold = startp[1];
			    c = *p++;
			  }
			else
			  {
			    int32_t table_size;
			    const int32_t *symb_table;
# ifdef WIDE_CHAR_VERSION
			    char str[c1];
			    size_t strcnt;
# else
#  define str (startp + 1)
# endif
			    const unsigned char *extra;
			    int32_t idx;
			    int32_t elem;
			    int32_t second;
			    int32_t hash;

# ifdef WIDE_CHAR_VERSION
			    /* We have to convert the name to a single-byte
			       string.  This is possible since the names
			       consist of ASCII characters and the internal
			       representation is UCS4.  */
			    for (strcnt = 0; strcnt < c1; ++strcnt)
			      str[strcnt] = startp[1 + strcnt];
# endif

			    table_size =
			      _NL_CURRENT_WORD (LC_COLLATE,
						_NL_COLLATE_SYMB_HASH_SIZEMB);
			    symb_table = (const int32_t *)
			      _NL_CURRENT (LC_COLLATE,
					   _NL_COLLATE_SYMB_TABLEMB);
			    extra = (const unsigned char *)
			      _NL_CURRENT (LC_COLLATE,
					   _NL_COLLATE_SYMB_EXTRAMB);

			    /* Locate the character in the hashing table.  */
			    hash = elem_hash (str, c1);

			    idx = 0;
			    elem = hash % table_size;
			    second = hash % (table_size - 2);
			    while (symb_table[2 * elem] != 0)
			      {
				/* First compare the hashing value.  */
				if (symb_table[2 * elem] == hash
				    && c1 == extra[symb_table[2 * elem + 1]]
				    && memcmp (str,
					       &extra[symb_table[2 * elem + 1]
						     + 1], c1) == 0)
				  {
				    /* Yep, this is the entry.  */
				    idx = symb_table[2 * elem + 1];
				    idx += 1 + extra[idx];
				    break;
				  }

				/* Next entry.  */
				elem += second;
			      }

			    if (symb_table[2 * elem] != 0)
			      {
				/* Compare the byte sequence but only if
				   this is not part of a range.  */
# ifdef WIDE_CHAR_VERSION
				int32_t *wextra;

				idx += 1 + extra[idx];
				/* Adjust for the alignment.  */
				idx = (idx + 3) & ~3;

				wextra = (int32_t *) &extra[idx + 4];
# endif

				if (! is_range)
				  {
# ifdef WIDE_CHAR_VERSION
				    for (c1 = 0;
					 (int32_t) c1 < wextra[idx];
					 ++c1)
				      if (n[c1] != wextra[1 + c1])
					break;

				    if ((int32_t) c1 == wextra[idx])
				      goto matched;
# else
				    for (c1 = 0; c1 < extra[idx]; ++c1)
				      if (n[c1] != extra[1 + c1])
					break;

				    if (c1 == extra[idx])
				      goto matched;
# endif
				  }

				/* Get the collation sequence value.  */
				is_seqval = true;
# ifdef WIDE_CHAR_VERSION
				cold = wextra[1 + wextra[idx]];
# else
				/* Adjust for the alignment.  */
				idx += 1 + extra[idx];
				idx = (idx + 3) & ~4;
				cold = *((int32_t *) &extra[idx]);
# endif

				c = *p++;
			      }
			    else if (c1 == 1)
			      {
				/* No valid character.  Match it as a
				   single byte.  */
				if (!is_range && *n == str[0])
				  goto matched;

				cold = str[0];
				c = *p++;
			      }
			    else
			      return FNM_NOMATCH;
			  }
		      }
		    else
# undef str
#endif
		      {
			c = FOLD (c);
		      normal_bracket:

			/* We have to handling the symbols differently in
			   ranges since then the collation sequence is
			   important.  */
			is_range = (*p == L_('-') && p[1] != L_('\0')
				    && p[1] != L_(']'));

			if (!is_range && c == fn)
			  goto matched;

			cold = c;
			c = *p++;
		      }

		    if (c == L_('-') && *p != L_(']'))
		      {
#if _LIBC
			/* We have to find the collation sequence
			   value for C.  Collation sequence is nothing
			   we can regularly access.  The sequence
			   value is defined by the order in which the
			   definitions of the collation values for the
			   various characters appear in the source
			   file.  A strange concept, nowhere
			   documented.  */
			uint32_t fcollseq;
			uint32_t lcollseq;
			UCHAR cend = *p++;

# ifdef WIDE_CHAR_VERSION
			/* Search in the `names' array for the characters.  */
			fcollseq = __collseq_table_lookup (collseq, fn);
			if (fcollseq == ~((uint32_t) 0))
			  /* XXX We don't know anything about the character
			     we are supposed to match.  This means we are
			     failing.  */
			  goto range_not_matched;

			if (is_seqval)
			  lcollseq = cold;
			else
			  lcollseq = __collseq_table_lookup (collseq, cold);
# else
			fcollseq = collseq[fn];
			lcollseq = is_seqval ? cold : collseq[(UCHAR) cold];
# endif

			is_seqval = false;
			if (cend == L_('[') && *p == L_('.'))
			  {
			    uint32_t nrules =
			      _NL_CURRENT_WORD (LC_COLLATE,
						_NL_COLLATE_NRULES);
			    const CHAR *startp = p;
			    size_t c1 = 0;

			    while (1)
			      {
				c = *++p;
				if (c == L_('.') && p[1] == L_(']'))
				  {
				    p += 2;
				    break;
				  }
				if (c == '\0')
				  return FNM_NOMATCH;
				++c1;
			      }

			    if (nrules == 0)
			      {
				/* There are no names defined in the
				   collation data.  Therefore we only
				   accept the trivial names consisting
				   of the character itself.  */
				if (c1 != 1)
				  return FNM_NOMATCH;

				cend = startp[1];
			      }
			    else
			      {
				int32_t table_size;
				const int32_t *symb_table;
# ifdef WIDE_CHAR_VERSION
				char str[c1];
				size_t strcnt;
# else
#  define str (startp + 1)
# endif
				const unsigned char *extra;
				int32_t idx;
				int32_t elem;
				int32_t second;
				int32_t hash;

# ifdef WIDE_CHAR_VERSION
				/* We have to convert the name to a single-byte
				   string.  This is possible since the names
				   consist of ASCII characters and the internal
				   representation is UCS4.  */
				for (strcnt = 0; strcnt < c1; ++strcnt)
				  str[strcnt] = startp[1 + strcnt];
# endif

				table_size =
				  _NL_CURRENT_WORD (LC_COLLATE,
						    _NL_COLLATE_SYMB_HASH_SIZEMB);
				symb_table = (const int32_t *)
				  _NL_CURRENT (LC_COLLATE,
					       _NL_COLLATE_SYMB_TABLEMB);
				extra = (const unsigned char *)
				  _NL_CURRENT (LC_COLLATE,
					       _NL_COLLATE_SYMB_EXTRAMB);

				/* Locate the character in the hashing
                                   table.  */
				hash = elem_hash (str, c1);

				idx = 0;
				elem = hash % table_size;
				second = hash % (table_size - 2);
				while (symb_table[2 * elem] != 0)
				  {
				/* First compare the hashing value.  */
				    if (symb_table[2 * elem] == hash
					&& (c1
					    == extra[symb_table[2 * elem + 1]])
					&& memcmp (str,
						   &extra[symb_table[2 * elem + 1]
							 + 1], c1) == 0)
				      {
					/* Yep, this is the entry.  */
					idx = symb_table[2 * elem + 1];
					idx += 1 + extra[idx];
					break;
				      }

				    /* Next entry.  */
				    elem += second;
				  }

				if (symb_table[2 * elem] != 0)
				  {
				    /* Compare the byte sequence but only if
				       this is not part of a range.  */
# ifdef WIDE_CHAR_VERSION
				    int32_t *wextra;

				    idx += 1 + extra[idx];
				    /* Adjust for the alignment.  */
				    idx = (idx + 3) & ~4;

				    wextra = (int32_t *) &extra[idx + 4];
# endif
				    /* Get the collation sequence value.  */
				    is_seqval = true;
# ifdef WIDE_CHAR_VERSION
				    cend = wextra[1 + wextra[idx]];
# else
				    /* Adjust for the alignment.  */
				    idx += 1 + extra[idx];
				    idx = (idx + 3) & ~4;
				    cend = *((int32_t *) &extra[idx]);
# endif
				  }
				else if (symb_table[2 * elem] != 0 && c1 == 1)
				  {
				    cend = str[0];
				    c = *p++;
				  }
				else
				  return FNM_NOMATCH;
			      }
# undef str
			  }
			else
			  {
			    if (!(flags & FNM_NOESCAPE) && cend == L_('\\'))
			      cend = *p++;
			    if (cend == L_('\0'))
			      return FNM_NOMATCH;
			    cend = FOLD (cend);
			  }

			/* XXX It is not entirely clear to me how to handle
			   characters which are not mentioned in the
			   collation specification.  */
			if (
# ifdef WIDE_CHAR_VERSION
			    lcollseq == 0xffffffff ||
# endif
			    lcollseq <= fcollseq)
			  {
			    /* We have to look at the upper bound.  */
			    uint32_t hcollseq;

			    if (is_seqval)
			      hcollseq = cend;
			    else
			      {
# ifdef WIDE_CHAR_VERSION
				hcollseq =
				  __collseq_table_lookup (collseq, cend);
				if (hcollseq == ~((uint32_t) 0))
				  {
				    /* Hum, no information about the upper
				       bound.  The matching succeeds if the
				       lower bound is matched exactly.  */
				    if (lcollseq != fcollseq)
				      goto range_not_matched;

				    goto matched;
				  }
# else
				hcollseq = collseq[cend];
# endif
			      }

			    if (lcollseq <= hcollseq && fcollseq <= hcollseq)
			      goto matched;
			  }
# ifdef WIDE_CHAR_VERSION
		      range_not_matched:
# endif
#else
			/* We use a boring value comparison of the character
			   values.  This is better than comparing using
			   `strcoll' since the latter would have surprising
			   and sometimes fatal consequences.  */
			UCHAR cend = *p++;

			if (!(flags & FNM_NOESCAPE) && cend == L_('\\'))
			  cend = *p++;
			if (cend == L_('\0'))
			  return FNM_NOMATCH;

			/* It is a range.  */
			if (cold <= fn && fn <= cend)
			  goto matched;
#endif

			c = *p++;
		      }
		  }

		if (c == L_(']'))
		  break;
	      }

	    if (!not)
	      return FNM_NOMATCH;
	    break;

	  matched:
	    /* Skip the rest of the [...] that already matched.  */
	    do
	      {
	      ignore_next:
		c = *p++;

		if (c == L_('\0'))
		  /* [... (unterminated) loses.  */
		  return FNM_NOMATCH;

		if (!(flags & FNM_NOESCAPE) && c == L_('\\'))
		  {
		    if (*p == L_('\0'))
		      return FNM_NOMATCH;
		    /* XXX 1003.2d11 is unclear if this is right.  */
		    ++p;
		  }
		else if (c == L_('[') && *p == L_(':'))
		  {
		    int c1 = 0;
		    const CHAR *startp = p;

		    while (1)
		      {
			c = *++p;
			if (++c1 == CHAR_CLASS_MAX_LENGTH)
			  return FNM_NOMATCH;

			if (*p == L_(':') && p[1] == L_(']'))
			  break;

			if (c < L_('a') || c >= L_('z'))
			  {
			    p = startp;
			    goto ignore_next;
			  }
		      }
		    p += 2;
		    c = *p++;
		  }
		else if (c == L_('[') && *p == L_('='))
		  {
		    c = *++p;
		    if (c == L_('\0'))
		      return FNM_NOMATCH;
		    c = *++p;
		    if (c != L_('=') || p[1] != L_(']'))
		      return FNM_NOMATCH;
		    p += 2;
		    c = *p++;
		  }
		else if (c == L_('[') && *p == L_('.'))
		  {
		    ++p;
		    while (1)
		      {
			c = *++p;
			if (c == '\0')
			  return FNM_NOMATCH;

			if (*p == L_('.') && p[1] == L_(']'))
			  break;
		      }
		    p += 2;
		    c = *p++;
		  }
	      }
	    while (c != L_(']'));
	    if (not)
	      return FNM_NOMATCH;
	  }
	  break;

	case L_('+'):
	case L_('@'):
	case L_('!'):
	  if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(')
	    {
	      int res;

	      res = EXT (c, p, n, string_end, no_leading_period, flags);
	      if (res != -1)
		return res;
	    }
	  goto normal_match;

	case L_('/'):
	  if (NO_LEADING_PERIOD (flags))
	    {
	      if (n == string_end || c != (UCHAR) *n)
		return FNM_NOMATCH;

	      new_no_leading_period = true;
	      break;
	    }
	  /* FALLTHROUGH */
	default:
	normal_match:
	  if (n == string_end || c != FOLD ((UCHAR) *n))
	    return FNM_NOMATCH;
	}

      no_leading_period = new_no_leading_period;
      ++n;
    }

  if (n == string_end)
    return 0;

  if ((flags & FNM_LEADING_DIR) && n != string_end && *n == L_('/'))
    /* The FNM_LEADING_DIR flag says that "foo*" matches "foobar/frobozz".  */
    return 0;

  return FNM_NOMATCH;
}
Beispiel #28
0
void
nsMsgKeySet::test_adder (void)
{
    const char *string;
    nsMsgKeySet *set;
    char *s;
    PRInt32 i;

    START("0-70,72-99,105,107,110-111,117-200");

    FROB(205, PR_TRUE);
    FROB(206, PR_TRUE);
    FROB(207, PR_TRUE);
    FROB(208, PR_TRUE);
    FROB(208, PR_TRUE);
    FROB(109, PR_TRUE);
    FROB(72, PR_TRUE);

    FROB(205, PR_FALSE);
    FROB(206, PR_FALSE);
    FROB(207, PR_FALSE);
    FROB(208, PR_FALSE);
    FROB(208, PR_FALSE);
    FROB(109, PR_FALSE);
    FROB(72, PR_FALSE);

    FROB(72, PR_TRUE);
    FROB(109, PR_TRUE);
    FROB(208, PR_TRUE);
    FROB(208, PR_TRUE);
    FROB(207, PR_TRUE);
    FROB(206, PR_TRUE);
    FROB(205, PR_TRUE);

    FROB(205, PR_FALSE);
    FROB(206, PR_FALSE);
    FROB(207, PR_FALSE);
    FROB(208, PR_FALSE);
    FROB(208, PR_FALSE);
    FROB(109, PR_FALSE);
    FROB(72, PR_FALSE);

    FROB(100, PR_TRUE);
    FROB(101, PR_TRUE);
    FROB(102, PR_TRUE);
    FROB(103, PR_TRUE);
    FROB(106, PR_TRUE);
    FROB(104, PR_TRUE);
    FROB(109, PR_TRUE);
    FROB(108, PR_TRUE);
    END();

    START("1-6");
    FROB(7, PR_FALSE);
    END();
    START("1-6");
    FROB(6, PR_FALSE);
    END();
    START("1-6");
    FROB(5, PR_FALSE);
    END();
    START("1-6");
    FROB(4, PR_FALSE);
    END();
    START("1-6");
    FROB(3, PR_FALSE);
    END();
    START("1-6");
    FROB(2, PR_FALSE);
    END();
    START("1-6");
    FROB(1, PR_FALSE);
    END();
    START("1-6");
    FROB(0, PR_FALSE);
    END();

    START("1-3");
    FROB(1, PR_FALSE);
    END();
    START("1-3");
    FROB(2, PR_FALSE);
    END();
    START("1-3");
    FROB(3, PR_FALSE);
    END();

    START("1,3,5-7,9,10");
    FROB(5, PR_FALSE);
    END();
    START("1,3,5-7,9,10");
    FROB(6, PR_FALSE);
    END();
    START("1,3,5-7,9,10");
    FROB(7, PR_FALSE);
    FROB(7, PR_TRUE);
    FROB(8, PR_TRUE);
    FROB (4, PR_TRUE);
    FROB (2, PR_FALSE);
    FROB (2, PR_TRUE);

    FROB (4, PR_FALSE);
    FROB (5, PR_FALSE);
    FROB (6, PR_FALSE);
    FROB (7, PR_FALSE);
    FROB (8, PR_FALSE);
    FROB (9, PR_FALSE);
    FROB (10, PR_FALSE);
    FROB (3, PR_FALSE);
    FROB (2, PR_FALSE);
    FROB (1, PR_FALSE);
    FROB (1, PR_FALSE);
    FROB (0, PR_FALSE);
    END();
}
Beispiel #29
0
/*							HTVMSBrowseDir()
**
**	This function generates a directory listing as an HTML-object
**	for local file URL's.  It assumes the first two elements of
**	of the path are a device followed by a directory:
**
**		file://localhost/device/directory[/[foo]]
**
**	Will not accept 000000 as a directory name.
**	Will offer links to parent through the top directory, unless
**	a terminal slash was included in the calling URL.
**
**	Returns HT_LOADED on success, HTLoadError() messages on error.
**
**	Developed for Lynx by Foteos Macrides ([email protected]).
*/
PUBLIC int HTVMSBrowseDir ARGS4(
	CONST char *,		address,
	HTParentAnchor *,	anchor,
	HTFormat,		format_out,
	HTStream *,		sink
)
{
    HTStructured* target;
    HTStructuredClass targetClass;
    char *pathname = HTParse(address, "", PARSE_PATH + PARSE_PUNCTUATION);
    char *tail = NULL;
    char *title = NULL;
    char *header = NULL;
    char *parent = NULL;
    char *relative = NULL;
    char *cp, *cp1;
    int  pathend, len;
    DIR *dp;
    struct stat file_info;
    time_t NowTime;
    static char ThisYear[8];
    VMSEntryInfo *entry_info = 0;
    char string_buffer[64];

    HTUnEscape(pathname);
    CTRACE((tfp,"HTVMSBrowseDir: Browsing `%s\'\n", pathname));

    /*
     *  Require at least two elements (presumably a device and directory)
     *  and disallow the device root (000000 directory).  Symbolic paths
     *  (e.g., sys$help) should have been translated and expanded (e.g.,
     *  to /sys$sysroot/syshlp) before calling this routine.
     */
    if (((*pathname != '/') ||
	 (cp = strchr(pathname+1, '/')) == NULL ||
	 *(cp + 1) == '\0' ||
	 0 == strncmp((cp + 1), "000000", 6)) ||
	(dp = HTVMSopendir(pathname)) == NULL) {
	FREE(pathname);
	return HTLoadError(sink, 403, COULD_NOT_ACCESS_DIR);
    }

    /*
     *  Set up the output stream.
     */
    _HTProgress (BUILDING_DIR_LIST);
    if (UCLYhndl_HTFile_for_unspec >= 0) {
	HTAnchor_setUCInfoStage(anchor,
				UCLYhndl_HTFile_for_unspec,
				UCT_STAGE_PARSER,
				UCT_SETBY_DEFAULT);
    }
    target = HTML_new(anchor, format_out, sink);
    targetClass = *(target->isa);

    /*
     *  Set up the offset string of the anchor reference,
     *  and strings for the title and header.
     */
    cp = strrchr(pathname, '/');  /* find lastslash */
    StrAllocCopy(tail, (cp+1)); /* take slash off the beginning */
    if (*tail != '\0') {
	StrAllocCopy(title, tail);
	*cp = '\0';
	if ((cp1=strrchr(pathname, '/')) != NULL &&
	    cp1 != pathname &&
	    strncmp((cp1+1), "000000", 6))
	    StrAllocCopy(parent, (cp1+1));
	*cp = '/';
    } else {
	pathname[strlen(pathname)-1] = '\0';
	cp = strrchr(pathname, '/');
	StrAllocCopy(title, (cp+1));
	pathname[strlen(pathname)] = '/';
    }
    StrAllocCopy(header, pathname);

    /*
     *  Initialize path name for HTStat().
     */
    pathend = strlen(pathname);
    if (*(pathname+pathend-1) != '/') {
	StrAllocCat(pathname, "/");
	pathend++;
    }

    /*
     *  Output the title and header.
     */
    START(HTML_HTML);
    PUTC('\n');
    START(HTML_HEAD);
    PUTC('\n');
    HTUnEscape(title);
    START(HTML_TITLE);
    PUTS(title);
    PUTS(" directory");
    END(HTML_TITLE);
    PUTC('\n');
    FREE(title);
    END(HTML_HEAD);
    PUTC('\n');
    START(HTML_BODY);
    PUTC('\n');
    HTUnEscape(header);
    START(HTML_H1);
    PUTS(header);
    END(HTML_H1);
    PUTC('\n');
    if (HTDirReadme == HT_DIR_README_TOP) {
	FILE * fp;
	if (header[strlen(header)-1] != '/')
	    StrAllocCat(header, "/");
	StrAllocCat(header, HT_DIR_README_FILE);
	if ((fp = fopen(header,	 "r")) != NULL) {
	    START(HTML_PRE);
	    for(;;) {
		char c = fgetc(fp);
		if (c == (char)EOF)
		    break;
#ifdef NOTDEFINED
		switch (c) {
		    case '&':
		    case '<':
		    case '>':
			PUTC('&');
			PUTC('#');
			PUTC((char)(c / 10));
			PUTC((char) (c % 10));
			PUTC(';');
			break;
		    default:
			PUTC(c);
		}
#else
		PUTC(c);
#endif /* NOTDEFINED */
	    }
	    END(HTML_PRE);
	    fclose(fp);
	}
    }
    FREE(header);
    if (parent) {
	HTSprintf0(&relative, "%s/..", tail);
	HTStartAnchor(target, "", relative);
	PUTS("Up to ");
	HTUnEscape(parent);
	PUTS(parent);
	END(HTML_A);
	START(HTML_P);
	PUTC('\n');
	FREE(relative);
	FREE(parent);
    }

    /*
     *  Set up the date comparison.
     */
    NowTime = time(NULL);
    strcpy(ThisYear, (char *)ctime(&NowTime)+20);
    ThisYear[4] = '\0';

    /*
     * Now, generate the Btree and put it out to the output stream.
     */
    {
	char dottest = 2;	/* To avoid two strcmp() each time */
	STRUCT_DIRENT *dirbuf;
	HTBTree *bt;

	/* Set up sort key and initialize BTree */
	bt = HTBTree_new((HTComparer) compare_VMSEntryInfo_structs);

	/* Build tree */
	while ((dirbuf = HTVMSreaddir(dp))) {
	    HTAtom *encoding = NULL;
	    HTFormat format;

	    /* Skip if not used */
	    if (!dirbuf->d_ino)	{
		continue;
	    }

	    /* Current and parent directories are never shown in list */
	    if (dottest && (!strcmp(dirbuf->d_name, ".") ||
			    !strcmp(dirbuf->d_name, ".."))) {
		dottest--;
		continue;
	    }

	    /* Don't show the selective enabling file
	     * unless version numbers are included */
	    if (!strcasecomp(dirbuf->d_name, HT_DIR_ENABLE_FILE)) {
		continue;
	    }

	    /* Skip files beginning with a dot? */
	    if ((no_dotfiles || !show_dotfiles) && *dirbuf->d_name == '.') {
		continue;
	    }

	    /* OK, make an lstat() and get a key ready. */
	    *(pathname+pathend) = '\0';
	    StrAllocCat(pathname, dirbuf->d_name);
	    if (HTStat(pathname, &file_info)) {
		/* for VMS the failure here means the file is not readable...
		   we however continue to browse through the directory... */
		continue;
	    }
	    entry_info = (VMSEntryInfo *)malloc(sizeof(VMSEntryInfo));
	    if (entry_info == NULL)
		outofmem(__FILE__, "HTVMSBrowseDir");
	    entry_info->type = 0;
	    entry_info->size = 0;
	    entry_info->date = 0;
	    entry_info->filename = 0;
	    entry_info->display = TRUE;

	    /* Get the type */
	    format = HTFileFormat(dirbuf->d_name, &encoding,
				  (CONST char **)&cp);
	    if (!cp) {
		if(!strncmp(HTAtom_name(format), "application",11))
		{
		    cp = HTAtom_name(format) + 12;
		    if(!strncmp(cp,"x-", 2))
			cp += 2;
		}
		else
		    cp = HTAtom_name(format);
	    }
	    StrAllocCopy(entry_info->type, cp);

	    StrAllocCopy(entry_info->filename, dirbuf->d_name);
	    if (S_ISDIR(file_info.st_mode)) {
		/* strip .DIR part... */
		char *dot;
		dot = strstr(entry_info->filename, ".DIR");
		if (dot)
		   *dot = '\0';
		LYLowerCase(entry_info->filename);
		StrAllocCopy(entry_info->type, "Directory");
	    } else {
		if ((cp = strstr(entry_info->filename, "READ")) == NULL) {
		    cp = entry_info->filename;
		} else {
		    cp += 4;
		    if (!strncmp(cp, "ME", 2)) {
			cp += 2;
			while (cp && *cp && *cp != '.') {
			    cp++;
			}
		    } else if (!strncmp(cp, ".ME", 3)) {
			cp = (entry_info->filename +
			      strlen(entry_info->filename));
		    } else {
			cp = entry_info->filename;
		    }
		}
		LYLowerCase(cp);
		if (((len = strlen(entry_info->filename)) > 2) &&
		    entry_info->filename[len-1] == 'z') {
		    if (entry_info->filename[len-2] == '.' ||
			entry_info->filename[len-2] == '_')
			entry_info->filename[len-1] = 'Z';
		}
	    }

	    /* Get the date */
	    {
		char *t = (char *)ctime((CONST time_t *)&file_info.st_ctime);
		*(t+24) = '\0';

		StrAllocCopy(entry_info->date, (t+4));
		*((entry_info->date)+7) = '\0';
		if ((atoi((t+19))) < atoi(ThisYear))
		    StrAllocCat(entry_info->date,  (t+19));
		else {
		    StrAllocCat(entry_info->date, (t+11));
		    *((entry_info->date)+12) = '\0';
		}
	    }

	    /* Get the size */
	    if (!S_ISDIR(file_info.st_mode))
		entry_info->size = (unsigned int)file_info.st_size;
	    else
		entry_info->size = 0;

	    /* Now, update the BTree etc. */
	    if(entry_info->display)
	      {
		 CTRACE((tfp,"Adding file to BTree: %s\n",
						      entry_info->filename));
		 HTBTree_add(bt, entry_info);
	      }

	} /* End while HTVMSreaddir() */

	FREE(pathname);
	HTVMSclosedir(dp);

	START(HTML_PRE);
	/*
	 * Run through the BTree printing out in order
	 */
	{
	    HTBTElement * ele;
	    int i;
	    for (ele = HTBTree_next(bt, NULL);
		 ele != NULL;
		 ele = HTBTree_next(bt, ele))
	    {
		entry_info = (VMSEntryInfo *)HTBTree_object(ele);

		/* Output the date */
		if(entry_info->date)
		       {
			     PUTS(entry_info->date);
			     PUTS("  ");
		       }
		else
			PUTS("     * ");

		/* Output the type */
		if(entry_info->type)
		  {
		    for(i = 0; entry_info->type[i] != '\0' && i < 15; i++)
			PUTC(entry_info->type[i]);
		    for(; i < 17; i++)
			PUTC(' ');

		  }

		/* Output the link for the name */
		HTDirEntry(target, tail, entry_info->filename);
		PUTS(entry_info->filename);
		END(HTML_A);

		/* Output the size */
		if(entry_info->size)
		  {
			  if(entry_info->size < 1024)
			      sprintf(string_buffer,"  %d bytes",
							entry_info->size);
			  else
			      sprintf(string_buffer,"  %dKb",
							entry_info->size/1024);
			  PUTS(string_buffer);
		  }

		PUTC('\n'); /* end of this entry */

		free_VMSEntryInfo_contents(entry_info);
	    }
	}

	HTBTreeAndObject_free(bt);

    } /* End of both BTree loops */

    /*
     *  Complete the output stream.
     */
    END(HTML_PRE);
    PUTC('\n');
    END(HTML_BODY);
    PUTC('\n');
    END(HTML_HTML);
    PUTC('\n');
    FREE(tail);
    FREE_TARGET;

    return HT_LOADED;

} /* End of directory reading section */
Beispiel #30
0
static void
test_write_nesting(void)
{
	struct spdk_json_write_ctx *w;

	BEGIN();
	VAL_ARRAY_BEGIN();
	VAL_ARRAY_BEGIN();
	VAL_ARRAY_END();
	VAL_ARRAY_END();
	END("[[]]");

	BEGIN();
	VAL_ARRAY_BEGIN();
	VAL_ARRAY_BEGIN();
	VAL_ARRAY_BEGIN();
	VAL_ARRAY_END();
	VAL_ARRAY_END();
	VAL_ARRAY_END();
	END("[[[]]]");

	BEGIN();
	VAL_ARRAY_BEGIN();
	VAL_INT32(0);
	VAL_ARRAY_BEGIN();
	VAL_ARRAY_END();
	VAL_ARRAY_END();
	END("[0,[]]");

	BEGIN();
	VAL_ARRAY_BEGIN();
	VAL_ARRAY_BEGIN();
	VAL_ARRAY_END();
	VAL_INT32(0);
	VAL_ARRAY_END();
	END("[[],0]");

	BEGIN();
	VAL_ARRAY_BEGIN();
	VAL_INT32(0);
	VAL_ARRAY_BEGIN();
	VAL_INT32(1);
	VAL_ARRAY_END();
	VAL_INT32(2);
	VAL_ARRAY_END();
	END("[0,[1],2]");

	BEGIN();
	VAL_ARRAY_BEGIN();
	VAL_INT32(0);
	VAL_INT32(1);
	VAL_ARRAY_BEGIN();
	VAL_INT32(2);
	VAL_INT32(3);
	VAL_ARRAY_END();
	VAL_INT32(4);
	VAL_INT32(5);
	VAL_ARRAY_END();
	END("[0,1,[2,3],4,5]");

	BEGIN();
	VAL_OBJECT_BEGIN();
	VAL_NAME("a");
	VAL_OBJECT_BEGIN();
	VAL_OBJECT_END();
	VAL_OBJECT_END();
	END("{\"a\":{}}");

	BEGIN();
	VAL_OBJECT_BEGIN();
	VAL_NAME("a");
	VAL_OBJECT_BEGIN();
	VAL_NAME("b");
	VAL_INT32(0);
	VAL_OBJECT_END();
	VAL_OBJECT_END();
	END("{\"a\":{\"b\":0}}");

	BEGIN();
	VAL_OBJECT_BEGIN();
	VAL_NAME("a");
	VAL_ARRAY_BEGIN();
	VAL_INT32(0);
	VAL_ARRAY_END();
	VAL_OBJECT_END();
	END("{\"a\":[0]}");

	BEGIN();
	VAL_ARRAY_BEGIN();
	VAL_OBJECT_BEGIN();
	VAL_NAME("a");
	VAL_INT32(0);
	VAL_OBJECT_END();
	VAL_ARRAY_END();
	END("[{\"a\":0}]");

	BEGIN();
	VAL_ARRAY_BEGIN();
	VAL_OBJECT_BEGIN();
	VAL_NAME("a");
	VAL_OBJECT_BEGIN();
	VAL_NAME("b");
	VAL_ARRAY_BEGIN();
	VAL_OBJECT_BEGIN();
	VAL_NAME("c");
	VAL_INT32(1);
	VAL_OBJECT_END();
	VAL_INT32(2);
	VAL_ARRAY_END();
	VAL_NAME("d");
	VAL_INT32(3);
	VAL_OBJECT_END();
	VAL_NAME("e");
	VAL_INT32(4);
	VAL_OBJECT_END();
	VAL_INT32(5);
	VAL_ARRAY_END();
	END("[{\"a\":{\"b\":[{\"c\":1},2],\"d\":3},\"e\":4},5]");

	/* Examples from RFC 7159 */
	BEGIN();
	VAL_OBJECT_BEGIN();
	VAL_NAME("Image");
	VAL_OBJECT_BEGIN();
	VAL_NAME("Width");
	VAL_INT32(800);
	VAL_NAME("Height");
	VAL_INT32(600);
	VAL_NAME("Title");
	VAL_STRING("View from 15th Floor");
	VAL_NAME("Thumbnail");
	VAL_OBJECT_BEGIN();
	VAL_NAME("Url");
	VAL_STRING("http://www.example.com/image/481989943");
	VAL_NAME("Height");
	VAL_INT32(125);
	VAL_NAME("Width");
	VAL_INT32(100);
	VAL_OBJECT_END();
	VAL_NAME("Animated");
	VAL_FALSE();
	VAL_NAME("IDs");
	VAL_ARRAY_BEGIN();
	VAL_INT32(116);
	VAL_INT32(943);
	VAL_INT32(234);
	VAL_INT32(38793);
	VAL_ARRAY_END();
	VAL_OBJECT_END();
	VAL_OBJECT_END();
	END(
		"{\"Image\":"
		"{"
		"\"Width\":800,"
		"\"Height\":600,"
		"\"Title\":\"View from 15th Floor\","
		"\"Thumbnail\":{"
		"\"Url\":\"http://www.example.com/image/481989943\","
		"\"Height\":125,"
		"\"Width\":100"
		"},"
		"\"Animated\":false,"
		"\"IDs\":[116,943,234,38793]"
		"}"
		"}");
}