예제 #1
0
void sys_errpack(int pri, char *fn, int ln, int en, struct sockaddr_in *peer,
		 void *pack, unsigned len, char *fmt, ...) {
  bstring bt = bfromcstr("");
  bstring bt2 = bfromcstr("");
  int sz;
  int n;
  
  bvformata(sz, bt, fmt, fmt);
  if (sz == BSTR_OK) {

    bassignformat(bt2, ". Packet from %s:%u, length: %d, content:",
		  inet_ntoa(peer->sin_addr),
		  ntohs(peer->sin_port),
		  len);
    
    bconcat(bt, bt2);
    
    for(n=0; n < len; n++) {
      bassignformat(bt, " %02hhx", ((unsigned char*)pack)[n]);
      bconcat(bt, bt2);
    }
  
    if (1) {
      fprintf(stderr, "%s: %d: %d (%s) %s", fn, ln, en, strerror(en), bt->data);
    } else {
      if (en)
	syslog(pri, "%s: %d: %d (%s) %s", fn, ln, en, strerror(en), bt->data);
      else
	syslog(pri, "%s: %d: %s", fn, ln, bt->data);
    }
  }

  bdestroy(bt);
  bdestroy(bt2);
}
예제 #2
0
파일: m2sh.c 프로젝트: duaneg/mongrel2
void taskmain(int argc, char *argv[])
{
    dbg_set_log(stderr);
    int i = 0;

    bstring arguments = bfromcstr(argv[0]);

    for(i = 1; i < argc; i++) {
        bstring a = bfromcstr(argv[i]);

        // compensate for quotes getting taken off by the shell
        // TODO: also need to escape " to bring back that
        if(bstrchr(a, ' ') != -1) {
            bcatcstr(arguments, " \"");
            bconcat(arguments, a);
            bcatcstr(arguments, "\"");
        } else {
            bcatcstr(arguments, " ");
            bconcat(arguments, a);
        }

        bdestroy(a);
    }

    debug("RUNNING: %s", bdata(arguments));
    taskexitall(Command_run(arguments));
}
예제 #3
0
void mongrel2_ws_debug(bstring data){
    if(data == NULL){
        fprintf(stderr, "cannot debug null data");
        return;
    }
    bstring single_hex = NULL;
    bstring single_char = NULL;

    bstring hex_dump = bfromcstr("");
    bstring san_dump = bfromcstr("");
    char* buf = calloc(4,sizeof(char));
    if(buf == NULL || data == NULL){
        fprintf(stderr, "debug could not allocate a conversion buffer");
        goto exit;
    }

    unsigned char* raw_char;
    unsigned char* cstr = (unsigned char*)bdata(data);
    if(cstr == NULL){
        goto exit;
        return;
    }

    for(int i=0; i<blength(data); i++){
        snprintf(buf,4,"%02X ",cstr[i]);
        single_hex = bfromcstr(buf);
        bconcat(hex_dump,single_hex);
        bdestroy(single_hex);

        raw_char = &cstr[i];
        if(*raw_char == START_CHAR){
            buf[0] = '@';
        } else if(*raw_char == TERM_CHAR){
            buf[0] = '@';
        } else {
            buf[0] = *raw_char;
        }
        buf[1] = '\0';
        
        single_char = bfromcstr(buf);
        bconcat(san_dump,single_char);
        bdestroy(single_char);
    }
    fprintf(stdout, "########################\n");
    fprintf(stdout, "SANITIZED DATA\n%.*s\n",blength(san_dump), bdata(san_dump));
    fprintf(stdout, "DEBUGGER SEZ\n%.*s\n", blength(hex_dump), bdata(hex_dump));
    fprintf(stdout, "########################\n");

    exit:
    bdestroy(san_dump);
    bdestroy(hex_dump);
    free(buf);

    return;
}
예제 #4
0
bool do_install(CURL* curl, bstring name)
{
    FILE* fp;
    CURLcode res;
    long httpcode = 0;
    struct stat buffer;
    bstring url = bfromcstr("http://dms.dcputoolcha.in/modules/download?name=");
    bstring modpath = osutil_getmodulepath();

    // Append the file name.
    bconchar(modpath, '/');
    bconcat(modpath, name);
    bcatcstr(modpath, ".lua");
    bconcat(url, name);
    bcatcstr(url, ".lua");

    // Check to see if the module is already installed.
    if (stat(modpath->data, &buffer) == 0)
    {
        if (unlink(modpath->data) == 0)
            printd(LEVEL_WARNING, "removed existing %s module.\n", name->data);
        else
        {
            printd(LEVEL_ERROR, "unable to remove existing %s module.\n", name->data);
            return 1;
        }
    }

    // Open the file and do the cURL transfer.
    printd(LEVEL_DEFAULT, "querying module repository...\n");
    fp = fopen(modpath->data, "wb");
    curl_easy_setopt(curl, CURLOPT_URL, url->data);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
    res = curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &httpcode);
    if (res != 0 && httpcode != 200)
    {
        bdestroy(url);
        bdestroy(name);
        bdestroy(modpath);
        printd(LEVEL_ERROR, "curl failed with error code %i, HTTP error code %i.\n", res, httpcode);
        return 1;
    }
    fclose(fp);
    printd(LEVEL_DEFAULT, "module %s installed.\n", name->data);

    return 0;
}
예제 #5
0
char *test_different_functions() {
  // create + length
  bstring string1 = bfromcstr("string");
  mu_assert_equal(6, blength(string1));

  // bassign, biseq
  bstring string2 = bfromcstr("foo");
  bassign(string2, string1);
  mu_assert(strcmp(bdata(string1), bdata(string2)) == 0, "both strings should be equal");
  mu_assert(biseq(string1, string2) == 1, "both strings should be equal");

  // bconcat
  bstring string2 = bfromcstr("foo");
  string1 = bfromcstr("Hello");
  string2 = bfromcstr(", World!");
  bconcat(string1, string2);
  mu_assert(strcmp("Hello, World!", bdata(string1)) == 0, "returned string not as expected");

  // bsplit
  string1 = bfromcstr("foo, bar, baz");
  struct bstrList *words;
  words = bsplit(string1, ',');
  mu_assert(strcmp("foo", bdata(words->entry[0])) == 0, "returned string not as expected");

  return NULL;
}
예제 #6
0
static bstring
ssh_arg_to_privkey(const bstring argkey)
{
	struct tagbstring tmp;
	bstring privkey;
	int i, len;

	/*
	 * A simple routine to convert from the private key format suitable for
	 * inclusion in a Torrc back to PEM.
	 */

	len = strlen(OBFSPROXYSSH_PEM_HDR) + blength(argkey) +
		blength(argkey) /64 + 1 + strlen(OBFSPROXYSSH_PEM_FTR);

	privkey = bfromcstralloc(len, OBFSPROXYSSH_PEM_HDR);

	for (i = 0; i < blength(argkey); i += 64) {
		bmid2tbstr(tmp, argkey, i, 64);
		bconcat(privkey, &tmp);
		bconchar(privkey, '\n');
	}

	bcatcstr(privkey, OBFSPROXYSSH_PEM_FTR);

	return privkey;
}
예제 #7
0
파일: bootstrap.c 프로젝트: txus/terrorvm
void
State_bootstrap(STATE)
{
  DArray *filenames = kernel_files(state);
  int count = DArray_count(filenames);

  // Expose toplevel constants
  expose_VM(state, state->lobby);

  int reenable_debugger = 0;

  // Disable debugger while loading kernel files
  if(Debug) {
    reenable_debugger = 1;
    Debug = 0;
  }

  // Load all files.
  for(int i=0; i < count; i++) {
    bstring filename = (bstring)DArray_at(filenames, i);
    bstring path = bfromcstr("kernel/");
    bconcat(path, filename);
    Primitive_require(state, String_new(state, bdata(path)), NULL, NULL);

    bdestroy(path);
    bdestroy(filename);
  }

  DArray_destroy(filenames);

  // Reenable debugger if needed
  if(reenable_debugger) Debug = 1;
}
예제 #8
0
bool do_uninstall(CURL* curl, bstring name)
{
    bstring modpath = osutil_getmodulepath();
    struct stat buffer;

    // Append the file name.
    bconchar(modpath, '/');
    bconcat(modpath, name);
    bcatcstr(modpath, ".lua");

    // Check to see if the module is installed.
    if (stat(modpath->data, &buffer) == 0)
    {
        if (unlink(modpath->data) == 0)
            printd(LEVEL_DEFAULT, "removed existing %s module.\n", name->data);
        else
        {
            printd(LEVEL_ERROR, "unable to remove existing %s module.\n", name->data);
            return 1;
        }
    }
    else
        printd(LEVEL_WARNING, "module %s is not installed.\n", name->data);

    return 0;
}
예제 #9
0
bstring build_oauth_header(bKeyValues *keyvalues)
{
    bstring buffer = bfromcstr("Authorization: OAuth ");
    int i = 0;
    int first = 1;
    
    for(i = 0; i < keyvalues->qty; i++) {
        if(first) {
            first = 0;
        } else {
            bconchar(buffer, ',');
        }
        bconcat(buffer, keyvalues->entry[i].key);
        bcatcstr(buffer, "=\"");
        bconcat(buffer, keyvalues->entry[i].value);
        bconchar(buffer, '\"');
    }
    return buffer;
}
예제 #10
0
static inline void B(bstring headers, const bstring k, const bstring v, int *first)
{
    if(v)
    {
        if(*first) {
            bcatcstr(headers, "\"");
            *first = 0;
        } else {
            bcatcstr(headers, ",\"");
        }
        bconcat(headers, k);
        bconcat(headers, &JSON_OBJSEP);

        bstring vstr = json_escape(v);
        bconcat(headers, vstr);
        bcatcstr(headers, "\"");

        bdestroy(vstr);
    }
}
예제 #11
0
파일: node.c 프로젝트: dardevelin/utu
void Node_catbstr(bstring str, Node *d, char sep, int follow_sibs) 
{
  int rc = 0;

  assert_not(str, NULL);

  if(d == NULL) return;

  if(d->sibling != NULL && follow_sibs) {
    Node_catbstr(str, d->sibling, sep, follow_sibs);
  }

  if(d->type == TYPE_GROUP) {
    rc = bformata(str, "[%c", sep);
    assert(rc == BSTR_OK);
  }

  if(d->child != NULL) {
    // we always follow siblings on the children
    Node_catbstr(str, d->child, sep, 1);
  }

  switch(d->type) {
    case TYPE_BLOB:
      bformata(str, "'%zu:" , blength(d->value.string));
      bconcat(str, d->value.string);
      bformata(str, "\'%c", sep);
      break;
    case TYPE_STRING:
      bformata(str, "\"%s\"%c" , bdata(d->value.string), sep);
      break;
    case TYPE_NUMBER:
      bformata(str, "%llu%c", d->value.number, sep);
      break;
    case TYPE_FLOAT:
      bformata(str, "%f%c", d->value.floating, sep);
      break;
    case TYPE_GROUP: 
      if(!d->name || bchar(d->name, 0) == '@') {
        rc = bformata(str, "]%c", sep);
        assert(rc == BSTR_OK);
      }
      break;
    case TYPE_INVALID: // fallthrough
    default:
      assert(!"invalid type for node");
      break;
  }

  if(d->name != NULL) {
    rc = bformata(str, "%s%c", bdata(d->name), sep); 
    assert(rc == BSTR_OK);
  }
}
예제 #12
0
파일: file_utils.c 프로젝트: txus/terrorvm
bstring
resolve_path(STATE, bstring path)
{
  char *absolute_path = malloc(PATH_MAX);
	bstring h = executable_name(state->binary);
	struct bstrList *x = bsplit(h, '/');
	bdestroy(h);
	bstring slash = bfromcstr("/");
	x->qty--;
	h = bjoin(x, slash);
	x->qty++;
	bstrListDestroy(x);
	bconcat(h, slash);
	bconcat(h, path);
	bdestroy(slash);

  realpath(bdata(h), absolute_path);
  bstring bpath = bfromcstr(absolute_path);
  bdestroy(h);
  free(absolute_path);
  return bpath;
}
예제 #13
0
char *test_bconcat(void)
{
	bstring b0 = bfromcstr(test);
	bstring b1 = bfromcstr(test_1);

	mu_assert(bconcat(b0, b1) == BSTR_OK, "Failed to bconcat().");
	mu_assert(strncmp((const char *)b0->data, test, strlen(test)) == 0, "Wrong original part afetr bconcat().");
	mu_assert(strncmp((const char *)b0->data + strlen(test), test_1, strlen(test_1)) == 0, "Wrong concate part afetr bconcat().");
	mu_assert(b0->slen == (int)strlen(test) + (int)strlen(test_1), "Wrong concat string length after bconcat().");
	
	mu_assert(bdestroy(b0) == BSTR_OK, "Failed to bdestroy() afetr bconcat().");
	mu_assert(bdestroy(b1) == BSTR_OK, "Failed to bdestroy() afetr bconcat().");
	return NULL;
}
예제 #14
0
bstring
alder_wordtable_kfmindex_toString(alder_wordtable_kfmindex_t *o,
                                  size_t pos)
{
    bstring bindexString =
    alder_wordtable_inedgedata_nodeDataString(o->inedgedata, pos);
    
    bstring bnodeString = alder_wordtable_kfmindex_nodeString(o,pos);
    
    bconcat(bindexString, bnodeString);
    
    size_t rho[4];
    for (int token = 0; token < 4; token++) {
        rho[token] = alder_wordtable_kfmindex_prevPos2(o,pos,token);
    }
    bstring brhoString = bformat(" %zu\t%zu\t%zu\t%zu", rho[0], rho[1], rho[2], rho[3]);
    bconcat(bindexString, brhoString);
    
    bdestroy(bnodeString);
    bdestroy(brhoString);
    
    return bindexString;
}
예제 #15
0
void concat_log_message(lua_State *L, bstring message) {
  
  int c = lua_gettop(L);
  
  bstring space = bfromcstr(" ");
  int i = 0;
  for (i = 0; i < c; i++) {
    const char *str = NULL;
    
    lua_pushvalue(L, 1);
    lua_remove(L, 1);
    
    if (lua_type(L, 1) == LUA_TSTRING) {
      str = lua_tostring(L, -1);
    } else {
      lua_getglobal(L, "tostring");
      lua_pushvalue(L, -2);
      lua_remove(L, -3);
      int rt = lua_pcall(L, 1, 1, 1);
      if (rt == 0) {
        str = lua_tostring(L, -1);
      } else {
        str = "<Could not convert arg to str>";
      }
    }
    
    bstring bstr = bfromcstr(str);
    if (i > 0) {
      bconcat(message, space);
    }
    bconcat(message, bstr);
    bdestroy(bstr);
    
    lua_pop(L, 1);
  }
  bdestroy(space);
}
예제 #16
0
파일: int_literal.c 프로젝트: dasfaha/sky
// Append the contents of the AST node to the string.
// 
// node - The node to dump.
// ret  - A pointer to the bstring to concatenate to.
//
// Return 0 if successful, otherwise returns -1.s
int qip_ast_int_literal_dump(qip_ast_node *node, bstring ret)
{
    check(node != NULL, "Node required");
    check(ret != NULL, "String required");
    
    bstring str = bformat("<int-literal value='%lld'>\n", node->int_literal.value);
    check_mem(str);
    check(bconcat(ret, str) == BSTR_OK, "Unable to append dump");

    return 0;

error:
    if(str != NULL) bdestroy(str);
    return -1;
}
예제 #17
0
파일: bstr_tests.c 프로젝트: wenzong/lab
char *test_bconcat() {
    bstring b_hello = bfromcstr("hello");
    bstring b_world = bfromcstr("world");

    int rc = bconcat(b_hello, b_world);
    mu_assert(rc == BSTR_OK, "bconcat should return BSTR_OK");

    bstring b_helloworld = bfromcstr("helloworld");

    mu_assert(biseq(b_hello, b_helloworld) == 1, "bconcat content different");

    bdestroy(b_hello);
    bdestroy(b_world);
    bdestroy(b_helloworld);
    return NULL;
}
예제 #18
0
파일: handler.c 프로젝트: ttuna/mongrel2
void Handler_notify_credits(Handler *handler, int id, int credits)
{
    void *socket = handler->send_socket;
    assert(socket && "Socket can't be NULL");
    tns_outbuf outbuf = {.buffer = NULL};
    bstring payload = NULL;

    if(handler->protocol == HANDLER_PROTO_TNET) {
        int header_start = tns_render_request_start(&outbuf);
        bstring creditsstr = bformat("%d", credits);
        tns_render_hash_pair(&outbuf, &HTTP_METHOD, &JSON_METHOD);
        tns_render_hash_pair(&outbuf, &DOWNLOAD_CREDITS, creditsstr);
        bdestroy(creditsstr);
        tns_outbuf_clamp(&outbuf, header_start);

        payload = bformat("%s %d @* %s%d:%s,",
                bdata(handler->send_ident), id,
                bdata(tns_outbuf_to_bstring(&outbuf)),
                blength(&CREDITS_MSG), bdata(&CREDITS_MSG));
    } else {
        bstring headers = bfromcstralloc(PAYLOAD_GUESS, "{");

        bcatcstr(headers, "\"METHOD\":\"JSON\",\"");
        bconcat(headers, &DOWNLOAD_CREDITS);
        bcatcstr(headers, "\":\"");
        bformata(headers, "%d", credits);
        bcatcstr(headers, "\"}");

        payload = bformat("%s %d @* %d:%s,%d:%s,",
                bdata(handler->send_ident), id,
                blength(headers), bdata(headers),
                blength(&CREDITS_MSG), bdata(&CREDITS_MSG));

        bdestroy(headers);
    }

    check(payload != NULL, "Failed to make the payload for credits.");

    if(Handler_deliver(socket, bdata(payload), blength(payload)) == -1) {
        log_err("Can't tell handler %d giving credits.", id);
    }

error: //fallthrough
    if(payload) free(payload);
    if(outbuf.buffer) free(outbuf.buffer);
}
예제 #19
0
파일: glsw.c 프로젝트: Nekrofage/qurp
const char* glswGetShaders(const char* combinedKeys)
{
	glswContext* gc = __glsw__Context;
	int tokenIndex=0;
	struct bstrList* tokens;
	bstring effectKeys;
	glswList* pCombinedEffect;	

	effectKeys = bfromcstr(combinedKeys);
	tokens = bsplit(effectKeys, '+');
	pCombinedEffect = gc->CombinedEffects;
    while (pCombinedEffect)
    {
		if (1 == biseq(pCombinedEffect->Key, effectKeys))
            break;
        pCombinedEffect = pCombinedEffect->Next;
    }
	if(!pCombinedEffect)
	{
		glswList* temp = gc->CombinedEffects;
		gc->CombinedEffects = (glswList*) calloc(sizeof(glswList), 1);
		if(gc->CombinedEffects)
		{
			gc->CombinedEffects->Key = bstrcpy(effectKeys);
			gc->CombinedEffects->Value = bfromcstr("");
			gc->CombinedEffects->Next = temp;
		
			for (tokenIndex = 0; tokenIndex < tokens->qty; tokenIndex++)
			{
				bstring token = tokens->entry[tokenIndex];
				bconcat(gc->CombinedEffects->Value, bfromcstr(glswGetShader(token->data)));
				//bdestroy(token);
			}
			bstrListDestroy(tokens);
			bdestroy(effectKeys);
			return (char*)gc->CombinedEffects->Value->data;
		}
		else
			return 0;
	}
	else
		return (char*)pCombinedEffect->Value->data;

	
}
예제 #20
0
static int chilli_sessions(bstring b) {
  struct dhcp_conn_t *conn = dhcp->firstusedconn;

  char *state = "<font color=green>Authorized</font>";

  bstring s = bfromcstr("");
  bcatcstr(b, "{\"service\":[{ \"");
  bcatcstr(b, getenv("CAP_table"));
  bcatcstr(b, "\":[ ");

  while (conn) {
    struct app_conn_t *appconn = (struct app_conn_t *)conn->peer;

    if (appconn && appconn->s_state.authenticated) {

    } else {
      state = "<font color=red>Redirect</font>";
    }

    bassignformat(s,
		  "{"
		  "\"state\":\"%s\","
		  "\"macAddress\":\"%.2X-%.2X-%.2X-%.2X-%.2X-%.2X\","
		  "\"ipAddress\":\"%s\",",
		  state,
		  conn->hismac[0], conn->hismac[1], conn->hismac[2],
		  conn->hismac[3], conn->hismac[4], conn->hismac[5],
		  inet_ntoa(conn->hisip)
		  );

    conn = conn->next;
    if (appconn) {
      session_json_params(&appconn->s_state, &appconn->s_params, s, 0);
      bcatcstr(s, ",");
      session_json_acct(&appconn->s_state, &appconn->s_params, s, 0);
    }
    bcatcstr(s, "},");
    bconcat(b, s);
  }

  bcatcstr(b, "]} ]}");
  return 0;
}
예제 #21
0
/* Description: Create a packet for sending data.
 * Author: Albin Severinson
 * Date: 07/03/15
 */
