Ejemplo n.º 1
0
int get_ip_port_from_sdp(char *sdp_text, in_addr_t *addr, unsigned short *port){
    unsigned long l;
    char *s;
    char s1[20];
    s=gettag(sdp_text,strlen(sdp_text),"c=IN IP4 ",&l);
    memset(s1,'\0',sizeof(s1));
    memcpy(s1,s,MIN(l,19));
    if ((long)(*addr=inet_addr(s1))==-1){
	*addr=0;
	*port=0;
	return 1;
    }
    s=gettag(sdp_text,strlen(sdp_text),"m=audio ",&l);
    if (l==0){
        s=gettag(sdp_text,strlen(sdp_text),"m=image ",&l);
    }
    if (l==0 || (*port=atoi(s))==0){
	*port=0;
	return 1;
    }
    return 0;
}
Ejemplo n.º 2
0
Archivo: gdcm.cpp Proyecto: CAAP/Lua
static int scanner(lua_State *L) {
    gdcm::Scanner scn;
    gdcm::Directory d;
    const char* dirname = luaL_checkstring(L, 1);
    luaL_checktype(L, 2, LUA_TTABLE); // table containing dicom tags
    bool recurse = (1 == lua_toboolean(L, 3)); // whether recursion is performed

    d.Load( dirname, recurse ); // Load files from directory; recursively

    int k, N = luaL_len(L, 2); // N is the number of tags
    unsigned int j[2];
    gdcm::Tag tags[N];
    for (k=0; k < N; k++) {
	    lua_rawgeti(L, 2, k+1);
	    gettag(L, j);
	    lua_pop(L, 1);
	    tags[k] = gdcm::Tag(j[0], j[1]);
	    scn.AddTag( tags[k] );
    }

    if (!scn.Scan( d.GetFilenames() )) {lua_pushnil(L); lua_pushfstring(L, "Unable to scan directory: %s.\n", dirname); return 2;}

    gdcm::Directory::FilenamesType files = scn.GetKeys(); // it is a vector structure

    if ( !files.empty() ) {
	    lua_newtable(L);
	    int m = 1; // Number of files
	    for (gdcm::Directory::FilenamesType::const_iterator file = files.begin(); file != files.end(); ++file) {
		    lua_newtable(L);
		    const char *fname = file->c_str();
		    lua_pushstring(L, fname);
		    lua_rawseti(L, -2, 1);
		    for (k=0; k<N; k++) {
			    lua_pushstring(L, scn.GetValue(fname, tags[k]));
			    if (lua_isnumber(L, -1) == 1) {
				    lua_pushnumber(L, lua_tonumber(L, -1));
				    lua_remove(L, -2);
			    }
			    if (lua_isnoneornil(L, -1) == 1) {
				    lua_pop(L, 1);
				    lua_pushstring(L, "");
			    }
			    lua_rawseti(L, -2, k+2);
		    }
		    lua_rawseti(L, -2, m++); 
	    }
    } else
	    {lua_pushnil(L); lua_pushfstring(L, "Unable to find DCM files in directory: %s.\n", dirname); return 2;}; //luaL_error(L, "Unable to read directory.");
    return 1;
}
Ejemplo n.º 3
0
Archivo: parser.c Proyecto: badcodes/c
int main(int argc,char** argv) 
{
    char property[MAX_PROPERTY];
    char value[MAX_VALUE];
    char tag[MAX_TAG];

    int do_next=0;
    char* fullurl=NULL;
    char* baseurl=NULL;

    if (argc>1)
        baseurl=argv[1];

    while (gettag(stdin,tag)) {
        if (!IS_LINK_TAG(tag)) continue;

        DEBUG_PRINT_STR(tag);
        while (getproperty(stdin,property)) {
            if (!IS_LINK_PROP(property)) continue;
            DEBUG_PRINT_STR(property);
            do_next=getvalue(stdin,value);
            DEBUG_PRINT_STR(value);     
            if (do_next) {
                fullurl=getfullurl(value,baseurl);
                if (fullurl!=NULL) {
                    printf("%s\n",fullurl);
                    free(fullurl);
                }
            }
        }
    }

    while (0) {
         do_next=getproperty(stdin,property);
//         printf("%s=",property);
         if (!do_next) break;
         do_next=getvalue(stdin,value);
         if (IS_LINK(property)) {
            fullurl=getfullurl(value,baseurl);
            if (fullurl!=NULL) {
                printf("%s\n",fullurl);
                free(fullurl);
            }
         }
         if (!do_next) break;
    }

    return 0;
}
Ejemplo n.º 4
0
int I_ReadSigSet(FILE * fd, struct SigSet *S)
{
    char tag[256];

    I_InitSigSet(S);

    while (gettag(fd, tag)) {
	if (eq(tag, "title:"))
	    get_title(fd, S);
	if (eq(tag, "nbands:"))
	    get_nbands(fd, S);
	if (eq(tag, "class:"))
	    get_class(fd, S);
    }
    return 1;			/* for now assume success */
}
Ejemplo n.º 5
0
Archivo: gdcm.cpp Proyecto: CAAP/Lua
static int readImageHeader(lua_State *L) {
    luaL_checktype(L, 2, LUA_TTABLE);

    int k, N = luaL_len(L, 2);
    unsigned int j[2];
    gdcm::Tag tags[N];
    for (k=0; k < N; k++) {
	    lua_rawgeti(L, 2, k+1);
	    gettag(L, j);
	    lua_pop(L, 1);
	    tags[k] = gdcm::Tag(j[0], j[1]);
    }

    lua_pushinteger(L, getHeader(L, luaL_checkstring(L, 1), tags, N)); // number of missing values

    return 2;
}
/*
 * get_dbpath --
 *   Read the path of the database from man.conf and return.
 */