bstring create_data_frame(bstring payload)
{
  int rc = 0;
  unsigned char payload_length = blength(payload);
  assert(payload_length <= PACKET_DATA_SIZE && "Payload exceeded max size.");
  
  //Prepare packet
  bstring packet = bfromcstr("");

  //If it's a DATA frame, add the preable
  if(payload_length != 0){
    rc = binsertch(packet, 0, 1, preamble);
    check(rc == BSTR_OK, "Failed to insert preamble.");

    //Insert payload length
    rc = binsertch(packet, 1, 1, payload_length);
    check(rc == 0, "Failed to add package size.");
    debug("Preamble added");
  }
  else{
    //Insert payload length
    rc = binsertch(packet, 0, 1, payload_length);
    check(rc == 0, "Failed to add package size.");
  }

  //Concat with payload
  bconcat(packet, payload);

  //Cleanup payload
  bdestroy(payload);

  return packet;

 error:
  bdestroy(packet);
  return NULL;
  
}
예제 #22
0
파일: block.c 프로젝트: dasfaha/sky
// Append the contents of the AST node to the string.
// 
// node - The node to dump.
// ret  - A pointer to the bstring to concatenate to.
//
// Return 0 if successful, otherwise returns -1.s
int qip_ast_block_dump(qip_ast_node *node, bstring ret)
{
    int rc;
    check(node != NULL, "Node required");
    check(ret != NULL, "String required");

    // Append dump.
    bstring str = bformat("<block name='%s'>\n", bdatae(node->block.name, ""));
    check_mem(str);
    check(bconcat(ret, str) == BSTR_OK, "Unable to append dump");

    // Recursively dump children
    unsigned int i;
    for(i=0; i<node->block.expr_count; i++) {
        rc = qip_ast_node_dump(node->block.exprs[i], ret);
        check(rc == 0, "Unable to dump block expression");
    }

    return 0;

error:
    if(str != NULL) bdestroy(str);
    return -1;
}
예제 #23
0
파일: cpustring.c 프로젝트: ThreeGe/likwid
static int cpuexpr_to_list(bstring bcpustr, bstring prefix, int* list, int length)
{
    topology_init();
    CpuTopology_t cpuid_topology = get_cpuTopology();
    affinity_init();
    AffinityDomains_t affinity = get_affinityDomains();
    struct bstrList* strlist = bstrListCreate();
    strlist = bsplit(bcpustr, ',');
    int oldinsert = 0;
    int insert = 0;
    for (int i=0;i < strlist->qty; i++)
    {
        bstring newstr = bstrcpy(prefix);
        bconcat(newstr, strlist->entry[i]);
        oldinsert = insert;
        for (int j = 0; j < affinity->numberOfAffinityDomains; j++)
        {
            if (bstrcmp(affinity->domains[j].tag, newstr) == 0)
            {
                list[insert] = atoi(bdata(strlist->entry[i]));
                insert++;
                if (insert == length)
                    goto list_done;
                break;
            }
        }
        if (insert == oldinsert)
        {
            fprintf(stderr,"Domain %s cannot be found\n", bdata(newstr));
        }
        bdestroy(newstr);
    }
list_done:
    bstrListDestroy(strlist);
    return insert;
}
예제 #24
0
static int redir_conn_read(struct conn_t *conn, void *ctx) {
  redir_request *req = (redir_request *)ctx;
  uint8_t bb[PKT_MAX_LEN];
  int s, r;

  if ((s=redir_cli_rewrite(req, conn)) != 0) 
    return 0;
  
  r = safe_recv(conn->sock, bb, sizeof(bb)-1, 0);
  
#if(_debug_)
  log_dbg("conn_read: %d clen=%d", r, req->clen);
#endif
  
  if (r == 0) {

    if (req->read_closed && redir_cli_rewrite(req, conn) == 0) {
      log_dbg("done reading and writing");
      redir_conn_finish(conn, req);
      return -1;
    }

    req->read_closed = 1;
    
  } else if (r < 0 && 
	     errno != EWOULDBLOCK && errno != EAGAIN) {
    
    log_dbg("ERRNO %d", errno);
    redir_conn_finish(conn, ctx);
    
  } else if (r > 0) {
#ifdef ENABLE_REDIRINJECT
    bstring inject = inject_fmt(req, 0);
#endif
    
    bb[r]=0;
    req->last_active = mainclock_tick();
    
#ifdef ENABLE_REDIRINJECT

    /**
     *
     */
    if (inject && !req->headers) {
      char *newline = "\r\n\r\n";
      char *eoh;
      
      bcatblk(req->hbuf, bb, r);
      
      if ((eoh = strstr((char *)req->hbuf->data, newline))) {
	
	int header_len = eoh - (char *)req->hbuf->data;
	bstring newhdr = bfromcstr("");

	if (strncmp((char *)req->hbuf->data, "HTTP/1.", 7) ||
	    strncmp((char *)req->hbuf->data+8, " 2", 2)) {
	  
	  log_dbg("Not HTTP/1.X 2XX reply");
	  bcatblk(newhdr, req->hbuf->data, header_len + 4);
	  
	} else {
	  
	  char *hdr, *p;
	  int clen = 0;
	  
	  hdr = (char *)req->hbuf->data;
	  
	  while (hdr && *hdr) {
	    int l;
	    
	    p = strstr(hdr, "\r\n");
	    
	    if (p == hdr) {
	      break;
	    } else if (p) {
	      l = (p - hdr);
	    } else {
	      l = (eoh - hdr);
	    }
	    
	    if (!strncasecmp(hdr, "content-length:", 15)) {
	      char c = hdr[l];
	      hdr[l] = 0;
	      clen = req->clen = atoi(hdr+15);
	      log_dbg("Detected Content Length %d", req->clen);
	      hdr[l] = c;
	    } else if (!strncasecmp(hdr, "content-type:", 13)) {
	      if (strstr(hdr, "text/html")) {
		req->html = 1;
	      }
	    } else if (strcasestr(hdr, "content-encoding: gzip")) {
	      req->gzip = 1;
	    } else if (strcasestr(hdr, "transfer-encoding:") && 
		       strstr(hdr,"chunked")) {
	      req->chunked = 1;
	    }
	    
	    hdr += l + 2;
	    if (!p) break;
	  }

	  hdr = (char *)req->hbuf->data;
	  
	  while (hdr && *hdr) {
	    int l;
	    int skip = 0;
	    
	    p = strstr(hdr, "\r\n");
	    
	    if (p == hdr) {
	      break;
	    } else if (p) {
	      l = (p - hdr);
	    } else {
	      l = (eoh - hdr);
	    }
	    
	    if (req->html) {
	      if (clen && !strncasecmp(hdr, "content-length:", 15)) {
		char tmp[128];
		if (inject) clen += inject->slen;
		safe_snprintf(tmp, sizeof(tmp), "Content-Length: %d\r\n", clen);
		bcatcstr(newhdr, tmp);
		skip = 1;
	      } else if (!strncasecmp(hdr, "connection:", 11)) {
		skip = 1;
	      } else if (!strncasecmp(hdr, "accept-ranges:", 14)) {
		skip = 1;
	      }
	    }
	    
	    log_dbg("Resp Header [%d] %.*s%s", 
		    l, l, hdr, skip ? " [Skipped]" : "");
	    
	    if (!skip) {
	      bcatblk(newhdr, hdr, l + 2);
	    }
	    
	    hdr += l + 2;
	    if (!p) break;
	  }

	  bcatcstr(newhdr, "Connection: close\r\n");
	
	  /* process headers */
	  /* Is HTML */
	  /* Check content-encoding chunked */
	  /* Adjust content-length */
	  
	  bcatblk(newhdr, newline, 2);
	  
	  if (req->html) {
	    if (req->chunked) {
	      char tmp[56];
	      safe_snprintf(tmp, sizeof(tmp), "%x\r\n", 
			    inject->slen);
	      bcatcstr(newhdr, tmp);
	    }
	    bconcat(newhdr, inject);
	    if (req->chunked) {
	      bcatblk(newhdr, newline, 2);
	    }
	  }
	}

	bcatblk(newhdr, eoh + 4, req->hbuf->slen - header_len - 4);
	if (req->clen > 0) /* adjust clen */
	  req->clen -= (req->hbuf->slen - header_len - 4);
	redir_cli_write(req, newhdr->data, newhdr->slen);
	req->headers = 1;
	bdestroy(newhdr);
      }
    } else {
#endif

      redir_cli_write(req, bb, r);
      if (req->clen > 0)
	req->clen -= r;

#ifdef ENABLE_REDIRINJECT
    }
#endif
  }
  /*log_dbg("leaving redir_conn_read()");*/
  return 0;
}
예제 #25
0
struct lua_hardware* vm_hw_lua_load(vm_t* vm, bstring name)
{
	bstring path, modtype;
	struct lua_hardware* hw;
	int module, hwinfo;