char *
get_dbpath(const char *manconf)
{
	TAG *tp;
	char *dbpath;

	config(manconf);
	tp = gettag("_mandb", 1);
	if (!tp)
		return NULL;
	
	if (TAILQ_EMPTY(&tp->entrylist))
		return NULL;

	dbpath = TAILQ_LAST(&tp->entrylist, tqh)->s;
	return dbpath;
}
Ejemplo n.º 7
0
static int get_subclass(FILE * fd, struct SigSet *S, struct ClassSig *C)
{
    struct SubSig *Sp;
    char tag[1024];

    Sp = I_NewSubSig(S, C);

    while (gettag(fd, tag)) {
	if (eq(tag, "endsubclass:"))
	    break;
	if (eq(tag, "pi:"))
	    get_subclass_pi(fd, Sp);
	if (eq(tag, "means:"))
	    get_subclass_means(fd, Sp, S->nbands);
	if (eq(tag, "covar:"))
	    get_subclass_covar(fd, Sp, S->nbands);
    }

    return 0;
}
Ejemplo n.º 8
0
int get_sip_peername(char *data, int data_len, const char *tag, char *peername, int peername_len){
    unsigned long r,r2,peername_tag_len;
    char *peername_tag=gettag(data,data_len,tag,&peername_tag_len);
    if ((r=(unsigned long)memmem(peername_tag,peername_tag_len,"sip:",4))==0){
	goto fail_exit;
    }
    r+=4;
    if ((r2=(unsigned long)memmem(peername_tag,peername_tag_len,"@",1))==0){
	goto fail_exit;
    }
    if (r2<=r){
	goto fail_exit;
    }
    memcpy(peername,(void*)r,r2-r);
    memset(peername+(r2-r),0,1);
    return 0;
fail_exit:
    strcpy(peername,"empty");
    return 1;
}
Ejemplo n.º 9
0
Archivo: liolib.c Proyecto: jeske/hz
static void io_writeto (void)
{
  FILE *current;
  lua_Object f = lua_getparam(FIRSTARG);
  if (f == LUA_NOOBJECT) {
    closefile(FOUTPUT);
    current = stdout;
  }
  else if (lua_tag(f) == gettag(IOTAG))
    current = lua_getuserdata(f);
  else {
    char *s = luaL_check_string(FIRSTARG);
    current = (*s == '|') ? popen(s+1,"w") : fopen(s,"w");
    if (current == NULL) {
      pushresult(0);
      return;
    }
  }
  setreturn(current, FOUTPUT);
}
Ejemplo n.º 10
0
rs_result
rs_build_hash_table(rs_signature_t * sums)
{
    int i;

    sums->tag_table = calloc(TABLE_SIZE, sizeof(sums->tag_table[0]));
    if (!sums->tag_table)
        return RS_MEM_ERROR;

    if (sums->count > 0) {
	sums->targets = calloc(sums->count, sizeof(rs_target_t));
        if (!sums->targets) {
	    free(sums->tag_table);
	    sums->tag_table = NULL;
            return RS_MEM_ERROR;
	}

	for (i = 0; i < sums->count; i++) {
	    sums->targets[i].i = i;
	    sums->targets[i].t = gettag(sums->block_sigs[i].weak_sum);
	}

	heap_sort(sums);
    }

    for (i = 0; i < TABLE_SIZE; i++) {
	sums->tag_table[i].l = NULL_TAG;
	sums->tag_table[i].r = NULL_TAG;
    }

    for (i = sums->count - 1; i >= 0; i--) {
	sums->tag_table[sums->targets[i].t].l = i;
    }

    for (i = 0; i < sums->count; i++) {
	sums->tag_table[sums->targets[i].t].r = i;
    }

    rs_trace("rs_build_hash_table done");
    return RS_DONE;
}
Ejemplo n.º 11
0
static int get_class(FILE * fd, struct SigSet *S)
{
    char tag[1024];
    struct ClassSig *C;

    C = I_NewClassSig(S);
    while (gettag(fd, tag)) {
	if (eq(tag, "endclass:"))
	    break;
	if (eq(tag, "classnum:"))
	    get_classnum(fd, C);
	if (eq(tag, "classtype:"))
	    get_classtype(fd, C);
	if (eq(tag, "classtitle:"))
	    get_classtitle(fd, C);
	if (eq(tag, "subclass:"))
	    get_subclass(fd, S, C);
    }

    return 0;
}
Ejemplo n.º 12
0
static void io_readfrom() {
	lua_Object f = lua_getparam(FIRSTARG);
	if (f == LUA_NOOBJECT) {
		if (getfile(FOUTPUT) != getfile(1)) {
			closefile(FINPUT);
			setreturn(1, FINPUT);
		}
	} else if (lua_tag(f) == gettag(IOTAG)) {
		int32 id = lua_getuserdata(f);
		LuaFile *current = getfile(id);
		if (!current) {
			pushresult(0);
			return;
		}
		setreturn(id, FINPUT);
	} else {
		const char *s = luaL_check_string(FIRSTARG);
		Common::String fileName = Common::lastPathComponent(s, '\\');
		LuaFile *current = NULL;
		Common::SeekableReadStream *inFile = NULL;
		Common::SaveFileManager *saveFileMan = g_system->getSavefileManager();
		inFile = saveFileMan->openForLoading(fileName);
		if (!inFile) {
			inFile = g_resourceloader->openNewStreamFile(s);
		}
		if (inFile) {
			current = new LuaFile();
			current->_in = inFile;
			current->_filename = s;
		} else {
			warning("liolib.cpp, io_readfrom(): Could not open file %s", s);
		}
		if (!current) {
			delete current;
			pushresult(0);
		} else {
			setreturn(addfile(current), FINPUT);
		}
	}
}
Ejemplo n.º 13
0
/**
 * anchor_get: return the specified anchor
 *
 *	@param[in]	name	name of anchor
 *	@param[in]	length	lenght of the name
 *	@param[in]	type	==0: not specified <br>
 *			!=0: D, M, T, R, Y
 *	@param[in]	lineno	line number
 */
struct anchor *
anchor_get(const char *name, int length, int type, int lineno)
{
	struct anchor *p = curp ? curp : start;

	if (table == NULL)
		return NULL;
	if (p->lineno > lineno)
		return NULL;
	/*
	 * set pointer to the top of the cluster.
	 */
	for (; p < end && p->lineno < lineno; p++)
		;
	if (p >= end || p->lineno != lineno)
		return NULL;
	curp = p;
	for (; p < end && p->lineno == lineno; p++)
		if (!p->done && p->length == length && !strcmp(gettag(p), name))
			if (!type || p->type == type)
				return p;
	return NULL;
}
Ejemplo n.º 14
0
void Store(mem_addr_t* addr)
{
    
    cache_set_t this_set=cache[getset(addr)];

    int index;
    for (index = 0; index < E; index++)
    {
        if ((this_set[index]).valid == '1' && gettag(addr) == (this_set[index]).tag)    //found
        {
            (this_set[index]).lru = ++lru_counter;
            break;
        }
    }

    if (index == E) // store miss
    {
        Load(addr);   // if miss, then load
    }
    else            // store hit
    {
        hit_count++;
    }
}
Ejemplo n.º 15
0
/* 
 * See if there is a match for the specified block INBUF..BLOCK_LEN in
 * the checksum set, using precalculated WEAK_SUM.
 *
 * If we don't find a match on the weak checksum, then we just give
 * up.  If we do find a weak match, then we proceed to calculate the
 * strong checksum for the current block, and see if it will match
 * anything.
 */
int
rs_search_for_block(rs_weak_sum_t weak_sum,
                    const rs_byte_t *inbuf,
                    size_t block_len,
                    rs_signature_t const *sig, rs_stats_t * stats,
                    rs_long_t * match_where)
{
    /* Caller must have called rs_build_hash_table() by now */
    if (!sig->tag_table)
        rs_fatal("Must have called rs_build_hash_table() by now");

    rs_strong_sum_t strong_sum;
    int got_strong = 0;
    int hash_tag = gettag(weak_sum);
    rs_tag_table_entry_t *bucket = &(sig->tag_table[hash_tag]);
    int l = bucket->l;
    int r = bucket->r + 1;
    int v = 1;

    if (l == NULL_TAG)
	return 0;

    while (l < r) {
	int m = (l + r) >> 1;
	int i = sig->targets[m].i;
	rs_block_sig_t *b = &(sig->block_sigs[i]);
	v = (weak_sum > b->weak_sum) - (weak_sum < b->weak_sum); // v < 0  - weak_sum <  b->weak_sum
								 // v == 0 - weak_sum == b->weak_sum
								 // v > 0  - weak_sum >  b->weak_sum
	if (v == 0) {
	    if (!got_strong) {
		if(sig->magic == RS_BLAKE2_SIG_MAGIC) {
		    rs_calc_blake2_sum(inbuf, block_len, &strong_sum);
		} else if (sig->magic == RS_MD4_SIG_MAGIC) {
		    rs_calc_md4_sum(inbuf, block_len, &strong_sum);
		} else {
		    rs_error("Unknown signature algorithm - this is a BUG");
		    return 0; /* FIXME: Is this the best way to handle this? */
		}
		got_strong = 1;
	    }
	    v = memcmp(strong_sum, b->strong_sum, sig->strong_sum_len);

	    if (v == 0) {
		l = m;
		r = m;
		break;
	    }
	}

	if (v > 0)
	    l = m + 1;
	else
	    r = m;
    }

    if (l == r) {
	int i = sig->targets[l].i;
	rs_block_sig_t *b = &(sig->block_sigs[i]);
	if (weak_sum != b->weak_sum)
	    return 0;
	if (!got_strong) {
            if(sig->magic == RS_BLAKE2_SIG_MAGIC) {
	        rs_calc_blake2_sum(inbuf, block_len, &strong_sum);
	    } else if (sig->magic == RS_MD4_SIG_MAGIC) {
                rs_calc_md4_sum(inbuf, block_len, &strong_sum);
	    } else {
	        rs_error("Unknown signature algorithm - this is a BUG");
		return 0; /* FIXME: Is this the best way to handle this? */
	    }
	    got_strong = 1;
	}
	v = memcmp(strong_sum, b->strong_sum, sig->strong_sum_len);
	int token = b->i;
	*match_where = (rs_long_t)(token - 1) * sig->block_len;
    }

    return !v;
}
Ejemplo n.º 16
0
Archivo: pgw.c Proyecto: aberg001/plan9
/*
 * cmd is one of:
 *    'p': normal print
 *    'h': just print headwords
 *    'P': print raw
 */