	// Calculate full path to file.
	path = osutil_getarg0path();
#ifdef _WIN32
	bcatcstr(path, "modules\\");
#else
	bcatcstr(path, "/modules/");
#endif
	bconcat(path, name);

	// Create the new lua hardware structure.
	hw = malloc(sizeof(struct lua_hardware));
	hw->vm = vm;
	hw->state = lua_open();
	assert(hw->state != NULL);
	luaL_openlibs(hw->state);
	luaX_loadexpressionlib(hw->state);

	// Execute the code in the new Lua context.
	if (luaL_dofile(hw->state, path->data) != 0)
	{
		printf("lua error was %s.\n", lua_tostring(hw->state, -1));

		// Return NULL.
		lua_close(hw->state);
		free(hw);
		bdestroy(path);
		return NULL;
	}

	// Load tables.
	lua_getglobal(hw->state, "MODULE");
	module = lua_gettop(hw->state);
	lua_getglobal(hw->state, "HARDWARE");
	hwinfo = lua_gettop(hw->state);

	// Ensure both tables were provided.
	if (lua_isnoneornil(hw->state, module) || lua_isnoneornil(hw->state, hwinfo))
	{
		printf("failed to load hardware from %s.\n", path->data);

		// Return NULL.
		lua_close(hw->state);
		free(hw);
		bdestroy(path);
		return NULL;
	}

	// Check to see whether the module is
	// a hardware module.
	lua_getfield(hw->state, module, "Type");
	modtype = bfromcstr(lua_tostring(hw->state, -1));
	if (!biseqcstrcaseless(modtype, "Hardware"))
	{
		// Return NULL.
		lua_pop(hw->state, 1);
		lua_close(hw->state);
		free(hw);
		bdestroy(modtype);
		bdestroy(path);
		return NULL;
	}
	lua_pop(hw->state, 1);
	bdestroy(modtype);

	// Store information into the Lua
	// hardware structure.
	lua_getfield(hw->state, hwinfo, "ID");
	lua_getfield(hw->state, hwinfo, "Version");
	lua_getfield(hw->state, hwinfo, "Manufacturer");
	hw->device.id = (uint32_t)lua_tonumber(hw->state, lua_gettop(hw->state) - 2);
	hw->device.version = (uint16_t)lua_tonumber(hw->state, lua_gettop(hw->state) - 1);
	hw->device.manufacturer = (uint32_t)lua_tonumber(hw->state, lua_gettop(hw->state));
	lua_pop(hw->state, 3);

	printf("hardware loaded ID: %u, Version: %u, Manufacturer: %u.\n", hw->device.id, hw->device.version, hw->device.manufacturer);

	// Register the hardware.
	hw->device.handler = &vm_hw_lua_interrupt;
	hw->device.userdata = hw;
	vm_hw_register(vm, hw->device);