void
pgwprintentry(Entry e, int cmd)
{
    char *p, *pe;
    int t;
    long r, rprev, rlig;
    Rune *transtab;

    p = e.start;
    pe = e.end;
    transtab = normtab;
    rprev = NONE;
    changett(0, 0, 0);
    curentry = e;
    if(cmd == 'h')
        outinhibit = 1;
    while(p < pe) {
        if(cmd == 'r') {
            outchar(*p++);
            continue;
        }
        r = transtab[(*p++)&0x7F];
        if(r < NONE) {
            /* Emit the rune, but buffer in case of ligature */
            if(rprev != NONE)
                outrune(rprev);
            rprev = r;
        } else if(r == SPCS) {
            /* Start of special character name */
            p = getspec(p, pe);
            r = lookassoc(spectab, asize(spectab), spec);
            if(r == -1) {
                if(debug)
                    err("spec %ld %d %s",
                        e.doff, cursize, spec);
                r = L'�';
            }
            if(r >= LIGS && r < LIGE) {
                /* handle possible ligature */
                rlig = liglookup(r, rprev);
                if(rlig != NONE)
                    rprev = rlig;	/* overwrite rprev */
                else {
                    /* could print accent, but let's not */
                    if(rprev != NONE) outrune(rprev);
                    rprev = NONE;
                }
            } else if(r >= MULTI && r < MULTIE) {
                if(rprev != NONE) {
                    outrune(rprev);
                    rprev = NONE;
                }
                outrunes(multitab[r-MULTI]);
            } else if(r == PAR) {
                if(rprev != NONE) {
                    outrune(rprev);
                    rprev = NONE;
                }
                outnl(1);
            } else {
                if(rprev != NONE) outrune(rprev);
                rprev = r;
            }
        } else if(r == TAGS) {
            /* Start of tag name */
            if(rprev != NONE) {
                outrune(rprev);
                rprev = NONE;
            }
            p = gettag(p, pe);
            t = lookassoc(tagtab, asize(tagtab), tag);
            if(t == -1) {
                if(debug)
                    err("tag %ld %d %s",
                        e.doff, cursize, tag);
                continue;
            }
            switch(t) {
            case Hw:
                if(cmd == 'h') {
                    if(!tagstarts)
                        outchar(' ');
                    outinhibit = !tagstarts;
                }
                break;
            case Sn:
                if(tagstarts) {
                    outnl(2);
                }
                break;
            case P:
                outnl(tagstarts);
                break;
            case Col:
            case Br:
            case Blockquote:
                if(tagstarts)
                    outnl(1);
                break;
            case U:
                outchar('/');
            }
        }
    }
    if(cmd == 'h') {
        outinhibit = 0;
        outnl(0);
    }
}
Ejemplo n.º 17
0
static void setreturn(int32 id, const char *name) {
	int32 tag = gettag(IOTAG);
	setfile(id, name, tag);
	lua_pushusertag(id, tag);
}
Ejemplo n.º 18
0
/* helper function for parser */
void set_optdepends() {
#ifdef DEBUG
  printf("tag '%u' is set optional depends\n", gettag());
#endif
  parser_state.req=optdepends; 
}
Ejemplo n.º 19
0
Archivo: liolib.c Proyecto: jeske/hz
static void setreturn (FILE *f, char *name)
{
  int tag = gettag(IOTAG);
  setfile(f, name, tag);
  lua_pushusertag(f, tag);
}
Ejemplo n.º 20
0
/* helper function for parser */
void set_mandatory() { 
#ifdef DEBUG
  printf("tag '%u' is mandatory\n", gettag());
#endif
  parser_state.req=mandatory;
}
Ejemplo n.º 21
0
BOOL WINAPI mp4GetTag(MAP_PLUGIN_FILETAG* pTag)
{
	return gettag(pTag) ? TRUE : FALSE;
}
Ejemplo n.º 22
0
int main(int argc, char *argv[])
{

    pcap_t *handle;/* Session handle */
    const char *opt_chdir;/* directory to write dump */
    char *ifname;/* interface to sniff on */
    char *fname;/* pcap file to read on */
    char errbuf[PCAP_ERRBUF_SIZE];/* Error string */
    struct bpf_program fp;/* The compiled filter */
    char filter_exp[] = "udp";/* The filter expression */
    bpf_u_int32 mask;/* Our netmask */
    bpf_u_int32 net;/* Our IP */
    struct pcap_pkthdr *pkt_header; /* The header that pcap gives us */
    const u_char *pkt_data; /* The actual packet */
    unsigned long last_cleanup=0;
    int res;
    int offset_to_ip=0;
    int opt_fork=1;
    int opt_promisc=1;
    int opt_packetbuffered=0;
    int opt_t38only=0;
    int opt_rtpsave=RTPSAVE_RTP_RTCP;
    int verbosity=0;
    bool number_filter_matched=false;
#ifdef USE_REGEXP
    regex_t number_filter;
    number_filter.allocated=0;
#else
    char number_filter[128];
    number_filter[0]=0;
#endif

    ifname=NULL;
    fname=NULL;
    opt_chdir="/var/spool/pcapsipdump";

    while(1) {
        char c;

        c = getopt (argc, argv, "i:r:d:v:n:R:fpUt");
        if (c == -1)
            break;

        switch (c) {
            case 'i':
                ifname=optarg;
                break;
            case 'v':
                verbosity=atoi(optarg);
                break;
            case 'n':
#ifdef USE_REGEXP
                regcomp(&number_filter,optarg,0);
#else
                strcpy(number_filter,optarg);
#endif
                break;
            case 'R':
                if (strcasecmp(optarg,"none")==0){
                    opt_rtpsave=RTPSAVE_NONE;
                }else if (strcasecmp(optarg,"rtpevent")==0){
                    opt_rtpsave=RTPSAVE_RTPEVENT;
                }else if (strcasecmp(optarg,"t38")==0){
                    opt_t38only=1;
                }else if (strcasecmp(optarg,"all")==0 ||
                          strcasecmp(optarg,"rtp+rtcp")==0){
                    opt_rtpsave=RTPSAVE_RTP_RTCP;
                }else if (strcasecmp(optarg,"rtp")==0){
                    opt_rtpsave=RTPSAVE_RTP;
                }else{
                    printf("Unrecognized RTP filter specification: '%s'\n",optarg);
	            return 1;
                }
                break;
            case 't':
                opt_t38only=1;
                break;
            case 'r':
                fname=optarg;
                break;
            case 'd':
                opt_chdir=optarg;
                break;
            case 'f':
                opt_fork=0;
                break;
            case 'p':
                opt_promisc=0;
                break;
            case 'U':
		opt_packetbuffered=1;
                break;
        }
    }

    // allow interface to be specified without '-i' option - for sake of compatibility
    if (optind < argc) {
	ifname = argv[optind];
    }

    if ((fname==NULL)&&(ifname==NULL)){
	printf( "pcapsipdump version %s\n"
		"Usage: pcapsipdump [-fpU] [-i <interface>] [-r <file>] [-d <working directory>] [-v level] [-R filter]\n"
		" -f   Do not fork or detach from controlling terminal.\n"
		" -p   Do not put the interface into promiscuous mode.\n"
		" -R   RTP filter. Possible values: 'rtp+rtcp' (default), 'rtp', 'rtpevent', 't38', or 'none'.\n"
		" -U   Make .pcap files writing 'packet-buffered' - slower method,\n"
		"      but you can use partitially written file anytime, it will be consistent.\n"
		" -v   Set verbosity level (higher is more verbose).\n"
		" -n   Number-filter. Only calls to/from specified number will be recorded\n"
#ifdef USE_REGEXP
		"      Argument is regular expression. See 'man 7 regex' for details\n"
#endif
		" -t   T.38-filter. Only calls, containing T.38 payload indicated in SDP will be recorded\n"
		,PCAPSIPDUMP_VERSION);
	return 1;
    }

    ct = new calltable;
    if (opt_t38only){
        ct->erase_non_t38=1;
    }
    signal(SIGINT,sigint_handler);
    signal(SIGTERM,sigterm_handler);

    if (ifname){
	printf("Capturing on interface: %s\n", ifname);
	/* Find the properties for interface */
	if (pcap_lookupnet(ifname, &net, &mask, errbuf) == -1) {
	    fprintf(stderr, "Couldn't get netmask for interface %s: %s\n", ifname, errbuf);
	    net = 0;
	    mask = 0;
	}
	handle = pcap_open_live(ifname, 1600, opt_promisc, 1000, errbuf);
	if (handle == NULL) {
	    fprintf(stderr, "Couldn't open interface '%s': %s\n", ifname, errbuf);
	    return(2);
	}
    }else{
	printf("Reading file: %s\n", fname);
        net = 0;
        mask = 0;
	handle = pcap_open_offline(fname, errbuf);
	if (handle == NULL) {
	    fprintf(stderr, "Couldn't open pcap file '%s': %s\n", ifname, errbuf);
	    return(2);
	}
    }

    chdir(opt_chdir);

    /* Compile and apply the filter */
    if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
	fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
	return(2);
    }
    if (pcap_setfilter(handle, &fp) == -1) {
	fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
	return(2);
    }

    if (opt_fork){
	// daemonize
	if (fork()) exit(0);
    }

    {
	int dlt=pcap_datalink(handle);
	switch (dlt){
	    case DLT_EN10MB :
		offset_to_ip=sizeof(struct ether_header);
		break;
	    case DLT_LINUX_SLL :
		offset_to_ip=16;
		break;
	    case DLT_RAW :
		offset_to_ip=0;
		break;
	    default : {
		printf("Unknown interface type (%d).\n",dlt);
		return 3;
	    }
	}
    }


    /* Retrieve the packets */
    while((res = pcap_next_ex( handle, &pkt_header, &pkt_data)) >= 0){
	{
	    struct iphdr *header_ip;
	    struct udphdr *header_udp;
	    char *data;
	    char *s;
	    char str1[1024],str2[1024];
	    unsigned long datalen;
	    unsigned long l;
	    int idx;

            if(res == 0)
                /* Timeout elapsed */
                continue;

	    if (pkt_header->ts.tv_sec-last_cleanup>15){
		if (last_cleanup>=0){
		    ct->do_cleanup(pkt_header->ts.tv_sec);
		}
		last_cleanup=pkt_header->ts.tv_sec;
	    }
	    header_ip=(iphdr *)((char*)pkt_data+offset_to_ip);
	    if (header_ip->protocol==17){//UPPROTO_UDP=17
                int idx_leg=0;
                int idx_rtp=0;
                int save_this_rtp_packet=0;
                int is_rtcp=0;
                uint16_t rtp_port_mask=0xffff;

                header_udp=(udphdr *)((char*)header_ip+sizeof(*header_ip));
                data=(char *)header_udp+sizeof(*header_udp);
                datalen=pkt_header->len-((unsigned long)data-(unsigned long)pkt_data);

                if (opt_rtpsave==RTPSAVE_RTP){
                    save_this_rtp_packet=1;
                }else if (opt_rtpsave==RTPSAVE_RTP_RTCP){
                    save_this_rtp_packet=1;
                    rtp_port_mask=0xfffe;
                    is_rtcp=(htons(header_udp->source) & 1) && (htons(header_udp->dest) & 1);
                }else if (opt_rtpsave==RTPSAVE_RTPEVENT &&
                           datalen==18 && (data[0]&0xff) == 0x80 && (data[1]&0x7d) == 0x65){
                    save_this_rtp_packet=1;
                }else{
                    save_this_rtp_packet=0;
                }

                if (save_this_rtp_packet &&
                        ct->find_ip_port_ssrc(
                            header_ip->daddr,htons(header_udp->dest) & rtp_port_mask,
                            get_ssrc(data,is_rtcp),
                            &idx_leg,&idx_rtp)){
                    if (ct->table[idx_leg].f_pcap!=NULL) {
                        ct->table[idx_leg].last_packet_time=pkt_header->ts.tv_sec;
                        pcap_dump((u_char *)ct->table[idx_leg].f_pcap,pkt_header,pkt_data);
                        if (opt_packetbuffered) {pcap_dump_flush(ct->table[idx_leg].f_pcap);}
                    }
                }else if (save_this_rtp_packet &&
                        ct->find_ip_port_ssrc(
                            header_ip->saddr,htons(header_udp->source) & rtp_port_mask,
                            get_ssrc(data,is_rtcp),
                            &idx_leg,&idx_rtp)){
                    if (ct->table[idx_leg].f_pcap!=NULL) {
                        ct->table[idx_leg].last_packet_time=pkt_header->ts.tv_sec;
                        pcap_dump((u_char *)ct->table[idx_leg].f_pcap,pkt_header,pkt_data);
                        if (opt_packetbuffered) {pcap_dump_flush(ct->table[idx_leg].f_pcap);}
                    }
                }else if (htons(header_udp->source)==5060||
                    htons(header_udp->dest)==5060){
                    char caller[256];
                    char called[256];
                    char sip_method[256];

                    //figure out method
                    memcpy(sip_method,data,sizeof(sip_method)-1);
                    sip_method[sizeof(sip_method)-1]=' ';
                    if (strchr(sip_method,' ')!=NULL){
                        *strchr(sip_method,' ')='\0';
                    }else{
                        sip_method[0]='\0';
                        if (verbosity>=2){
                            printf("Empty SIP method!\n");
                        }
                    }

		    data[datalen]=0;
		    get_sip_peername(data,datalen,"From:",caller,sizeof(caller));
		    get_sip_peername(data,datalen,"To:",called,sizeof(called));
		    s=gettag(data,datalen,"Call-ID:",&l);
                    number_filter_matched=false;
#ifdef USE_REGEXP
                    {
                        regmatch_t pmatch[1];
                        if ((number_filter.allocated==0) ||
                            (regexec(&number_filter, caller, 1, pmatch, 0)==0) ||
                            (regexec(&number_filter, called, 1, pmatch, 0)==0)) {
                            number_filter_matched=true;
                        }
                    }
#else
                    if (number_filter[0]==0||(strcmp(number_filter,caller)==0)||(strcmp(number_filter,called)==0)) {
                        number_filter_matched=true;
                    }
#endif
		    if (s!=NULL && ((idx=ct->find_by_call_id(s,l))<0) && number_filter_matched){
			if ((idx=ct->add(s,l,pkt_header->ts.tv_sec))<0){
			    printf("Too many simultaneous calls. Ran out of call table space!\n");
			}else{
			    if ((strcmp(sip_method,"INVITE")==0)||(strcmp(sip_method,"OPTIONS")==0)||(strcmp(sip_method,"REGISTER")==0)){
				struct tm *t;
				t=localtime(&pkt_header->ts.tv_sec);
				sprintf(str2,"%04d%02d%02d",
					t->tm_year+1900,t->tm_mon+1,t->tm_mday);
				mkdir(str2,0700);
				sprintf(str2,"%04d%02d%02d/%02d",
					t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour);
				mkdir(str2,0700);
				sprintf(str2,"%04d%02d%02d/%02d/%04d%02d%02d-%02d%02d%02d-%s-%s",
					t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,
					t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec,caller,called);
				memcpy(str1,s,l);
				str1[l]='\0';
				strcat(str2,"-");
				strcat(str2,str1);
				strcat(str2,".raw");
				ct->table[idx].f=NULL;
				str1[l]='\0';
				*strstr(str2,".raw")='\0';
				strcat(str2,".pcap");
				ct->table[idx].f_pcap=pcap_dump_open(handle,str2);
				strncpy(ct->table[idx].fn_pcap,str2,sizeof(ct->table[idx].fn_pcap));
			    }else{
				if (verbosity>=2){
				    printf("Unknown SIP method:'%s'!\n",sip_method);
				}
				ct->table[idx].f=NULL;
				ct->table[idx].f_pcap=NULL;
			    }
			}
		    }

                    // idx holds a valid pointer to open leg at this point
                    if (strcmp(sip_method,"BYE")==0){
                        ct->table[idx].had_bye=1;
                    }
		    s=gettag(data,datalen,"Content-Type:",&l);
		    if(idx>=0 && l>0 && strncasecmp(s,"application/sdp",l)==0 && strstr(data,"\r\n\r\n")!=NULL){
			in_addr_t tmp_addr;
			unsigned short tmp_port;
			if (!get_ip_port_from_sdp(strstr(data,"\r\n\r\n")+1,&tmp_addr,&tmp_port)){
			    ct->add_ip_port(idx,tmp_addr,tmp_port);
			}else{
			    if (verbosity>=2){
				printf("Can't get ip/port from SDP:\n%s\n\n",strstr(data,"\r\n\r\n")+1);
			    }
			}
			if (opt_t38only && memmem(data,datalen,"udptl t38",9)!=NULL){
			    ct->table[idx].had_t38=1;
			}
		    }

		    if (ct->table[idx].f_pcap!=NULL){
			pcap_dump((u_char *)ct->table[idx].f_pcap,pkt_header,pkt_data);
			if (opt_packetbuffered) {pcap_dump_flush(ct->table[idx].f_pcap);}
		    }
		}else{
		    if (verbosity>=3){
			char st1[16];
			char st2[16];
			struct in_addr in;

			in.s_addr=header_ip->saddr;
			strcpy(st1,inet_ntoa(in));
			in.s_addr=header_ip->daddr;
			strcpy(st2,inet_ntoa(in));
			printf ("Skipping udp packet %s:%d->%s:%d\n",st1,htons(header_udp->source),st2,htons(header_udp->dest));
		    }
		}
	    }
	}
    }
    /* flush / close files */
    ct->do_cleanup(1<<31);
    /* And close the session */
    pcap_close(handle);
    return(0);
}
Ejemplo n.º 23
0
void write_file(iface_t *ifa)
{
    struct if_file *ifc = (struct if_file *) ifa->info;
    senblk_t *sptr;
    int usereturn=flag_test(ifa,F_NOCR)?0:1;
    int data=0;
    int cnt=1;
    struct iovec iov[2];

    /* ifc->fd will only be < 0 if we're opening a FIFO.
     */
    if (ifc->fd < 0) {
        if ((ifc->fd=open(ifc->filename,O_WRONLY)) < 0) {
            logerr(errno,"Failed to open FIFO %s for writing\n",ifc->filename);
            iface_thread_exit(errno);
        }
        if ((ifa->q =init_q(ifc->qsize)) == NULL) {
            logerr(errno,"Could not create queue for FIFO %s",ifc->filename);
            iface_thread_exit(errno);
        }
    }

    if (ifa->tagflags) {
        if ((iov[0].iov_base=malloc(TAGMAX)) == NULL) {
                logerr(errno,"Disabing tag output on interface id %u (%s)",
                        ifa->id,(ifa->name)?ifa->name:"unlabelled");
                ifa->tagflags=0;
        } else {
            cnt=2;
            data=1;
        }
    }


    for(;;)  {
        if ((sptr = next_senblk(ifa->q)) == NULL) {
            break;
        }

        if (senfilter(sptr,ifa->ofilter)) {
            senblk_free(sptr,ifa->q);
            continue;
        }

        if (!usereturn) {
            sptr->data[sptr->len-2] = '\n';
            sptr->len--;
        }

        if (ifa->tagflags)
            if ((iov[0].iov_len = gettag(ifa,iov[0].iov_base,sptr)) == 0) {
                logerr(errno,"Disabing tag output on interface id %u (%s)",
                        ifa->id,(ifa->name)?ifa->name:"unlabelled");
                ifa->tagflags=0;
                cnt=1;
                data=0;
                free(iov[0].iov_base);
            }

        iov[data].iov_base=sptr->data;
        iov[data].iov_len=sptr->len;
        if (writev(ifc->fd,iov,cnt) <0) {
            if (!(flag_test(ifa,F_PERSIST) && errno == EPIPE) )
                break;
            if ((ifc->fd=open(ifc->filename,O_WRONLY)) < 0)
                break;
        }
        senblk_free(sptr,ifa->q);
    }

    if (cnt == 2)
        free(iov[0].iov_base);

    iface_thread_exit(errno);
}
Ejemplo n.º 24
0
// Call this to get the tokens.
//  The number of returned tokens is returned in *plen.
Token*
_gettoks(uchar* data, int datalen, int chset, int mtype, int* plen)
{
	TokenSource*	ts;
	Token*		a;
	int	alen;
	int	ai;
	int	starti;
	int	c;
	int	tag;

	if(!lexinited)
		lexinit();
	ts = newtokensource(data, datalen, chset, mtype);
	if(dbglex)
		fprint(2, "_gettoks starts, ts.i=%d, ts.edata=%d\n", ts->i, ts->edata);
	alen = 0;
	ai = 0;
	a = 0;
	if(ts->mtype == TextHtml) {
		for(;;) {
			if(alen - ai < ToksChunk/32) {
				alen += ToksChunk;
				a = erealloc(a, alen*sizeof *a);
			}
			starti = ts->i;
			c = getchar(ts);
			if(c < 0)
				break;
			if(c == '<') {
				tag = gettag(ts, starti, a, &ai);
				if(tag == Tscript || tag == Tstyle) {
					// special rules for getting Data after....
					starti = ts->i;
					c = getchar(ts);
					tag = getscriptdata(ts, c, starti, a, &ai, tag);
				}
			}
			else
				tag = getdata(ts, c, starti, a, &ai);
			if(tag == -1)
				break;
			else if(dbglex > 1 && tag != Comment)
				fprint(2, "lex: got token %T\n", &a[ai-1]);
		}
	}
	else {
		// plain text (non-html) tokens
		for(;;) {
			if(alen - ai < ToksChunk/32) {
				alen += ToksChunk;
				a = erealloc(a, alen*sizeof *a);
			}
			tag = getplaindata(ts, a, &ai);
			if(tag == -1)
				break;
			if(dbglex > 1)
				fprint(2, "lex: got token %T\n", &a[ai]);
		}
	}
	free(ts);
	if(dbglex)
		fprint(2, "lex: returning %d tokens\n", ai);
	*plen = ai;
	if(ai == 0){
		free(a);
		a = 0;
	}
	return a;
}
Ejemplo n.º 25
0
// The rules for lexing scripts are different (ugh).
// Gather up everything until see an "</" tagnames[tok] ">"
static int
getscriptdata(TokenSource* ts, int firstc, int starti, Token* a, int* pai, int findtag)
{
	Rune*	s;
	int	j;
	int	tstarti;
	int	savei;
	int	c;
	int	tag;
	int	done;
	Token*	tok;
	Rune	buf[BIGBUFSIZE];

	s = nil;
	j = 0;
	tstarti = starti;
	c = firstc;
	done = 0;
	while(c >= 0) {
		if(c == '<') {
			// other browsers ignore stuff to end of line after <!
			savei = ts->i;
			c = getchar(ts);
			if(c == '!') {
				if(comment(ts) == -1)
					break;
				if(c == '\r')
					c = getchar(ts);
				if(c == '\n')
					c = getchar(ts);
			}
			else if(c >= 0) {
				backup(ts, savei);
				tag = gettag(ts, tstarti, a, pai);
				if(tag == -1)
					break;
				if(tag != Comment)
					(*pai)--;
				backup(ts, tstarti);
				if(tag == findtag + RBRA) {
					done = 1;
					break;
				}
				// here tag was not the one we were looking for, so take as regular data
				c = getchar(ts);
			}
		}
		if(c < 0)
			break;
		if(c != 0) {
			buf[j++] = c;
			if(j == nelem(buf)-1) {
				s = buftostr(s, buf, j);
				j = 0;
			}
		}
		tstarti = ts->i;
		c = getchar(ts);
	}
	if(done || ts->i == ts->edata) {
		s = buftostr(s, buf, j);
		tok = &a[(*pai)++];
		tok->tag = Data;
		tok->text = s;
		tok->attr = nil;
		tok->starti = starti;
		return Data;
	}
	free(s);
	backup(ts, starti);
	return -1;
}
Ejemplo n.º 26
0
/* helper function for parser */
void set_optional() {
#ifdef DEBUG
  printf("tag '%u' is optional\n", gettag());
#endif
  parser_state.req=optional; 
}
Ejemplo n.º 27
0
void
pcollprintentry(Entry e, int cmd)
{
	char *p, *pe;
	long r, rprev, t, rlig;
	int saveoi;
	Rune *transtab;

	p = e.start;
	pe = e.end;
	transtab = normtab;
	rprev = NONE;
	changett(0, 0, 0);
	curentry = e;
	saveoi = 0;
	if(cmd == 'h')
		outinhibit = 1;
	while(p < pe) {
		if(cmd == 'r') {
			outchar(*p++);
			continue;
		}
		r = transtab[(*p++)&0x7F];
		if(r < NONE) {
			/* Emit the rune, but buffer in case of ligature */
			if(rprev != NONE)
				outrune(rprev);
			rprev = r;
		} else if(r == TAGS) {
			p = gettag(p, pe);
			t = lookassoc(tagtab, asize(tagtab), tag);
			if(t == -1) {
				if(debug && !outinhibit)
					err("tag %ld %d %s",
						e.doff, cursize, tag);
				continue;
			}
			if(t < NONE) {
				if(rprev != NONE)
					outrune(rprev);
				rprev = t;
			} else if(t >= LIGS && t < LIGE) {
				/* handle possible ligature */
				rlig = liglookup(t, rprev);
				if(rlig != NONE)
					rprev = rlig;	/* overwrite rprev */
				else {
					/* could print accent, but let's not */
					if(rprev != NONE) outrune(rprev);
					rprev = NONE;
				}
			} else if(t >= MULTI && t < MULTIE) {
				if(rprev != NONE) {
					outrune(rprev);
					rprev = NONE;
				}
				outrunes(multitab[t-MULTI]);
			} else {
				if(rprev != NONE) {
					outrune(rprev);
					rprev = NONE;
				}
				switch(t){
				case H:
					if(cmd == 'h')
						outinhibit = 0;
					else
						outnl(0);
					break;
				case X:
					if(cmd == 'h')
						outinhibit = 1;
					else
						outchars(".  ");
					break;
				case Ps:
					/* don't know enough of pron. key yet */
					saveoi = outinhibit;
					outinhibit = 1;
					break;
				case Pe:
					outinhibit = saveoi;
					break;
				}
			}
		}
	}
	if(cmd == 'h')
		outinhibit = 0;
	outnl(0);
}
Ejemplo n.º 28
0
/* helper function for parser */
void set_ifdepends() {
#ifdef DEBUG
  printf("tag '%u' is set if depends\n", gettag());
#endif
  parser_state.req=ifdepends; 
}
Ejemplo n.º 29
0
static void closefile(const char *name) {
	LuaFile *f = getfile(name);
	f->close();
	lua_pushobject(lua_getglobal(name));
	lua_settag(gettag(CLOSEDTAG));
}
Ejemplo n.º 30
0
Archivo: rpc.c Proyecto: 99years/plan9
Packet*
_vtrpc(VtConn *z, Packet *p, VtFcall *tx)
{
	int i;
	uchar tag, buf[2], *top;
	Rwait *r, *rr;

	/* must malloc because stack could be private */
	r = vtmallocz(sizeof(Rwait));

	qlock(&z->lk);
	r->r.l = &z->lk;
	tag = gettag(z, r);
	if(tx){
		/* vtfcallrpc can't print packet because it doesn't have tag */
		tx->tag = tag;
		if(chattyventi)
			fprint(2, "%s -> %F\n", argv0, tx);
	}

	/* slam tag into packet */
	top = packetpeek(p, buf, 0, 2);
	if(top == nil){
		packetfree(p);
		return nil;
	}
	if(top == buf){
		werrstr("first two bytes must be in same packet fragment");
		packetfree(p);
		vtfree(r);
		return nil;
	}
	top[1] = tag;
	qunlock(&z->lk);
	if(vtsend(z, p) < 0){
		vtfree(r);
		return nil;
	}

	qlock(&z->lk);
	/* wait for the muxer to give us our packet */
	r->sleeping = 1;
	z->nsleep++;
	while(z->muxer && !r->done)
		rsleep(&r->r);
	z->nsleep--;
	r->sleeping = 0;

	/* if not done, there's no muxer: start muxing */
	if(!r->done){
		if(z->muxer)
			abort();
		z->muxer = 1;
		while(!r->done){
			qunlock(&z->lk);
			if((p = vtrecv(z)) == nil){
				werrstr("unexpected eof on venti connection");
				z->muxer = 0;
				vtfree(r);
				return nil;
			}
			qlock(&z->lk);
			muxrpc(z, p);
		}
		z->muxer = 0;
		/* if there is anyone else sleeping, wake first unfinished to mux */
		if(z->nsleep)
		for(i=0; i<256; i++){
			rr = z->wait[i];
			if(rr && rr->sleeping && !rr->done){
				rwakeup(&rr->r);
				break;
			}
		}
	}

	p = r->p;
	puttag(z, r, tag);
	vtfree(r);
	qunlock(&z->lk);
	return p;
}