	// Register the hooks.
	hw->cycle_id = vm_hook_register(vm, &vm_hw_lua_cycle, HOOK_ON_POST_CYCLE, hw);
	hw->write_id = vm_hook_register(vm, &vm_hw_lua_write, HOOK_ON_WRITE, hw);

	// Pop tables from stack.
	lua_pop(hw->state, 2);

	// Return new hardware.
	return hw;
}
예제 #26
0
void TranslateToGLSL(HLSLCrossCompilerContext* psContext, GLLang* planguage,const GlExtensions *extensions)
{
    bstring glsl;
    uint32_t i;
    Shader* psShader = psContext->psShader;
    GLLang language = *planguage;
    const uint32_t ui32InstCount = psShader->ui32InstCount;
    const uint32_t ui32DeclCount = psShader->ui32DeclCount;

    psContext->indent = 0;

    if(language == LANG_DEFAULT)
    {
        language = ChooseLanguage(psShader);
        *planguage = language;
    }

    glsl = bfromcstralloc (1024, GetVersionString(language));

    psContext->glsl = glsl;
	psContext->earlyMain = bfromcstralloc (1024, "");
    for(i=0; i<NUM_PHASES;++i)
    {
        psContext->postShaderCode[i] = bfromcstralloc (1024, "");
    }
    psContext->currentGLSLString = &glsl;
    psShader->eTargetLanguage = language;
	psShader->extensions = (const struct GlExtensions*)extensions;
    psContext->currentPhase = MAIN_PHASE;

	if(extensions)
	{
		if(extensions->ARB_explicit_attrib_location)
			bcatcstr(glsl,"#extension GL_ARB_explicit_attrib_location : require\n");
		if(extensions->ARB_explicit_uniform_location)
			bcatcstr(glsl,"#extension GL_ARB_explicit_uniform_location : require\n");
		if(extensions->ARB_shading_language_420pack)
			bcatcstr(glsl,"#extension GL_ARB_shading_language_420pack : require\n");
	}

    ClearDependencyData(psShader->eShaderType, psContext->psDependencies);

    AddVersionDependentCode(psContext);

    if(psContext->flags & HLSLCC_FLAG_UNIFORM_BUFFER_OBJECT)
    {
        bcatcstr(glsl, "layout(std140) uniform;\n");
    }

    //Special case. Can have multiple phases.
    if(psShader->eShaderType == HULL_SHADER)
    {
        int haveInstancedForkPhase = 0;
        uint32_t forkIndex = 0;

        ConsolidateHullTempVars(psShader);

        for(i=0; i < psShader->ui32HSDeclCount; ++i)
        {
            TranslateDeclaration(psContext, psShader->psHSDecl+i);
        }

        //control
        psContext->currentPhase = HS_CTRL_POINT_PHASE;

        if(psShader->ui32HSControlPointDeclCount)
        {
            bcatcstr(glsl, "//Control point phase declarations\n");
            for(i=0; i < psShader->ui32HSControlPointDeclCount; ++i)
            {
                TranslateDeclaration(psContext, psShader->psHSControlPointPhaseDecl+i);
            }
        }

        if(psShader->ui32HSControlPointInstrCount)
        {
			SetDataTypes(psContext, psShader->psHSControlPointPhaseInstr, psShader->ui32HSControlPointInstrCount);

            bcatcstr(glsl, "void control_point_phase()\n{\n");
            psContext->indent++;

                for(i=0; i < psShader->ui32HSControlPointInstrCount; ++i)
                {
                    TranslateInstruction(psContext, psShader->psHSControlPointPhaseInstr+i);
                }
            psContext->indent--;
            bcatcstr(glsl, "}\n");
        }

        //fork
        psContext->currentPhase = HS_FORK_PHASE;
        for(forkIndex = 0; forkIndex < psShader->ui32ForkPhaseCount; ++forkIndex)
        {
            bcatcstr(glsl, "//Fork phase declarations\n");
            for(i=0; i < psShader->aui32HSForkDeclCount[forkIndex]; ++i)
            {
                TranslateDeclaration(psContext, psShader->apsHSForkPhaseDecl[forkIndex]+i);
                if(psShader->apsHSForkPhaseDecl[forkIndex][i].eOpcode == OPCODE_DCL_HS_FORK_PHASE_INSTANCE_COUNT)
                {
                    haveInstancedForkPhase = 1;
                }
            }

            bformata(glsl, "void fork_phase%d()\n{\n", forkIndex);
            psContext->indent++;

			SetDataTypes(psContext, psShader->apsHSForkPhaseInstr[forkIndex], psShader->aui32HSForkInstrCount[forkIndex]-1);

                if(haveInstancedForkPhase)
                {
                    AddIndentation(psContext);
                    bformata(glsl, "for(int forkInstanceID = 0; forkInstanceID < HullPhase%dInstanceCount; ++forkInstanceID) {\n", forkIndex);
                    psContext->indent++;
                }

                    //The minus one here is remove the return statement at end of phases.
                    //This is needed otherwise the for loop will only run once.
                    ASSERT(psShader->apsHSForkPhaseInstr[forkIndex][psShader->aui32HSForkInstrCount[forkIndex]-1].eOpcode == OPCODE_RET);
                    for(i=0; i < psShader->aui32HSForkInstrCount[forkIndex]-1; ++i)
                    {
                        TranslateInstruction(psContext, psShader->apsHSForkPhaseInstr[forkIndex]+i);
                    }

                if(haveInstancedForkPhase)
                {
                    psContext->indent--;
                    AddIndentation(psContext);
                    bcatcstr(glsl, "}\n");

                    if(psContext->havePostShaderCode[psContext->currentPhase])
                    {
#ifdef _DEBUG
                        AddIndentation(psContext);
                        bcatcstr(glsl, "//--- Post shader code ---\n");
#endif
                        bconcat(glsl, psContext->postShaderCode[psContext->currentPhase]);
#ifdef _DEBUG
                        AddIndentation(psContext);
                        bcatcstr(glsl, "//--- End post shader code ---\n");
#endif
                    }
                }

            psContext->indent--;
            bcatcstr(glsl, "}\n");
        }


        //join
        psContext->currentPhase = HS_JOIN_PHASE;
        if(psShader->ui32HSJoinDeclCount)
        {
            bcatcstr(glsl, "//Join phase declarations\n");
            for(i=0; i < psShader->ui32HSJoinDeclCount; ++i)
            {
                TranslateDeclaration(psContext, psShader->psHSJoinPhaseDecl+i);
            }
        }

        if(psShader->ui32HSJoinInstrCount)
        {
			SetDataTypes(psContext, psShader->psHSJoinPhaseInstr, psShader->ui32HSJoinInstrCount);

            bcatcstr(glsl, "void join_phase()\n{\n");
            psContext->indent++;

                for(i=0; i < psShader->ui32HSJoinInstrCount; ++i)
                {
                    TranslateInstruction(psContext, psShader->psHSJoinPhaseInstr+i);
                }

            psContext->indent--;
            bcatcstr(glsl, "}\n");
        }

        bcatcstr(glsl, "void main()\n{\n");

            psContext->indent++;

#ifdef _DEBUG
            AddIndentation(psContext);
            bcatcstr(glsl, "//--- Start Early Main ---\n");
#endif
            bconcat(glsl, psContext->earlyMain);
#ifdef _DEBUG
            AddIndentation(psContext);
            bcatcstr(glsl, "//--- End Early Main ---\n");
#endif

            if(psShader->ui32HSControlPointInstrCount)
            {
                AddIndentation(psContext);
                bcatcstr(glsl, "control_point_phase();\n");

                if(psShader->ui32ForkPhaseCount || psShader->ui32HSJoinInstrCount)
                {
                    AddIndentation(psContext);
                    bcatcstr(glsl, "barrier();\n");
                }
            }
            for(forkIndex = 0; forkIndex < psShader->ui32ForkPhaseCount; ++forkIndex)
            {
                AddIndentation(psContext);
                bformata(glsl, "fork_phase%d();\n", forkIndex);

                if(psShader->ui32HSJoinInstrCount || (forkIndex+1 < psShader->ui32ForkPhaseCount))
                {
                    AddIndentation(psContext);
                    bcatcstr(glsl, "barrier();\n");
                }
            }
            if(psShader->ui32HSJoinInstrCount)
            {
                AddIndentation(psContext);
                bcatcstr(glsl, "join_phase();\n");
            }

            psContext->indent--;

        bcatcstr(glsl, "}\n");

        if(psContext->psDependencies)
        {
            //Save partitioning and primitive type for use by domain shader.
            psContext->psDependencies->eTessOutPrim = psShader->sInfo.eTessOutPrim;

            psContext->psDependencies->eTessPartitioning = psShader->sInfo.eTessPartitioning;
        }

        return;
    }

    if(psShader->eShaderType == DOMAIN_SHADER && psContext->psDependencies)
    {
        //Load partitioning and primitive type from hull shader.
        switch(psContext->psDependencies->eTessOutPrim)
        {
            case TESSELLATOR_OUTPUT_TRIANGLE_CW:
            {
                bcatcstr(glsl, "layout(cw) in;\n");
                break;
            }
            case TESSELLATOR_OUTPUT_POINT:
            {
                bcatcstr(glsl, "layout(point_mode) in;\n");
                break;
            }
            default:
            {
                break;
            }
        }

        switch(psContext->psDependencies->eTessPartitioning)
        {
            case TESSELLATOR_PARTITIONING_FRACTIONAL_ODD:
            {
                bcatcstr(glsl, "layout(fractional_odd_spacing) in;\n");
                break;
            }
            case TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN:
            {
                bcatcstr(glsl, "layout(fractional_even_spacing) in;\n");
                break;
            }
            default:
            {
                break;
            }
        }
    }

    for(i=0; i < ui32DeclCount; ++i)
    {
        TranslateDeclaration(psContext, psShader->psDecl+i);
    }

    bcatcstr(glsl, "void main()\n{\n");

    psContext->indent++;

#ifdef _DEBUG
    AddIndentation(psContext);
    bcatcstr(glsl, "//--- Start Early Main ---\n");
#endif
	bconcat(glsl, psContext->earlyMain);
#ifdef _DEBUG
    AddIndentation(psContext);
    bcatcstr(glsl, "//--- End Early Main ---\n");
#endif

    MarkIntegerImmediates(psContext);

	SetDataTypes(psContext, psShader->psInst, ui32InstCount);

    for(i=0; i < ui32InstCount; ++i)
    {
        TranslateInstruction(psContext, psShader->psInst+i);
    }

    psContext->indent--;

    bcatcstr(glsl, "}\n");
}
예제 #27
0
파일: glsw.c 프로젝트: Cloudef/glhck
const char* glswGetShader(const char* pEffectKey, const char* pContentsFromMemory)
{
    glswContext* gc = __glsw__Context;
    bstring effectKey;
    glswList* closestMatch = 0;
    struct bstrList* tokens;
    bstring effectName;
    glswList* pLoadedEffect;
    glswList* pShaderEntry;
    bstring shaderKey = 0;

    if (!gc)
    {
        return 0;
    }

    // Extract the effect name from the effect key
    effectKey = bfromcstr(pEffectKey);
    tokens = bsplit(effectKey, '.');
    if (!tokens || !tokens->qty)
    {
        bdestroy(gc->ErrorMessage);
        gc->ErrorMessage = bformat("Malformed effect key key '%s'.", pEffectKey);
        bstrListDestroy(tokens);
        bdestroy(effectKey);
        return 0;
    }
    effectName = tokens->entry[0];

    // Check if we already loaded this effect file
    pLoadedEffect = gc->LoadedEffects;
    while (pLoadedEffect)
    {
        if (1 == biseq(pLoadedEffect->Key, effectName))
        {
            break;
        }
        pLoadedEffect = pLoadedEffect->Next;
    }

    // If we haven't loaded this file yet, load it in
    if (!pLoadedEffect)
    {
        bstring effectContents;
        struct bstrList* lines;
        int lineNo;

        if (!pContentsFromMemory) {
            FILE* fp;
            bstring effectFile;

            // Decorate the effect name to form the fullpath
            effectFile = bstrcpy(effectName);
            binsert(effectFile, 0, gc->PathPrefix, '?');
            bconcat(effectFile, gc->PathSuffix);

            // Attempt to open the file
            fp = fopen((const char*) effectFile->data, "rb");
            if (!fp)
            {
                bdestroy(gc->ErrorMessage);
                gc->ErrorMessage = bformat("Unable to open effect file '%s'.", effectFile->data);
                bdestroy(effectFile);
                bdestroy(effectKey);
                bstrListDestroy(tokens);
                return 0;
            }

            // Add a new entry to the front of gc->LoadedEffects
            {
                glswList* temp = gc->LoadedEffects;
                gc->LoadedEffects = (glswList*) calloc(sizeof(glswList), 1);
                gc->LoadedEffects->Key = bstrcpy(effectName);
                gc->LoadedEffects->Next = temp;
            }

            // Read in the effect file
            effectContents = bread((bNread) fread, fp);
            fclose(fp);
            bdestroy(effectFile);
        } else {
            effectContents = bfromcstr(pContentsFromMemory);
        }

        lines = bsplit(effectContents, '\n');
        bdestroy(effectContents);
        effectContents = 0;

        for (lineNo = 0; lineNo < lines->qty; lineNo++)
        {
            bstring line = lines->entry[lineNo];

            // If the line starts with "--", then it marks a new section
            if (blength(line) >= 2 && line->data[0] == '-' && line->data[1] == '-')
            {
                // Find the first character in [A-Za-z0-9_].
                int colNo;
                for (colNo = 2; colNo < blength(line); colNo++)
                {
                    char c = line->data[colNo];
                    if (__glsw__Alphanumeric(c))
                    {
                        break;
                    }
                }

                // If there's no alphanumeric character,
                // then this marks the start of a new comment block.
                if (colNo >= blength(line))
                {
                    bdestroy(shaderKey);
                    shaderKey = 0;
                }
                else
                {
                    // Keep reading until a non-alphanumeric character is found.
                    int endCol;
                    for (endCol = colNo; endCol < blength(line); endCol++)
                    {
                        char c = line->data[endCol];
                        if (!__glsw__Alphanumeric(c))
                        {
                            break;
                        }
                    }

                    bdestroy(shaderKey);
                    shaderKey = bmidstr(line, colNo, endCol - colNo);

                    // Add a new entry to the shader map.
                    {
                        glswList* temp = gc->ShaderMap;
                        gc->ShaderMap = (glswList*) calloc(sizeof(glswList), 1);
                        gc->ShaderMap->Key = bstrcpy(shaderKey);
                        gc->ShaderMap->Next = temp;
                        gc->ShaderMap->Value = bformat("#line %d\n", lineNo);

                        binsertch(gc->ShaderMap->Key, 0, 1, '.');
                        binsert(gc->ShaderMap->Key, 0, effectName, '?');
                    }

                    // Check for a version mapping.
                    if (gc->TokenMap)
                    {
                        struct bstrList* tokens = bsplit(shaderKey, '.');
                        glswList* pTokenMapping = gc->TokenMap;

                        while (pTokenMapping)
                        {
                            bstring directive = 0;
                            int tokenIndex;

                            // An empty key in the token mapping means "always prepend this directive".
                            // The effect name itself is also checked against the token mapping.
                            if (0 == blength(pTokenMapping->Key) ||
                                1 == biseq(pTokenMapping->Key, effectName))
                            {
                                directive = pTokenMapping->Value;
                                binsert(gc->ShaderMap->Value, 0, directive, '?');
                            }

                            // Check all tokens in the current section divider for a mapped token.
                            for (tokenIndex = 0; tokenIndex < tokens->qty && !directive; tokenIndex++)
                            {
                                bstring token = tokens->entry[tokenIndex];
                                if (1 == biseq(pTokenMapping->Key, token))
                                {
                                    directive = pTokenMapping->Value;
                                    binsert(gc->ShaderMap->Value, 0, directive, '?');
                                }
                            }

                            pTokenMapping = pTokenMapping->Next;
                        }

                        bstrListDestroy(tokens);
                    }
                }

                continue;
            }
            if (shaderKey)
            {
                bconcat(gc->ShaderMap->Value, line);
                bconchar(gc->ShaderMap->Value, '\n');
            }
        }

        // Cleanup
        bstrListDestroy(lines);
        bdestroy(shaderKey);
    }

    // Find the longest matching shader key
    pShaderEntry = gc->ShaderMap;

    while (pShaderEntry)
    {
        if (binstr(effectKey, 0, pShaderEntry->Key) == 0 &&
            (!closestMatch || blength(pShaderEntry->Key) > blength(closestMatch->Key)))
        {
            closestMatch = pShaderEntry;
        }

        pShaderEntry = pShaderEntry->Next;
    }

    bstrListDestroy(tokens);
    bdestroy(effectKey);

    if (!closestMatch)
    {
        bdestroy(gc->ErrorMessage);
        gc->ErrorMessage = bformat("Could not find shader with key '%s'.", pEffectKey);
        return 0;
    }

    return (const char*) closestMatch->Value->data;
}
예제 #28
0
static bstring tr_eval(TextResource tr, trnode_t* node) {
	//internally we work with bstrings



	trnode_t* tmpNode;

	switch(node->type) {
	case TRNODE_TEXT:
		return bstrcpy(node->textData);
	case TRNODE_REPR:
		; int match=0;
		if (node->condKey) {
			assert(node->condValue);
			//conditional
			char* condkey = bstr2cstr(node->condKey,'\0');
			bstring val = ght_get(tr->parameters,strlen(condkey),condkey);
			bcstrfree(condkey);

			if (val && !bstrcmp(node->condValue, val)) {
				//matches
				match = 1;
			}
		} else {
			//unconditional, so go too
			match=1;
		}

		if (match) {
			return tr_evalKey(tr,node->reprKey->data);
		} else
			return bfromcstr("");
	case TRNODE_STRING:
		//these guys have a blob of nodes that needs to be catted together smartly
		tmpNode = node->children_list;
		bstring tmpStr = bfromcstralloc(32,"");
		while(tmpNode) {
			bstring childStr = tr_eval(tr,tmpNode);
			bconchar(tmpStr,' ');
			bconcat(tmpStr,childStr);
			bdestroy(childStr);
			tmpNode = tmpNode->next;
		}
		return tmpStr;
	case TRNODE_SWITCH:
		//look through the children for matching choice
		; char* switchVar = bstr2cstr(node->switchVar,'\0');
		bstring val = ght_get(tr->parameters,strlen(switchVar),switchVar);
		bcstrfree(switchVar);

		tmpNode = node->children_list;
		while(tmpNode) {
			assert(tmpNode->type == TRNODE_STRING);
			assert(tmpNode->caseValue);

			if (!bstrcmp(tmpNode->caseValue,val)) {
				//we match, return this
				return tr_eval(tr,tmpNode);
			}
			//try next
			tmpNode = tmpNode->next;
		}
		return bfromcstr("");
	default:
		assert(0);
	}

	assert(0);
	return NULL;
}
예제 #29
0
bool do_search(CURL* curl, bstring name, bool all)
{
    DIR* dir;
    bool printed;
    CURLcode res;
    FILE* fp;
    list_t installed;
    struct bStream* stream;
    long httpcode = 0;
    bstring buffer, fname, sstr;
    bstring ext = bfromcstr(".lua");
    bstring url = bfromcstr("http://dms.dcputoolcha.in/modules/search?q=");
    bstring modpath = osutil_getmodulepath();
    struct dirent* entry;
    list_init(&installed);
    list_attributes_copy(&installed, list_meter_string, 1);
    list_attributes_comparator(&installed, list_comparator_string);

    // Attempt to open the modules directory.
    dir = opendir(modpath->data);
    if (dir == NULL)
    {
        printd(LEVEL_ERROR, "unable to query local repository.\n");
        return 1;
    }

    // Append the temporary search file name.
    bcatcstr(modpath, "/.search");
    bconcat(url, name);

    // Open the file and do the cURL transfer.
    printd(LEVEL_DEFAULT, "querying module repository...\n");
    fp = fopen(modpath->data, "wb");
    curl_easy_setopt(curl, CURLOPT_URL, url->data);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
    res = curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &httpcode);
    if (res != 0 || httpcode != 200)
    {
        bdestroy(url);
        bdestroy(name);
        bdestroy(modpath);
        printd(LEVEL_ERROR, "curl failed with error code %i, HTTP error code %i.\n", res, httpcode);
        return 1;
    }
    fclose(fp);

    // Print the local results.
    if (all)
        printd(LEVEL_DEFAULT, "all modules:\n");
    else
        printd(LEVEL_DEFAULT, "search results for %s:\n", name->data);
    while ((entry = readdir(dir)) != NULL)
    {
        fname = bfromcstr(&entry->d_name[0]);
        if (binstr(fname, blength(fname) - 4, ext) == BSTR_ERR)
        {
            bdestroy(fname);
            continue;
        }
        if (binstr(fname, 0, name) == BSTR_ERR)
        {
            bdestroy(fname);
            continue;
        }
        if (entry->d_type != DT_REG)
        {
            bdestroy(fname);
            continue;
        }
        sstr = bmidstr(fname, 0, blength(fname) - 4);
        printd(LEVEL_DEFAULT, "   %s (installed)\n", sstr->data);
        list_append(&installed, sstr->data);
        bdestroy(sstr);
        bdestroy(fname);
    }

    // Print the online results.
    fp = fopen(modpath->data, "r");
    stream = bsopen(&read_data, fp);
    buffer = bfromcstr("");
    printed = false;
    while (bsreadln(buffer, stream, '\n') != BSTR_ERR)
    {
        btrimws(buffer);
        sstr = bmidstr(buffer, 0, blength(buffer) - 4);
        if (!list_contains(&installed, sstr->data))
            printd(LEVEL_DEFAULT, "  %s\n", sstr->data);
        printed = true;
        bdestroy(sstr);
    }
    if (!printed)
        printd(LEVEL_DEFAULT, "   <no online results>\n");
    bsclose(stream);
    fclose(fp);

    // Clean up.
    curl_easy_cleanup(curl);
    return 0;
}
예제 #30
0
파일: Reader.c 프로젝트: denji/mdr
void createLine(int side, bstring base, bstring content, lineData lineMap, int * highlightMask)
{
    if (lineMap.type == INFO)
    {
        content = bfromcstr("");
        lineMap.lineNo = 0;
    }

    int position = 0;
    int needToCloseLastHighlightBeforeEscapingHTML = FALSE;

    if (highlightMask != NULL)
    {
        int lastState = MASK_SAME;
        int advanceBy;
        int i;
        int contentLen = content->slen; // Copy this because it will change as we work.
        for (i = 0; i < contentLen; i++)
        {
            advanceBy = 1; // Normally advance by one char.

            // Escape HTML as we go.
            if (content->data[position] == '&')
            {
                breplace(content, position, 1, bfromcstr("&amp;"), ' ');
                advanceBy += 4;
            }
            else if (content->data[position] == '<')
            {
                breplace(content, position, 1, bfromcstr("&lt;"), ' ');
                advanceBy += 3;
            }
            else if (content->data[position] == '>')
            {
                breplace(content, position, 1, bfromcstr("&gt;"), ' ');
                advanceBy += 3;
            }

            if (highlightMask[i] != lastState)
            {
                if (highlightMask[i] == MASK_DIFFERENT)
                {
                    binsert(content, position, bfromcstr("<em>"), ' ');
                    advanceBy += 4;
                }
                else
                {
                    binsert(content, position, bfromcstr("</em>"), ' ');
                    advanceBy += 5;
                }
            }

            position += advanceBy;
            lastState = highlightMask[i];
        }
    }

    // Escape HTML.
    // TODO: This can't possibly be good enough.
    bfindreplace(content, bfromcstr("&"), bfromcstr("&amp;"), position);
    bfindreplace(content, bfromcstr("<"), bfromcstr("&lt;"), position);
    bfindreplace(content, bfromcstr(">"), bfromcstr("&gt;"), position);

    // Put something in blank lines.
    if (content->slen == 0) bcatcstr(content, "&#32;");

    if (needToCloseLastHighlightBeforeEscapingHTML)
    {
        bcatcstr(content, "</em>");
    }

    // TODO: there's a lot of string manipulation going on here. It might be
    // good for performance to call ballocmin and boost the base string size by
    // a big chunk.

    if (lineMap.lineNo >= 0 && lineMap.type != INFO)
    {
        char * lineNo = lineNumberString(lineMap.lineNo);
        bcatcstr(base, "<td class='line_number ");
        bcatcstr(base, typeString(lineMap.type));
        bcatcstr(base, " ");
        bcatcstr(base, (side == LEFT) ? "left" : "right");
        bcatcstr(base, "' width='*'>");
        bcatcstr(base, lineNo);
        bcatcstr(base, "</td>\n");
        bcatcstr(base, "<td class='line ");
        free(lineNo);
    }
    else
    {
        bcatcstr(base, "<td colspan='2' class='line ");
    }
    bstring whitespace;

    bcatcstr(base, typeString(lineMap.type));
    bcatcstr(base, " ");
    bcatcstr(base, (side == LEFT) ? "left" : "right");
    bcatcstr(base, "' width='49%'>");
    bconcat(base, whitespace = getWhitespace(lineMap.leadingSpaces));
    bconcat(base, content);
    bcatcstr(base, "</td>\n");

    bdestroy(whitespace);
}