Ejemplo n.º 1
1
 void decodeTest()
 {
   std::string bstr("Hi \xe4 there");
   cxxtools::String ustr = cxxtools::Iso8859_1Codec::decode(bstr);
   CXXTOOLS_UNIT_ASSERT(ustr == L"Hi \xe4 there");
 }
Ejemplo n.º 2
0
BSTR CAddVideoHtmlDlg::GetLastCatalog()
{
	CComBSTR bstr(ConfigureManager::GetInstance().GetLastCatalog().c_str());
	return bstr;
}
Ejemplo n.º 3
0
Archivo: buildgc.c Proyecto: 8l/go
// mkanames reads [5689].out.h and writes anames[5689].c
// The format is much the same as the Go opcodes above.
// It also writes out cnames array for C_* constants and the dnames
// array for D_* constants.
void
mkanames(char *dir, char *file)
{
	int i, j, ch, n, unknown;
	Buf in, b, out, out2;
	Vec lines;
	char *p, *p2;
	Vec dnames[128];

	binit(&b);
	binit(&in);
	binit(&out);
	binit(&out2);
	vinit(&lines);
	for(i=0; i<nelem(dnames); i++)
		vinit(&dnames[i]);

	ch = file[xstrlen(file)-3];
	bprintf(&b, "%s/../cmd/%cl/%c.out.h", dir, ch, ch);
	readfile(&in, bstr(&b));
	splitlines(&lines, bstr(&in));
	
	// Include link.h so that the extern declaration there is
	// checked against the non-extern declaration we are generating.
	bwritestr(&out, bprintf(&b, "// auto generated by go tool dist\n"));
	bwritestr(&out, bprintf(&b, "#include <u.h>\n"));
	bwritestr(&out, bprintf(&b, "#include <libc.h>\n"));
	bwritestr(&out, bprintf(&b, "#include <bio.h>\n"));
	bwritestr(&out, bprintf(&b, "#include <link.h>\n"));
	bwritestr(&out, bprintf(&b, "#include \"../cmd/%cl/%c.out.h\"\n", ch, ch));
	bwritestr(&out, bprintf(&b, "\n"));

	bwritestr(&out, bprintf(&b, "char*	anames%c[] = {\n", ch));
	for(i=0; i<lines.len; i++) {
		if(hasprefix(lines.p[i], "\tA")) {
			p = xstrstr(lines.p[i], ",");
			if(p)
				*p = '\0';
			p = xstrstr(lines.p[i], "\n");
			if(p)
				*p = '\0';
			p = lines.p[i] + 2;
			bwritestr(&out, bprintf(&b, "\t\"%s\",\n", p));
		}
	}
	bwritestr(&out, "};\n");

	j=0;
	bprintf(&out2, "char*	cnames%c[] = {\n", ch);
	for(i=0; i<lines.len; i++) {
		if(hasprefix(lines.p[i], "\tC_")) {
			p = xstrstr(lines.p[i], ",");
			if(p)
				*p = '\0';
			p = xstrstr(lines.p[i], "\n");
			if(p)
				*p = '\0';
			p = lines.p[i] + 3;
			bwritestr(&out2, bprintf(&b, "\t\"%s\",\n", p));
			j++;
		}
	}
	bwritestr(&out2, "};\n");
	if(j>0)
		bwriteb(&out, &out2);

	j=unknown=0;
	n=-1;
	for(i=0; i<lines.len; i++) {
		if(hasprefix(lines.p[i], "\tD_")) {
			p = xstrstr(lines.p[i], ",");
			if(p)
				*p = '\0';
			p = xstrstr(lines.p[i], "\n");
			if(p)
				*p = '\0';

			// Parse explicit value, if any
			p = xstrstr(lines.p[i], "=");
			if(p) {
				// Skip space after '='
				p2 = p + 1;
				while(*p2 == ' ' || *p2 == '\t')
					p2++;
				n = xatoi(p2, &p2);
				// We can't do anything about
				// non-numeric values or anything that
				// follows
				while(*p2 == ' ' || *p2 == '\t')
					p2++;
				if(*p2 != 0) {
					unknown = 1;
					continue;
				}
				// Truncate space before '='
				while(*(p-1) == ' ' || *(p-1) == '\t')
					p--;
				*p = '\0';
				unknown = 0;
			} else {
				n++;
			}

			if(unknown || n >= nelem(dnames))
				continue;

			p = lines.p[i] + 3;
			if(xstrcmp(p, "LAST") == 0)
				continue;
			vadd(&dnames[n], p);
			j++;
		}
	}
	if(j>0){
		bwritestr(&out, bprintf(&b, "char*	dnames%c[D_LAST] = {\n", ch));
		for(i=0; i<nelem(dnames); i++) {
			if(dnames[i].len == 0)
				continue;
			bwritestr(&out, bprintf(&b, "\t[D_%s] = \"", dnames[i].p[0]));
			for(j=0; j<dnames[i].len; j++) {
				if(j != 0)
					bwritestr(&out, "/");
				bwritestr(&out, dnames[i].p[j]);
			}
			bwritestr(&out, "\",\n");
		}
		bwritestr(&out, "};\n");
	}

	writefile(&out, file, 0);

	bfree(&b);
	bfree(&in);
	bfree(&out);
	bfree(&out2);
	vfree(&lines);
	for(i=0; i<nelem(dnames); i++)
		vfree(&dnames[i]);
}
Ejemplo n.º 4
0
// genrun is the generic run implementation.
static void
genrun(Buf *b, char *dir, int mode, Vec *argv, int wait)
{
	int i, p[2], pid;
	Buf b1, cmd;
	char *q;

	while(nbg >= maxnbg)
		bgwait1();

	binit(&b1);
	binit(&cmd);

	if(!isabs(argv->p[0])) {
		bpathf(&b1, "/bin/%s", argv->p[0]);
		free(argv->p[0]);
		argv->p[0] = xstrdup(bstr(&b1));
	}

	// Generate a copy of the command to show in a log.
	// Substitute $WORK for the work directory.
	for(i=0; i<argv->len; i++) {
		if(i > 0)
			bwritestr(&cmd, " ");
		q = argv->p[i];
		if(workdir != nil && hasprefix(q, workdir)) {
			bwritestr(&cmd, "$WORK");
			q += strlen(workdir);
		}
		bwritestr(&cmd, q);
	}
	if(vflag > 1)
		errprintf("%s\n", bstr(&cmd));

	if(b != nil) {
		breset(b);
		if(pipe(p) < 0)
			fatal("pipe");
	}

	switch(pid = fork()) {
	case -1:
		fatal("fork");
	case 0:
		if(b != nil) {
			close(0);
			close(p[0]);
			dup(p[1], 1);
			dup(p[1], 2);
			if(p[1] > 2)
				close(p[1]);
		}
		if(dir != nil) {
			if(chdir(dir) < 0) {
				fprint(2, "chdir: %r\n");
				_exits("chdir");
			}
		}
		vadd(argv, nil);
		exec(argv->p[0], argv->p);
		fprint(2, "%s\n", bstr(&cmd));
		fprint(2, "exec: %r\n");
		_exits("exec");
	}
	if(b != nil) {
		close(p[1]);
		breadfrom(b, p[0]);
		close(p[0]);
	}

	if(nbg < 0)
		fatal("bad bookkeeping");
	bg[nbg].pid = pid;
	bg[nbg].mode = mode;
	bg[nbg].cmd = btake(&cmd);
	bg[nbg].b = b;
	nbg++;
	
	if(wait)
		bgwait();

	bfree(&cmd);
	bfree(&b1);
}
Ejemplo n.º 5
0
HRESULT __stdcall Setting::Load( BSTR filename)
{
	mol::filestream fs;
	if (!fs.open(BSTR2ansi(filename))) 
	{
		return E_INVALIDARG;
	}

	std::string content = fs.readAll();
	fs.close();

	mol::XMLDocument xmlDoc;
	if(!xmlDoc.parse(content)) 
	{
		return E_INVALIDARG;
	}


	if (!xmlDoc.documentElement()->hasChildNodes())
	{
		return S_OK;
	}

	this->setDirty(FALSE);
	this->Clear();

	mol::Element* root = (mol::Element*)xmlDoc.documentElement()->firstChild();
	readWalker(root,this);
	return S_OK;


	std::string file = BSTR2ansi(filename);
    std::ifstream in(file.c_str());
    if (in)
    {
		
        char bufKey[1024];
        while( in.getline(bufKey,1024) )
        {
            std::string key = mol::trim(bufKey);
            if ( key != "" )
            {
				punk<ISetting> set;
				if ( S_OK == getKey(mol::towstring(key),&set) )
                if ( set )
                {
                    char bufVal[1024];
                    std::string val = "";
                    while( in.getline(bufVal,1024) )
                    {
                        std::string tmp(bufVal);// = mol::trim(bufVal);
                        if ( tmp.size() == 0 )
                        {
                            if ( in.peek() == '[' )
                                break;
                        }
                        val += tmp;
                        val += "\n";
                    }
                    if ( val != "" )
						set->put_Value(bstr(val));
                        //getValue(val,ce);
                }
				
            }
        }
        in.close();
    }
	this->setDirty(FALSE);
	return S_OK;
}
Ejemplo n.º 6
0
// install installs the library, package, or binary associated with dir,
// which is relative to $GOROOT/src.
static void
install(char *dir)
{
	char *name, *p, *elem, *prefix, *exe;
	bool islib, ispkg, isgo, stale;
	Buf b, b1, path;
	Vec compile, files, link, go, missing, clean, lib, extra;
	Time ttarg, t;
	int i, j, k, n, doclean, targ, usecpp;

	if(vflag) {
		if(!streq(goos, gohostos) || !streq(goarch, gohostarch))
			errprintf("%s (%s/%s)\n", dir, goos, goarch);
		else
			errprintf("%s\n", dir);
	}

	binit(&b);
	binit(&b1);
	binit(&path);
	vinit(&compile);
	vinit(&files);
	vinit(&link);
	vinit(&go);
	vinit(&missing);
	vinit(&clean);
	vinit(&lib);
	vinit(&extra);


	// path = full path to dir.
	bpathf(&path, "%s/src/%s", goroot, dir);
	name = lastelem(dir);

	// For misc/prof, copy into the tool directory and we're done.
	if(hasprefix(dir, "misc/")) {
		copy(bpathf(&b, "%s/%s", tooldir, name),
			bpathf(&b1, "%s/misc/%s", goroot, name), 1);
		goto out;
	}

	// For release, cmd/prof is not included.
	if((streq(dir, "cmd/prof")) && !isdir(bstr(&path))) {
		if(vflag > 1)
			errprintf("skipping %s - does not exist\n", dir);
		goto out;
	}

	// set up gcc command line on first run.
	if(gccargs.len == 0) {
		bprintf(&b, "%s", defaultcc);
		splitfields(&gccargs, bstr(&b));
		for(i=0; i<nelem(proto_gccargs); i++)
			vadd(&gccargs, proto_gccargs[i]);
		if(contains(gccargs.p[0], "clang")) {
			// disable ASCII art in clang errors, if possible
			vadd(&gccargs, "-fno-caret-diagnostics");
			// clang is too smart about unused command-line arguments
			vadd(&gccargs, "-Qunused-arguments");
		}
		if(streq(gohostos, "darwin")) {
			// golang.org/issue/5261
			vadd(&gccargs, "-mmacosx-version-min=10.6");
		}
	}

	islib = hasprefix(dir, "lib") || streq(dir, "cmd/cc") || streq(dir, "cmd/gc");
	ispkg = hasprefix(dir, "pkg");
	isgo = ispkg || streq(dir, "cmd/go") || streq(dir, "cmd/cgo");

	exe = "";
	if(streq(gohostos, "windows"))
		exe = ".exe";

	// Start final link command line.
	// Note: code below knows that link.p[targ] is the target.
	if(islib) {
		// C library.
		vadd(&link, "ar");
		if(streq(gohostos, "plan9"))
			vadd(&link, "rc");
		else
			vadd(&link, "rsc");
		prefix = "";
		if(!hasprefix(name, "lib"))
			prefix = "lib";
		targ = link.len;
		vadd(&link, bpathf(&b, "%s/pkg/obj/%s_%s/%s%s.a", goroot, gohostos, gohostarch, prefix, name));
	} else if(ispkg) {
		// Go library (package).
		vadd(&link, bpathf(&b, "%s/pack", tooldir));
		vadd(&link, "grc");
		p = bprintf(&b, "%s/pkg/%s_%s/%s", goroot, goos, goarch, dir+4);
		*xstrrchr(p, '/') = '\0';
		xmkdirall(p);
		targ = link.len;
		vadd(&link, bpathf(&b, "%s/pkg/%s_%s/%s.a", goroot, goos, goarch, dir+4));
	} else if(streq(dir, "cmd/go") || streq(dir, "cmd/cgo")) {
		// Go command.
		vadd(&link, bpathf(&b, "%s/%sl", tooldir, gochar));
		vadd(&link, "-o");
		elem = name;
		if(streq(elem, "go"))
			elem = "go_bootstrap";
		targ = link.len;
		vadd(&link, bpathf(&b, "%s/%s%s", tooldir, elem, exe));
	} else {
		// C command. Use gccargs.
		if(streq(gohostos, "plan9")) {
			vadd(&link, bprintf(&b, "%sl", gohostchar));
			vadd(&link, "-o");
			targ = link.len;
			vadd(&link, bpathf(&b, "%s/%s", tooldir, name));
		} else {
			vcopy(&link, gccargs.p, gccargs.len);
			if(sflag)
				vadd(&link, "-static");
			vadd(&link, "-o");
			targ = link.len;
			vadd(&link, bpathf(&b, "%s/%s%s", tooldir, name, exe));
			if(streq(gohostarch, "amd64"))
				vadd(&link, "-m64");
			else if(streq(gohostarch, "386"))
				vadd(&link, "-m32");
		}
	}
	ttarg = mtime(link.p[targ]);

	// Gather files that are sources for this target.
	// Everything in that directory, and any target-specific
	// additions.
	xreaddir(&files, bstr(&path));

	// Remove files beginning with . or _,
	// which are likely to be editor temporary files.
	// This is the same heuristic build.ScanDir uses.
	// There do exist real C files beginning with _,
	// so limit that check to just Go files.
	n = 0;
	for(i=0; i<files.len; i++) {
		p = files.p[i];
		if(hasprefix(p, ".") || (hasprefix(p, "_") && hassuffix(p, ".go")))
			xfree(p);
		else
			files.p[n++] = p;
	}
	files.len = n;

	for(i=0; i<nelem(deptab); i++) {
		if(hasprefix(dir, deptab[i].prefix)) {
			for(j=0; (p=deptab[i].dep[j])!=nil; j++) {
				breset(&b1);
				bwritestr(&b1, p);
				bsubst(&b1, "$GOROOT", goroot);
				bsubst(&b1, "$GOOS", goos);
				bsubst(&b1, "$GOARCH", goarch);
				p = bstr(&b1);
				if(hassuffix(p, ".a")) {
					if(streq(gohostos, "plan9") && hassuffix(p, "libbio.a"))
						continue;
					vadd(&lib, bpathf(&b, "%s", p));
					continue;
				}
				if(hassuffix(p, "/*")) {
					bpathf(&b, "%s/%s", bstr(&path), p);
					b.len -= 2;
					xreaddir(&extra, bstr(&b));
					bprintf(&b, "%s", p);
					b.len -= 2;
					for(k=0; k<extra.len; k++)
						vadd(&files, bpathf(&b1, "%s/%s", bstr(&b), extra.p[k]));
					continue;
				}
				if(hasprefix(p, "-")) {
					p++;
					n = 0;
					for(k=0; k<files.len; k++) {
						if(hasprefix(files.p[k], p))
							xfree(files.p[k]);
						else
							files.p[n++] = files.p[k];
					}
					files.len = n;
					continue;
				}
				vadd(&files, p);
			}
		}
	}
	vuniq(&files);

	// Convert to absolute paths.
	for(i=0; i<files.len; i++) {
		if(!isabs(files.p[i])) {
			bpathf(&b, "%s/%s", bstr(&path), files.p[i]);
			xfree(files.p[i]);
			files.p[i] = btake(&b);
		}
	}

	// Is the target up-to-date?
	stale = rebuildall;
	n = 0;
	for(i=0; i<files.len; i++) {
		p = files.p[i];
		for(j=0; j<nelem(depsuffix); j++)
			if(hassuffix(p, depsuffix[j]))
				goto ok;
		xfree(files.p[i]);
		continue;
	ok:
		t = mtime(p);
		if(t != 0 && !hassuffix(p, ".a") && !shouldbuild(p, dir)) {
			xfree(files.p[i]);
			continue;
		}
		if(hassuffix(p, ".go"))
			vadd(&go, p);
		if(t > ttarg)
			stale = 1;
		if(t == 0) {
			vadd(&missing, p);
			files.p[n++] = files.p[i];
			continue;
		}
		files.p[n++] = files.p[i];
	}
	files.len = n;

	// If there are no files to compile, we're done.
	if(files.len == 0)
		goto out;
	
	for(i=0; i<lib.len && !stale; i++)
		if(mtime(lib.p[i]) > ttarg)
			stale = 1;

	if(!stale)
		goto out;

	// For package runtime, copy some files into the work space.
	if(streq(dir, "pkg/runtime")) {
		copy(bpathf(&b, "%s/arch_GOARCH.h", workdir),
			bpathf(&b1, "%s/arch_%s.h", bstr(&path), goarch), 0);
		copy(bpathf(&b, "%s/defs_GOOS_GOARCH.h", workdir),
			bpathf(&b1, "%s/defs_%s_%s.h", bstr(&path), goos, goarch), 0);
		p = bpathf(&b1, "%s/signal_%s_%s.h", bstr(&path), goos, goarch);
		if(isfile(p))
			copy(bpathf(&b, "%s/signal_GOOS_GOARCH.h", workdir), p, 0);
		copy(bpathf(&b, "%s/os_GOOS.h", workdir),
			bpathf(&b1, "%s/os_%s.h", bstr(&path), goos), 0);
		copy(bpathf(&b, "%s/signals_GOOS.h", workdir),
			bpathf(&b1, "%s/signals_%s.h", bstr(&path), goos), 0);
	}

	// Generate any missing files; regenerate existing ones.
	for(i=0; i<files.len; i++) {
		p = files.p[i];
		elem = lastelem(p);
		for(j=0; j<nelem(gentab); j++) {
			if(hasprefix(elem, gentab[j].nameprefix)) {
				if(vflag > 1)
					errprintf("generate %s\n", p);
				gentab[j].gen(bstr(&path), p);
				// Do not add generated file to clean list.
				// In pkg/runtime, we want to be able to
				// build the package with the go tool,
				// and it assumes these generated files already
				// exist (it does not know how to build them).
				// The 'clean' command can remove
				// the generated files.
				goto built;
			}
		}
		// Did not rebuild p.
		if(find(p, missing.p, missing.len) >= 0)
			fatal("missing file %s", p);
	built:;
	}

	// One more copy for package runtime.
	// The last batch was required for the generators.
	// This one is generated.
	if(streq(dir, "pkg/runtime")) {
		copy(bpathf(&b, "%s/zasm_GOOS_GOARCH.h", workdir),
			bpathf(&b1, "%s/zasm_%s_%s.h", bstr(&path), goos, goarch), 0);
	}

	// Generate .c files from .goc files.
	if(streq(dir, "pkg/runtime")) {
		for(i=0; i<files.len; i++) {
			p = files.p[i];
			if(!hassuffix(p, ".goc"))
				continue;
			// b = path/zp but with _goos_goarch.c instead of .goc
			bprintf(&b, "%s%sz%s", bstr(&path), slash, lastelem(p));
			b.len -= 4;
			bwritef(&b, "_%s_%s.c", goos, goarch);
			goc2c(p, bstr(&b));
			vadd(&files, bstr(&b));
		}
		vuniq(&files);
	}

	if((!streq(goos, gohostos) || !streq(goarch, gohostarch)) && isgo) {
		// We've generated the right files; the go command can do the build.
		if(vflag > 1)
			errprintf("skip build for cross-compile %s\n", dir);
		goto nobuild;
	}

	// The files generated by GNU Bison use macros that aren't
	// supported by the Plan 9 compilers so we have to use the
	// external preprocessor when compiling.
	usecpp = 0;
	if(streq(gohostos, "plan9")) {
		for(i=0; i<files.len; i++) {
			p = files.p[i];
			if(hassuffix(p, "y.tab.c") || hassuffix(p, "y.tab.h")){
				usecpp = 1;
				break;
			}
		}
	}

	// Compile the files.
	for(i=0; i<files.len; i++) {
		if(!hassuffix(files.p[i], ".c") && !hassuffix(files.p[i], ".s"))
			continue;
		name = lastelem(files.p[i]);

		vreset(&compile);
		if(!isgo) {
			// C library or tool.
			if(streq(gohostos, "plan9")) {
				vadd(&compile, bprintf(&b, "%sc", gohostchar));
				vadd(&compile, "-FTVw");
				if(usecpp)
					vadd(&compile, "-Bp+");
				vadd(&compile, bpathf(&b, "-I%s/include/plan9", goroot));
				vadd(&compile, bpathf(&b, "-I%s/include/plan9/%s", goroot, gohostarch));
				// Work around Plan 9 C compiler's handling of #include with .. path.
				vadd(&compile, bpathf(&b, "-I%s/src/cmd/ld", goroot));
			} else {
				vcopy(&compile, gccargs.p, gccargs.len);
				vadd(&compile, "-c");
				if(streq(gohostarch, "amd64"))
					vadd(&compile, "-m64");
				else if(streq(gohostarch, "386"))
					vadd(&compile, "-m32");
				if(streq(dir, "lib9"))
					vadd(&compile, "-DPLAN9PORT");
	
				vadd(&compile, "-I");
				vadd(&compile, bpathf(&b, "%s/include", goroot));
			}

			vadd(&compile, "-I");
			vadd(&compile, bstr(&path));

			// lib9/goos.c gets the default constants hard-coded.
			if(streq(name, "goos.c")) {
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GOOS=\"%s\"", goos));
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GOARCH=\"%s\"", goarch));
				bprintf(&b1, "%s", goroot_final);
				bsubst(&b1, "\\", "\\\\");  // turn into C string
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GOROOT=\"%s\"", bstr(&b1)));
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GOVERSION=\"%s\"", goversion));
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GOARM=\"%s\"", goarm));
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GO386=\"%s\"", go386));
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GO_EXTLINK_ENABLED=\"%s\"", goextlinkenabled));
			}

			// gc/lex.c records the GOEXPERIMENT setting used during the build.
			if(streq(name, "lex.c")) {
				xgetenv(&b, "GOEXPERIMENT");
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b1, "GOEXPERIMENT=\"%s\"", bstr(&b)));
			}
		} else {
			// Supporting files for a Go package.
			if(hassuffix(files.p[i], ".s"))
				vadd(&compile, bpathf(&b, "%s/%sa", tooldir, gochar));
			else {
				vadd(&compile, bpathf(&b, "%s/%sc", tooldir, gochar));
				vadd(&compile, "-F");
				vadd(&compile, "-V");
				vadd(&compile, "-w");
			}
			vadd(&compile, "-I");
			vadd(&compile, workdir);
			vadd(&compile, "-I");
			vadd(&compile, bprintf(&b, "%s/pkg/%s_%s", goroot, goos, goarch));
			vadd(&compile, "-D");
			vadd(&compile, bprintf(&b, "GOOS_%s", goos));
			vadd(&compile, "-D");
			vadd(&compile, bprintf(&b, "GOARCH_%s", goarch));
			vadd(&compile, "-D");
			vadd(&compile, bprintf(&b, "GOOS_GOARCH_%s_%s", goos, goarch));
		}

		bpathf(&b, "%s/%s", workdir, lastelem(files.p[i]));
		doclean = 1;
		if(!isgo && streq(gohostos, "darwin")) {
			// To debug C programs on OS X, it is not enough to say -ggdb
			// on the command line.  You have to leave the object files
			// lying around too.  Leave them in pkg/obj/, which does not
			// get removed when this tool exits.
			bpathf(&b1, "%s/pkg/obj/%s", goroot, dir);
			xmkdirall(bstr(&b1));
			bpathf(&b, "%s/%s", bstr(&b1), lastelem(files.p[i]));
			doclean = 0;
		}

		// Change the last character of the output file (which was c or s).
		if(streq(gohostos, "plan9"))
			b.p[b.len-1] = gohostchar[0];
		else
			b.p[b.len-1] = 'o';
		vadd(&compile, "-o");
		vadd(&compile, bstr(&b));
		vadd(&compile, files.p[i]);
		bgrunv(bstr(&path), CheckExit, &compile);

		vadd(&link, bstr(&b));
		if(doclean)
			vadd(&clean, bstr(&b));
	}
	bgwait();

	if(isgo) {
		// The last loop was compiling individual files.
		// Hand the Go files to the compiler en masse.
		vreset(&compile);
		vadd(&compile, bpathf(&b, "%s/%sg", tooldir, gochar));

		bpathf(&b, "%s/_go_.%s", workdir, gochar);
		vadd(&compile, "-o");
		vadd(&compile, bstr(&b));
		vadd(&clean, bstr(&b));
		vadd(&link, bstr(&b));

		vadd(&compile, "-p");
		if(hasprefix(dir, "pkg/"))
			vadd(&compile, dir+4);
		else
			vadd(&compile, "main");

		if(streq(dir, "pkg/runtime"))
			vadd(&compile, "-+");

		vcopy(&compile, go.p, go.len);

		runv(nil, bstr(&path), CheckExit, &compile);
	}

	if(!islib && !isgo) {
		// C binaries need the libraries explicitly, and -lm.
		vcopy(&link, lib.p, lib.len);
		if(!streq(gohostos, "plan9"))
			vadd(&link, "-lm");
	}

	// Remove target before writing it.
	xremove(link.p[targ]);

	runv(nil, nil, CheckExit, &link);

nobuild:
	// In package runtime, we install runtime.h and cgocall.h too,
	// for use by cgo compilation.
	if(streq(dir, "pkg/runtime")) {
		copy(bpathf(&b, "%s/pkg/%s_%s/cgocall.h", goroot, goos, goarch),
			bpathf(&b1, "%s/src/pkg/runtime/cgocall.h", goroot), 0);
		copy(bpathf(&b, "%s/pkg/%s_%s/runtime.h", goroot, goos, goarch),
			bpathf(&b1, "%s/src/pkg/runtime/runtime.h", goroot), 0);
	}


out:
	for(i=0; i<clean.len; i++)
		xremove(clean.p[i]);

	bfree(&b);
	bfree(&b1);
	bfree(&path);
	vfree(&compile);
	vfree(&files);
	vfree(&link);
	vfree(&go);
	vfree(&missing);
	vfree(&clean);
	vfree(&lib);
	vfree(&extra);
}
Ejemplo n.º 7
0
// findgoversion determines the Go version to use in the version string.
static char*
findgoversion(void)
{
	char *tag, *rev, *p;
	int i, nrev;
	Buf b, path, bmore, branch;
	Vec tags;

	binit(&b);
	binit(&path);
	binit(&bmore);
	binit(&branch);
	vinit(&tags);

	// The $GOROOT/VERSION file takes priority, for distributions
	// without the Mercurial repo.
	bpathf(&path, "%s/VERSION", goroot);
	if(isfile(bstr(&path))) {
		readfile(&b, bstr(&path));
		chomp(&b);
		// Commands such as "dist version > VERSION" will cause
		// the shell to create an empty VERSION file and set dist's
		// stdout to its fd. dist in turn looks at VERSION and uses
		// its content if available, which is empty at this point.
		if(b.len > 0)
			goto done;
	}

	// The $GOROOT/VERSION.cache file is a cache to avoid invoking
	// hg every time we run this command.  Unlike VERSION, it gets
	// deleted by the clean command.
	bpathf(&path, "%s/VERSION.cache", goroot);
	if(isfile(bstr(&path))) {
		readfile(&b, bstr(&path));
		chomp(&b);
		goto done;
	}

	// Otherwise, use Mercurial.
	// What is the current branch?
	run(&branch, goroot, CheckExit, "hg", "identify", "-b", nil);
	chomp(&branch);

	// What are the tags along the current branch?
	tag = "devel";
	rev = ".";
	run(&b, goroot, CheckExit, "hg", "log", "-b", bstr(&branch), "-r", ".:0", "--template", "{tags} + ", nil);
	splitfields(&tags, bstr(&b));
	nrev = 0;
	for(i=0; i<tags.len; i++) {
		p = tags.p[i];
		if(streq(p, "+"))
			nrev++;
		// NOTE: Can reenable the /* */ code when we want to
		// start reporting versions named 'weekly' again.
		if(/*hasprefix(p, "weekly.") ||*/ hasprefix(p, "go")) {
			tag = xstrdup(p);
			// If this tag matches the current checkout
			// exactly (no "+" yet), don't show extra
			// revision information.
			if(nrev == 0)
				rev = "";
			break;
		}
	}

	if(tag[0] == '\0') {
		// Did not find a tag; use branch name.
		bprintf(&b, "branch.%s", bstr(&branch));
		tag = btake(&b);
	}

	if(rev[0]) {
		// Tag is before the revision we're building.
		// Add extra information.
		run(&bmore, goroot, CheckExit, "hg", "log", "--template", " +{node|short} {date|date}", "-r", rev, nil);
		chomp(&bmore);
	}

	bprintf(&b, "%s", tag);
	if(bmore.len > 0)
		bwriteb(&b, &bmore);

	// Cache version.
	writefile(&b, bstr(&path), 0);

done:
	p = btake(&b);


	bfree(&b);
	bfree(&path);
	bfree(&bmore);
	bfree(&branch);
	vfree(&tags);

	return p;
}
Ejemplo n.º 8
0
void editroompic(void) {
	char buf[SIZ];
	snprintf(buf, SIZ, "_roompic_|%s",
		 bstr("which_room"));
	do_graphics_upload(buf);
}
Ejemplo n.º 9
0
/*!
 * @brief Perform a WMI query.
 * @param lpwRoot Name of the root object that is to be queried against.
 * @param lpwQuery The filter to use when reading objects (LDAP style).
 * @param response The response \c Packet to add the results to.
 */
DWORD wmi_query(LPCWSTR lpwRoot, LPWSTR lpwQuery, Packet* response)
{
	HRESULT hResult;

	dprintf("[WMI] Initialising COM");
	if ((hResult = CoInitializeEx(NULL, COINIT_MULTITHREADED)) == S_OK)
	{
		dprintf("[WMI] COM initialised");
		IWbemLocator* pLocator = NULL;
		IWbemServices* pServices = NULL;
		IEnumWbemClassObject* pEnumerator = NULL;
		IWbemClassObject* pSuperClass = NULL;
		IWbemClassObject* pObj = NULL;
		Tlv* valueTlvs = NULL;
		char* values = NULL;
		VARIANT** fields = NULL;

		do
		{
			if (FAILED(hResult = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, 0)))
			{
				dprintf("[WMI] Failed to initialize security: %x", hResult);
				break;
			}
			dprintf("[WMI] Security initialised");

			if (FAILED(hResult = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_ALL, IID_PPV_ARGS(&pLocator))))
			{
				dprintf("[WMI] Failed to create WbemLocator: %x", hResult);
				break;
			}
			dprintf("[WMI] WbemLocator created.");

			if (FAILED(hResult = pLocator->ConnectServer(_bstr_t(lpwRoot), NULL, NULL, NULL, WBEM_FLAG_CONNECT_USE_MAX_WAIT, NULL, NULL, &pServices)))
			{
				dprintf("[WMI] Failed to create WbemServices at %S: %x", lpwRoot, hResult);
				break;
			}
			dprintf("[WMI] WbemServices created.");

			if (FAILED(hResult = pServices->ExecQuery(L"WQL", lpwQuery, WBEM_FLAG_FORWARD_ONLY, NULL, &pEnumerator)))
			{
				dprintf("[WMI] Failed to create Enumerator for query %S: %x", lpwQuery, hResult);
				break;
			}
			dprintf("[WMI] Enumerated created.");

			ULONG numFound;
			if (FAILED(hResult = pEnumerator->Next(ENUM_TIMEOUT, 1, &pObj, &numFound)))
			{
				dprintf("[WMI] Failed to get the first query element: %x", lpwQuery, hResult);
				break;
			}
			dprintf("[WMI] First result read. hr=%x p=%p", hResult, pObj);

			if (hResult == WBEM_S_FALSE)
			{
				// this is not an error
				dprintf("[WMI] No results found!");
				break;
			}

			// get the names of the fields out of the first object before doing anything else.
			LPSAFEARRAY pFieldArray = NULL;
			if (FAILED(hResult = pObj->GetNames(NULL, WBEM_FLAG_ALWAYS, NULL, &pFieldArray)))
			{
				dprintf("[WMI] Failed to get field names: %x", hResult);
				break;
			}
			dprintf("[WMI] Field Names extracted. hr=%x p=%p", hResult, pFieldArray);

			// lock the array
			if (FAILED(hResult = SafeArrayLock(pFieldArray)))
			{
				dprintf("[WMI] Failed to get array dimension: %x", hResult);
				break;
			}
			dprintf("[WMI] Field name array locked.");

			do
			{
				dprintf("[WMI] Array dimensions: %u", SafeArrayGetDim(pFieldArray));

				// this array is just one dimension, let's get the bounds of the first dimension
				LONG lBound, uBound;
				if (FAILED(hResult = SafeArrayGetLBound(pFieldArray, 1, &lBound))
					|| FAILED(hResult = SafeArrayGetUBound(pFieldArray, 1, &uBound)))
				{
					dprintf("[WMI] Failed to get array dimensions: %x", hResult);
					break;
				}
				dprintf("[WMI] Bounds: %u to %u", lBound, uBound);

				LONG fieldCount = uBound - lBound - SYSTEM_FIELD_COUNT - 1;
				dprintf("[WMI] Query results in %u fields", fieldCount);

				fields = (VARIANT**)malloc(fieldCount * sizeof(VARIANT**));
				valueTlvs = (Tlv*)malloc(fieldCount * sizeof(Tlv));
				values = (char*)malloc(fieldCount * FIELD_SIZE);
				memset(fields, 0, fieldCount * sizeof(VARIANT**));
				memset(valueTlvs, 0, fieldCount * sizeof(Tlv));
				memset(values, 0, fieldCount * FIELD_SIZE);

				for (LONG i = 0; i < fieldCount; ++i)
				{
					LONG indices[1] = { i + SYSTEM_FIELD_COUNT };
					char* fieldName = values + (i * FIELD_SIZE);
					SafeArrayPtrOfIndex(pFieldArray, indices, (void**)&fields[i]);
					_bstr_t bstr(fields[i]->bstrVal);

					strncpy_s(fieldName, FIELD_SIZE, (const char*)bstr, FIELD_SIZE - 1);

					valueTlvs[i].header.type = TLV_TYPE_EXT_WMI_FIELD;
					valueTlvs[i].header.length = (UINT)strlen(fieldName) + 1;
					valueTlvs[i].buffer = (PUCHAR)fieldName;

					dprintf("[WMI] Added header field: %s", fieldName);
				}

				dprintf("[WMI] added all field headers");
				// add the field names to the packet
				packet_add_tlv_group(response, TLV_TYPE_EXT_WMI_FIELDS, valueTlvs, fieldCount);

				dprintf("[WMI] processing values...");
				// with that horrible pain out of the way, let's actually grab the data
				do
				{
					if (FAILED(hResult))
					{
						dprintf("[WMI] Loop exited via %x", hResult);
						break;
					}

					memset(valueTlvs, 0, fieldCount * sizeof(Tlv));
					memset(values, 0, fieldCount * FIELD_SIZE);

					for (LONG i = 0; i < fieldCount; ++i)
					{
						char* value = values + (i * FIELD_SIZE);
						valueTlvs[i].header.type = TLV_TYPE_EXT_WMI_VALUE;
						valueTlvs[i].buffer = (PUCHAR)value;

						VARIANT varValue;
						VariantInit(&varValue);

						_bstr_t field(fields[i]->bstrVal);
						dprintf("[WMI] Extracting value for %s", (char*)field);
						if (SUCCEEDED(pObj->Get(field, 0, &varValue, NULL, NULL)))
						{
							variant_to_string(_variant_t(varValue), value, FIELD_SIZE);
						}

						valueTlvs[i].header.length = (UINT)strlen(value) + 1;
						dprintf("[WMI] Added value for %s: %s", (char*)_bstr_t(fields[i]->bstrVal), value);
					}

					// add the field values to the packet
					packet_add_tlv_group(response, TLV_TYPE_EXT_WMI_VALUES, valueTlvs, fieldCount);

					pObj->Release();
					pObj = NULL;
				} while ((hResult = pEnumerator->Next(ENUM_TIMEOUT, 1, &pObj, &numFound)) != WBEM_S_FALSE);

			} while (0);

			SafeArrayUnlock(pFieldArray);
		} while (0);

		if (fields)
		{
			free(fields);
		}

		if (values)
		{
			free(values);
		}

		if (valueTlvs)
		{
			free(valueTlvs);
		}

		if (pObj)
		{
			pObj->Release();
		}

		if (pEnumerator)
		{
			pEnumerator->Release();
		}

		if (pServices)
		{
			pServices->Release();
		}

		if (pLocator)
		{
			pLocator->Release();
		}
		CoUninitialize();

		if (SUCCEEDED(hResult))
		{
			hResult = S_OK;
			dprintf("[WMI] Things appeard to go well!");
		}
	}
	else
	{
		dprintf("[WMI] Failed to initialize COM");
	}

	if (FAILED(hResult))
	{
		// if we failed, we're going to convert the error to a string, add it and still return success, but we'll
		// also include the hresult.
		char errorMessage[1024];
		memset(errorMessage, 0, 1024);
		_com_error comError(hResult);
		_snprintf_s(errorMessage, 1024, 1023, "%s (0x%x)", comError.ErrorMessage(), hResult);
		dprintf("[WMI] returning error -> %s", errorMessage);
		packet_add_tlv_string(response, TLV_TYPE_EXT_WMI_ERROR, errorMessage);
		hResult = S_OK;
	}

	return (DWORD)hResult;
}
Ejemplo n.º 10
0
		void Notification(const char* str)
		{
			BSString bstr(str);
			StaticPapyrusFunction<void(BSString*)>::Call(fNotification, &bstr);
		}
Ejemplo n.º 11
0
		void MessageBOX(const char* str)
		{
			BSString bstr(str);
			StaticPapyrusFunction<void(BSString*)>::Call(fMessageBox, &bstr);
		}
Ejemplo n.º 12
0
void save_pushemail(void) 
{
	folder Room;
	int Done = 0;
	StrBuf *Buf;
	char buf[SIZ];
	int msgnum = 0;
	char *pushsetting = bstr("pushsetting");
	char *sms = NULL;

	if (strncasecmp(pushsetting, "textmessage", 11) == 0) {
		sms = bstr("user_sms_number");
	}
	Buf = NewStrBuf();
	memset(&Room, 0, sizeof(folder));
	if (goto_config_room(Buf, &Room) != 0) {
		FreeStrBuf(&Buf);
		FlushFolder(&Room);
		return;	/* oh well. */
	}
	FlushFolder(&Room);

	serv_puts("MSGS ALL|0|1");
	StrBuf_ServGetln(Buf);
	if (GetServerStatus(Buf, NULL) == 8) {
		serv_puts("subj|__ Push email settings __");
		serv_puts("000");
	} else {
		printf("Junk in save_pushemail buffer!: %s\n", buf);
		FreeStrBuf(&Buf);
		return;
	}

	while (!Done &&
	       StrBuf_ServGetln(Buf) >= 0) {
		if ( (StrLength(Buf)==3) && 
		     !strcmp(ChrPtr(Buf), "000")) {
			Done = 1;
			break;
		}
		msgnum = StrTol(Buf);
	}

	if (msgnum > 0L) {
		serv_printf("DELE %d", msgnum);
		StrBuf_ServGetln(Buf);
		GetServerStatus(Buf, NULL);
	}

	serv_printf("ENT0 1||0|1|__ Push email settings __|");
	StrBuf_ServGetln(Buf);
	if (GetServerStatus(Buf, NULL) == 4) {
		serv_puts(pushsetting);
		if (sms != NULL) {
		serv_puts(sms);
		} 
		serv_puts("");
		serv_puts("000");
	}

	/** Go back to the room we're supposed to be in */
	serv_printf("GOTO %s", ChrPtr(WC->CurRoom.name));
	StrBuf_ServGetln(Buf);
	GetServerStatus(Buf, NULL);
	http_redirect("display_pushemail");
	FreeStrBuf(&Buf);
}
Ejemplo n.º 13
0
QoreHashNode* qore_httpclient_priv::send_internal(ExceptionSink* xsink, const char* mname, const char* meth, const char* mpath, const QoreHashNode* headers, const void* data, unsigned size, const ResolvedCallReferenceNode* send_callback, bool getbody, QoreHashNode* info, int timeout_ms, const ResolvedCallReferenceNode* recv_callback, QoreObject* obj) {
   assert(!(data && send_callback));

   // check if method is valid
   method_map_t::const_iterator i = method_map.find(meth);
   if (i == method_map.end()) {
       i = additional_methods_map.find(meth);
       if (i == additional_methods_map.end()) {
          xsink->raiseException("HTTP-CLIENT-METHOD-ERROR", "HTTP method (%s) not recognized.", meth);
          return 0;
       }
   }

   // make sure the capitalized version is used
   meth = i->first.c_str();
   bool bodyp = i->second;

   // use the default timeout value if a zero value is given in the call
   if (!timeout_ms)
      timeout_ms = timeout;

   SafeLocker sl(msock->m);
   Queue* cb_queue = msock->socket->getQueue();

   ReferenceHolder<QoreHashNode> nh(new QoreHashNode, xsink);
   bool keep_alive = true;

   bool transfer_encoding = false;

   if (headers) {
      ConstHashIterator hi(headers);
      while (hi.next()) {
	 // if one of the mandatory headers is found, then ignore it
	 strcase_set_t::iterator si = header_ignore.find(hi.getKey());
	 if (si != header_ignore.end())
	    continue;

	 // otherwise set the value in the hash
	 const AbstractQoreNode* n = hi.getValue();
	 if (!is_nothing(n)) {
	    if (!strcasecmp(hi.getKey(), "transfer-encoding"))
	       transfer_encoding = true;

	    nh->setKeyValue(hi.getKey(), n->refSelf(), xsink);

	    if (!strcasecmp(hi.getKey(), "connection") || (proxy_connection.has_url() && !strcasecmp(hi.getKey(), "proxy-connection"))) {
	       const char* conn = get_string_header(xsink, **nh, hi.getKey(), true);
	       if (*xsink) {
		  disconnect_unlocked();
		  return 0;
	       }
	       if (conn && !strcasecmp(conn, "close"))
		  keep_alive = false;
	    }
	 }
      }
   }

   // add default headers if they weren't overridden
   for (header_map_t::const_iterator hdri = default_headers.begin(), e = default_headers.end(); hdri != e; ++hdri) {
      // look in original headers to see if the key was already given
      if (headers) {
	 bool skip = false;
	 ConstHashIterator hi(headers);
	 while (hi.next()) {
	    if (!strcasecmp(hi.getKey(), hdri->first.c_str())) {
	       skip = true;
	       break;
	    }
	 }
	 if (skip)
	    continue;
      }
      // if there is no message body then do not send the "content-type" header
      if (!data && !send_callback && !strcmp(hdri->first.c_str(), "Content-Type"))
	 continue;
      nh->setKeyValue(hdri->first.c_str(), new QoreStringNode(hdri->second.c_str()), xsink);
   }

   // set Transfer-Encoding: chunked if used with a send callback
   if (send_callback && !transfer_encoding)
      nh->setKeyValue("Transfer-Encoding", new QoreStringNode("chunked"), xsink);

   if (!connection.username.empty()) {
      // check for "Authorization" header
      bool auth_found = false;
      if (headers) {
	 ConstHashIterator hi(headers);
	 while (hi.next()) {
	    if (!strcasecmp(hi.getKey(), "Authorization")) {
	       auth_found = true;
	       break;
	    }
	 }
      }

      if (!auth_found) {
	 QoreString tmp;
	 tmp.sprintf("%s:%s", connection.username.c_str(), connection.password.c_str());
	 QoreStringNode* auth_str = new QoreStringNode("Basic ");
	 auth_str->concatBase64(&tmp);
	 nh->setKeyValue("Authorization", auth_str, xsink);
      }
   }

   // save original HTTP method in case we have to issue a CONNECT request to a proxy for an HTTPS connection
   const char* meth_orig = meth;

   bool use_proxy_connect = false;
   const char* proxy_path = 0;
   ReferenceHolder<QoreHashNode> proxy_headers(xsink);
   QoreString hostport;
   if (!proxy_connected && proxy_connection.has_url()) {
      // use CONNECT if we need to make an HTTPS connection from the proxy
      if (!proxy_connection.ssl && connection.ssl) {
	 meth = "CONNECT";
	 use_proxy_connect = true;
	 hostport.concat(connection.host);
	 if (connection.port)
	    hostport.sprintf(":%d", connection.port);
	 proxy_path = hostport.getBuffer();
	 proxy_headers = new QoreHashNode;
	 proxy_headers->setKeyValue("Host", new QoreStringNode(hostport), xsink);

	 addProxyAuthorization(headers, **proxy_headers, xsink);
      }
      else
	 addProxyAuthorization(headers, **nh, xsink);
   }

   bool host_override = headers ? (bool)headers->getKeyValue("Host") : false;

   int code;
   ReferenceHolder<QoreHashNode> ans(xsink);
   int redirect_count = 0;
   const char* location = 0;

   // flag for aborted chunked sends
   bool send_aborted = false;

   while (true) {
      // set host field automatically if not overridden
      if (!host_override)
	 nh->setKeyValue("Host", getHostHeaderValue(), xsink);

      if (info) {
	 info->setKeyValue("headers", nh->copy(), xsink);
	 if (*xsink)
	    return 0;
      }

      //printd(5, "qore_httpclient_priv::send_internal() meth=%s proxy_path=%s mpath=%s upc=%d\n", meth, proxy_path ? proxy_path : "n/a", mpath, use_proxy_connect);
      // send HTTP message and get response header
      if (use_proxy_connect)
	 ans = sendMessageAndGetResponse(meth, proxy_path, *(*proxy_headers), 0, 0, 0, info, true, timeout_ms, code, send_aborted, xsink);
      else
	 ans = sendMessageAndGetResponse(meth, mpath, *(*nh), data, size, send_callback, info, false, timeout_ms, code, send_aborted, xsink);
      if (!ans)
	 return 0;

      if (info) {
	 info->setKeyValue("response-headers", ans->refSelf(), xsink);
	 if (*xsink)
	    return 0;
      }

      if (code >= 300 && code < 400) {
	 disconnect_unlocked();

	 host_override = false;
	 const QoreStringNode* mess = reinterpret_cast<QoreStringNode*>(ans->getKeyValue("status_message"));

	 const QoreStringNode* loc = get_string_header_node(xsink, **ans, "location");
	 if (*xsink)
	    return 0;
	 const char* location = loc && !loc->empty() ? loc->getBuffer() : 0;
	 if (!location) {
	    sl.unlock();
	    const char* msg = mess ? mess->getBuffer() : "<no message>";
	    xsink->raiseException("HTTP-CLIENT-REDIRECT-ERROR", "no redirect location given for status code %d: message: '%s'", code, msg);
	    return 0;
	 }

	 if (cb_queue)
	    do_redirect_event(cb_queue, msock->socket->getObjectIDForEvents(), loc, mess);

	 if (++redirect_count > max_redirects)
	    break;

	 if (set_url_unlocked(location, xsink)) {
	    sl.unlock();
	    const char* msg = mess ? mess->getBuffer() : "<no message>";
	    xsink->raiseException("HTTP-CLIENT-REDIRECT-ERROR", "exception occurred while setting URL for new location '%s' (code %d: message: '%s')", location, code, msg);
	    return 0;
	 }

	 // set redirect info in info hash if present
	 if (info) {
	    QoreString tmp;
	    tmp.sprintf("redirect-%d", redirect_count);
	    info->setKeyValue(tmp.getBuffer(), loc->refSelf(), xsink);
	    if (*xsink)
	       return 0;

	    tmp.clear();
	    tmp.sprintf("redirect-message-%d", redirect_count);
	    info->setKeyValue(tmp.getBuffer(), mess ? mess->refSelf() : 0, xsink);
	 }

	 // FIXME: reset send callback and send_aborted here

	 // set mpath to NULL so that the new path will be taken
	 mpath = 0;
	 continue;
      }
      else if (use_proxy_connect) {
	 meth = meth_orig;
	 use_proxy_connect = false;
	 proxy_path = 0;
	 if (msock->socket->upgradeClientToSSL(0, 0, xsink)) {
	    disconnect_unlocked();
	    return 0;
	 }
	 proxy_connected = true;

	 // remove "Proxy-Authorization" header
	 nh->removeKey("Proxy-Authorization", xsink);
	 if (*xsink)
	    return 0;

	 // try again as if we are talking directly to the client
	 continue;
      }

      break;
   }

   if (code >= 300 && code < 400) {
      sl.unlock();
      const char* mess = get_string_header(xsink, **ans, "status_message");
      if (!mess)
	 mess = "<no message>";
      if (!location)
	 location = "<no location>";
      xsink->raiseException("HTTP-CLIENT-MAXIMUM-REDIRECTS-EXCEEDED", "maximum redirections (%d) exceeded; redirect code %d to '%s' ignored (message: '%s')", max_redirects, code, location, mess);
      return 0;
   }

   // process content-type
   const QoreStringNode* v = get_string_header_node(xsink, **ans, "content-type");
   if (*xsink) {
      disconnect_unlocked();
      return 0;
   }
   //ans->getKeyValue("content-type");   

   // see if there is a character set specification in the content-type header
   if (v) {
      // save original content-type header before processing
      ans->setKeyValue("_qore_orig_content_type", v->refSelf(), xsink);

      const char* str = v->getBuffer();
      const char* p = strstr(str, "charset=");
      if (p && (p == str || *(p - 1) == ';' || *(p - 1) == ' ')) {
	 // move p to start of encoding
	 const char* c = p + 8;
	 char quote = '\0';
	 if (*c == '\'' || *c == '"') {
	    quote = *c;
	    ++c;
	 }
	 QoreString enc;
	 while (*c && *c != ';' && *c != ' ' && *c != quote)
	    enc.concat(*(c++));
	 
	 if (quote && *c == quote)
	    ++c;

	 printd(5, "QoreHttpClientObject::send_intern() setting encoding to '%s' from content-type header: '%s' (cs=%p c=%p %d)\n", enc.getBuffer(), str, p + 8, c);

	 // set new encoding
	 msock->socket->setEncoding(QEM.findCreate(&enc));
	 // strip from content-type
	 QoreStringNode* nc = new QoreStringNode();
	 // skip any spaces before the charset=
	 while (p != str && (*(p - 1) == ' ' || *(p - 1) == ';'))
	    p--;
	 if (p != str)
	    nc->concat(str, p - str);
	 if (*c)
	    nc->concat(c);
	 ans->setKeyValue("content-type", nc, xsink);
	 str = nc->getBuffer();
      }
      // split into a list if ";" characters are present
      p = strchr(str, ';');
      if (p) {
	 bool multipart = false;
	 QoreListNode* l = new QoreListNode();
	 do {
	    // skip whitespace
	    while (*str == ' ') str++;
	    if (str != p) {
	       int len = p - str;
	       check_headers(str, len, multipart, *(*ans), msock->socket->getEncoding(), xsink);
	       l->push(new QoreStringNode(str, len, msock->socket->getEncoding()));
	    }
	    str = p + 1;
	 } while ((p = strchr(str, ';')));
	 // skip whitespace
	 while (*str == ' ') str++;
	 // add last field
	 if (*str) {
	    check_headers(str, strlen(str), multipart, *(*ans), msock->socket->getEncoding(), xsink);
	    l->push(new QoreStringNode(str, msock->socket->getEncoding()));
	 }
	 ans->setKeyValue("content-type", l, xsink);
      }
   }

   // send headers to recv_callback
   if (recv_callback && msock->socket->priv->runHeaderCallback(xsink, mname, *recv_callback, &msock->m, *ans, send_aborted, obj))
      return 0;

   AbstractQoreNode* body = 0;
   const char* content_encoding = 0;

   // do not read any message body for messages that cannot have one
   // rfc 2616 4.4 p1 (http://tools.ietf.org/html/rfc2616#section-4.4)
   /*
     1.Any response message which "MUST NOT" include a message-body (such
     as the 1xx, 204, and 304 responses and any response to a HEAD
     request) is always terminated by the first empty line after the
     header fields, regardless of the entity-header fields present in
     the message.
    */
   //printd(5, "qore_httpclient_priv::send_internal() this: %p bodyp: %d code: %d\n", this, bodyp, code);

   qore_uncompress_to_string_t dec = 0;

   // code >= 300 && < 400 is already handled above
   if (bodyp && (code < 100 || code >= 200) && code != 204) {
      // see if we should do a binary or string read
      content_encoding = get_string_header(xsink, **ans, "content-encoding");
      if (*xsink) {
	 disconnect_unlocked();
	 return 0;
      }

      if (content_encoding) {
	 // check for misuse (? not sure: check RFCs again) of this field by including a character encoding value
	 if (!strncasecmp(content_encoding, "iso", 3) || !strncasecmp(content_encoding, "utf-", 4)) {
	    msock->socket->setEncoding(QEM.findCreate(content_encoding));
	    content_encoding = 0;
	 }
	 else if (!recv_callback) {
	    // only decode message bodies automatically if there is no receive callback
	    if (!strcasecmp(content_encoding, "deflate") || !strcasecmp(content_encoding, "x-deflate"))
	       dec = qore_inflate_to_string;
	    else if (!strcasecmp(content_encoding, "gzip") || !strcasecmp(content_encoding, "x-gzip"))
	       dec = qore_gunzip_to_string;
	    else if (!strcasecmp(content_encoding, "bzip2") || !strcasecmp(content_encoding, "x-bzip2"))
	       dec = qore_bunzip2_to_string;
	 }
      }

      const char* te = get_string_header(xsink, **ans, "transfer-encoding");
      if (*xsink) {
	 disconnect_unlocked();
	 return 0;
      }
   
      // get response body, if any
      const char* cl = get_string_header(xsink, **ans, "content-length");
      if (*xsink) {
	 disconnect_unlocked();
	 return 0;
      }
      int len = cl ? atoi(cl) : 0;
      
      if (cl && cb_queue)
	 do_content_length_event(cb_queue, msock->socket->getObjectIDForEvents(), len);

      if (te && !strcasecmp(te, "chunked")) { // check for chunked response body
	 if (cb_queue)
	    do_event(cb_queue, msock->socket->getObjectIDForEvents(), QORE_EVENT_HTTP_CHUNKED_START);
	 ReferenceHolder<QoreHashNode> nah(xsink);
	 if (recv_callback) {
	    if (content_encoding)
	       msock->socket->priv->readHttpChunkedBodyBinary(timeout_ms, xsink, QORE_SOURCE_HTTPCLIENT, recv_callback, &msock->m, obj);
	    else
	       msock->socket->priv->readHttpChunkedBody(timeout_ms, xsink, QORE_SOURCE_HTTPCLIENT, recv_callback, &msock->m, obj);
	 }
	 else {
	    if (content_encoding)
	       nah = msock->socket->priv->readHttpChunkedBodyBinary(timeout_ms, xsink, QORE_SOURCE_HTTPCLIENT);
	    else
	       nah = msock->socket->priv->readHttpChunkedBody(timeout_ms, xsink, QORE_SOURCE_HTTPCLIENT);
	 }
	 if (cb_queue)
	    do_event(cb_queue, msock->socket->getObjectIDForEvents(), QORE_EVENT_HTTP_CHUNKED_END);
	 
	 if (!nah && !recv_callback) {
	    if (!msock->socket->isOpen())
	       disconnect_unlocked();
	    return 0;
	 }

	 if (info) {
	    info->setKeyValue("chunked", &True, xsink);
	    if (*xsink)
	       return 0;
	 }
	 
	 if (!recv_callback) {
	    body = nah->takeKeyValue("body");
	    ans->merge(*nah, xsink);
	 }
      }
      else if (getbody || len) {
	 if (content_encoding) {
	    SimpleRefHolder<BinaryNode> bobj(msock->socket->recvBinary(len, timeout_ms, xsink));
	    if (!(*xsink) && bobj)
	       body = bobj.release();
	 }
	 else {
	    QoreStringNodeHolder bstr(msock->socket->recv(len, timeout_ms, xsink));
	    if (!(*xsink) && bstr)
	       body = bstr.release();
	 }
	 
	 if (*xsink && !msock->socket->isOpen())
	    disconnect_unlocked();
	 //printf("body=%p\n", body);
      }  
   }

   // check for connection: close header
   if (!keep_alive)
      disconnect_unlocked();
   else {
      const char* conn = get_string_header(xsink, **ans, "connection", true);
      if (*xsink) {
	 disconnect_unlocked();
	 return 0;
      }
      if (conn && !strcasecmp(conn, "close"))
	 disconnect_unlocked();
   }

   sl.unlock();

   // for content-encoding processing we can run unlocked

   // add body to result hash and process content encoding if necessary
   if (body) {
      if (content_encoding) {
	 if (!dec) {
	    if (!recv_callback) {
	       xsink->raiseException("HTTP-CLIENT-RECEIVE-ERROR", "don't know how to handle content-encoding '%s'", content_encoding);
	       ans = 0;
	    }
	 }
	 else {
	    BinaryNode* bobj = reinterpret_cast<BinaryNode*>(body);
	    QoreStringNode* str = dec(bobj, msock->socket->getEncoding(), xsink);
	    bobj->deref();
	    body = str;
	 }
      }

      if (body) {
	 // send data to recv_callback (already unlocked)
	 if (recv_callback) {
	    ReferenceHolder<> bh(body, xsink);
	    if (msock->socket->priv->runDataCallback(xsink, mname, *recv_callback, 0, body, false)
		|| msock->socket->priv->runHeaderCallback(xsink, mname, *recv_callback, 0, 0, send_aborted, obj))
	       return 0;
	 }
	 else
	    ans->setKeyValue("body", body, xsink);
      }
   }

   // do not throw an exception if a receive callback is used
   if (!recv_callback && !*xsink && (code < 100 || code >= 300)) {
      const char* mess = get_string_header(xsink, **ans, "status_message");
      if (!mess)
	 mess = "<no message>";
      assert(!*xsink);

      xsink->raiseExceptionArg("HTTP-CLIENT-RECEIVE-ERROR", ans.release(), "HTTP status code %d received: message: %s", code, mess);
      return 0;
   }

   return *xsink || recv_callback ? 0 : ans.release();
}
Ejemplo n.º 14
0
LRESULT CAddVideoHtmlDlg::OnLoadCatalog(WPARAM wParam, LPARAM lParam)
{
	if(wParam == NULL)
	{
		MessageBox(TEXT("获取视频分类数据失败,请检查您的网络情况。"), TEXT("错误"), MB_OK|MB_ICONERROR);
		return 0;
	}

	try
	{
		TSTLSTRING strCatalogHtml;
		int iSelectedIndex = -1;

		IXMLDOMDocument* pDOM = NULL;
		HRESULT hr = CoCreateInstance(CLSID_DOMDocument, NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void**)&pDOM);
		if(hr != S_OK)
		{
			throw Exception(TEXT("解析视频分类数据失败。"));
		}

		VARIANT_BOOL loaded = VARIANT_FALSE;
		hr = pDOM->loadXML(CComBSTR((LPCOLESTR)wParam), &loaded);
		if(hr != S_OK || loaded == VARIANT_FALSE)
		{
			pDOM->Release();
			throw Exception(TEXT("解析视频分类数据失败。"));
		}

		IXMLDOMNodeList* pNodeList = NULL;
		hr = pDOM->get_childNodes(&pNodeList);
		if(hr != S_OK)
		{
			pDOM->Release();
			throw Exception(TEXT("解析视频分类数据失败。"));
		}

		IXMLDOMNode* pRoot = NULL;
		hr = pNodeList->get_item(1, &pRoot);
		if(hr != S_OK)
		{
			pNodeList->Release();
			pDOM->Release();
			throw Exception(TEXT("解析视频分类数据失败。"));
		}

		IXMLDOMNodeList* pRootChildren = NULL;
		hr = pRoot->get_childNodes(&pRootChildren);
		if(hr != S_OK)
		{
			pRoot->Release();
			pNodeList->Release();
			pDOM->Release();
			throw Exception(TEXT("解析视频分类数据失败。"));
		}

		IXMLDOMNode* pResultNote = NULL;
		hr = pRootChildren->get_item(0, &pResultNote);
		if(hr != S_OK)
		{
			pRootChildren->Release();
			pRoot->Release();
			pNodeList->Release();
			pDOM->Release();
			throw Exception(TEXT("解析视频分类数据失败。"));
		}

		IXMLDOMNodeList* pResultChildren = NULL;
		hr = pResultNote->get_childNodes(&pResultChildren);
		if(hr != S_OK)
		{
			pResultNote->Release();
			pRootChildren->Release();
			pRoot->Release();
			pNodeList->Release();
			pDOM->Release();
			throw Exception(TEXT("解析视频分类数据失败。"));
		}

		IXMLDOMNode* pResultStatusNote = NULL;
		hr = pRootChildren->get_item(0, &pResultStatusNote);
		if(hr != S_OK)
		{
			pResultChildren->Release();
			pResultNote->Release();
			pRootChildren->Release();
			pRoot->Release();
			pNodeList->Release();
			pDOM->Release();
			throw Exception(TEXT("解析视频分类数据失败。"));
		}

		CComBSTR bstrResultStatus;
		hr = pResultStatusNote->get_text(&bstrResultStatus);
		if(hr != S_OK)
		{
			pResultStatusNote->Release();
			pResultChildren->Release();
			pResultNote->Release();
			pRootChildren->Release();
			pRoot->Release();
			pNodeList->Release();
			pDOM->Release();
			throw Exception(TEXT("解析视频分类数据失败。"));
		}
		pResultStatusNote->Release();

		if(bstrResultStatus != TEXT("o"))
		{
			IXMLDOMNode* pResultMessageNote = NULL;
			hr = pRootChildren->get_item(1, &pResultMessageNote);
			if(hr != S_OK)
			{
				pResultChildren->Release();
				pResultNote->Release();
				pRootChildren->Release();
				pRoot->Release();
				pNodeList->Release();
				pDOM->Release();
				throw Exception(TEXT("解析视频分类数据失败。"));
			}

			CComBSTR bstrResultMessage;
			hr = pResultMessageNote->get_text(&bstrResultMessage);
			if(hr != S_OK)
			{
				pResultMessageNote->Release();
				pResultChildren->Release();
				pResultNote->Release();
				pRootChildren->Release();
				pRoot->Release();
				pNodeList->Release();
				pDOM->Release();
				throw Exception(TEXT("解析视频分类数据失败。"));
			}
			pResultMessageNote->Release();
			pResultChildren->Release();
			pResultNote->Release();
			pRootChildren->Release();
			pRoot->Release();
			pNodeList->Release();
			pDOM->Release();

			throw Exception(bstrResultMessage.m_str);
		}

		pResultChildren->Release();
		pResultNote->Release();

		IXMLDOMNode* pItemNote = NULL;
		hr = pRootChildren->get_item(1, &pItemNote);
		if(hr != S_OK)
		{
			pRootChildren->Release();
			pRoot->Release();
			pNodeList->Release();
			pDOM->Release();
			throw Exception(TEXT("解析视频分类数据失败。"));
		}

		IXMLDOMNodeList* pItemChildren = NULL;
		hr = pItemNote->get_childNodes(&pItemChildren);
		if(hr != S_OK)
		{
			pItemNote->Release();
			pRootChildren->Release();
			pRoot->Release();
			pNodeList->Release();
			pDOM->Release();
			throw Exception(TEXT("解析视频分类数据失败。"));
		}

		long ItemCount = 0;
		pItemChildren->get_length(&ItemCount);
		if(hr != S_OK)
		{
			pItemChildren->Release();
			pItemNote->Release();
			pRootChildren->Release();
			pRoot->Release();
			pNodeList->Release();
			pDOM->Release();
			throw Exception(TEXT("解析视频分类数据失败。"));
		}

		for(int i=0; i<ItemCount; ++i)
		{
			IXMLDOMNode* pCatalogItemNote = NULL;
			hr = pItemChildren->get_item(i, &pCatalogItemNote);
			if(hr != S_OK)
			{
				pItemChildren->Release();
				pItemNote->Release();
				pRootChildren->Release();
				pRoot->Release();
				pNodeList->Release();
				pDOM->Release();
				throw Exception(TEXT("解析视频分类数据失败。"));
			}

			IXMLDOMNodeList* pCatalogItemChildren = NULL;
			hr = pCatalogItemNote->get_childNodes(&pCatalogItemChildren);
			if(hr != S_OK)
			{
				pCatalogItemNote->Release();
				pItemChildren->Release();
				pItemNote->Release();
				pRootChildren->Release();
				pRoot->Release();
				pNodeList->Release();
				pDOM->Release();
				throw Exception(TEXT("解析视频分类数据失败。"));
			}

			IXMLDOMNode* pCatalogIdNote = NULL;
			hr = pCatalogItemChildren->get_item(0, &pCatalogIdNote);
			if(hr != S_OK)
			{
				pCatalogItemChildren->Release();
				pCatalogItemNote->Release();
				pItemChildren->Release();
				pItemNote->Release();
				pRootChildren->Release();
				pRoot->Release();
				pNodeList->Release();
				pDOM->Release();
				throw Exception(TEXT("解析视频分类数据失败。"));
			}

			CComBSTR bstrCatalogId;
			hr = pCatalogIdNote->get_text(&bstrCatalogId);
			if(hr != S_OK)
			{
				pCatalogIdNote->Release();
				pCatalogItemChildren->Release();
				pCatalogItemNote->Release();
				pItemChildren->Release();
				pItemNote->Release();
				pRootChildren->Release();
				pRoot->Release();
				pNodeList->Release();
				pDOM->Release();
				throw Exception(TEXT("解析视频分类数据失败。"));
			}
			pCatalogIdNote->Release();

			IXMLDOMNode* pCatalogNameNote = NULL;
			hr = pCatalogItemChildren->get_item(1, &pCatalogNameNote);
			if(hr != S_OK)
			{
				pCatalogItemChildren->Release();
				pCatalogItemNote->Release();
				pItemChildren->Release();
				pItemNote->Release();
				pRootChildren->Release();
				pRoot->Release();
				pNodeList->Release();
				pDOM->Release();
				throw Exception(TEXT("解析视频分类数据失败。"));
			}
			CComBSTR bstrCatalogName;
			hr = pCatalogNameNote->get_text(&bstrCatalogName);
			if(hr != S_OK)
			{
				pCatalogNameNote->Release();
				pCatalogItemChildren->Release();
				pCatalogItemNote->Release();
				pItemChildren->Release();
				pItemNote->Release();
				pRootChildren->Release();
				pRoot->Release();
				pNodeList->Release();
				pDOM->Release();
				throw Exception(TEXT("解析视频分类数据失败。"));
			}
			pCatalogNameNote->Release();

			pCatalogItemChildren->Release();
			pCatalogItemNote->Release();

			TSTLSTRING strCurrID = TSTLSTRING(COLE2T(bstrCatalogId));

			TSTLSTRING strLastCatalog = ConfigureManager::GetInstance().GetLastCatalog();
			TSTLSTRING strCurrName = TSTLSTRING(COLE2T(bstrCatalogName));
			bool IsSelected = ((strLastCatalog.empty() && strCurrName == TEXT("其他")) ||
				(!strLastCatalog.empty() && strLastCatalog.compare(strCurrID) == 0));

			strCatalogHtml.append(TEXT("<div class=\"ComboxListItem\" onmouseover=\"this.className='ComboxListItemSelected';\" onclick=\"OnCatalogComboxClick();\" onmouseout=\"this.className='ComboxListItem';\" Value=\""));
			strCatalogHtml.append(strCurrID);
			strCatalogHtml.append(TEXT("\">"));
			strCatalogHtml.append(strCurrName);
			strCatalogHtml.append(TEXT("</div>"));

			if(IsSelected)
				iSelectedIndex = i;
		}

		pItemChildren->Release();
		pItemNote->Release();

		pRootChildren->Release();
		pRoot->Release();
		pNodeList->Release();
		pDOM->Release();

		DISPPARAMS dp;
		memset(&dp, 0, sizeof(DISPPARAMS));
		dp.cArgs = 2;
		dp.cNamedArgs = 0;

		VARIANTARG arg[2];
		memset(arg, 0, sizeof(VARIANTARG) * 2);
		dp.rgvarg = arg;

		CComBSTR bstr(strCatalogHtml.c_str());
		arg[0].vt = VT_BSTR;
		bstr.CopyTo(&arg[0].bstrVal);
		arg[1].vt = VT_INT;
		arg[1].intVal = iSelectedIndex;

		m_lpCatalogInvoke->Invoke(
			0, 
			IID_NULL, 
			LOCALE_SYSTEM_DEFAULT,
			DISPATCH_METHOD,
			&dp,
			NULL, NULL, NULL);

	}
	catch(Exception& error)
	{
		MessageBox(error.GetMessage().c_str(), TEXT("错误"), MB_OK|MB_ICONERROR);
	}

	return 0;
}
Ejemplo n.º 15
0
void
NDalign::display(char    *prefix,
                 int32    aLo,   int32   aHi,
                 int32    bLo,   int32   bHi,
                 int32   *delta, int32   deltaLen,
                 bool     displayIt,
                 bool     saveStats) {

  uint32 matches    = 0;
  uint32 errors     = 0;
  uint32 gapmatches = 0;
  uint32 freegaps   = 0;

  if (_topDisplay == NULL) {
    _topDisplay = new char [2 * AS_MAX_READLEN + 1];
    _botDisplay = new char [2 * AS_MAX_READLEN + 1];
    _resDisplay = new char [2 * AS_MAX_READLEN + 1];
  }

  char *a      = astr() + aLo;
  int32 a_len = aHi - aLo;

  char *b      = bstr() + bLo;
  int32 b_len = bHi - bLo;

  int32 top_len = 0;

  {
    int32 i = 0;
    int32 j = 0;

    for (int32 k = 0;  k < deltaLen;  k++) {
      for (int32 m = 1;  m < abs (delta[k]);  m++) {
        _topDisplay[top_len++] = a[i++];
        j++;
      }

      if (delta[k] < 0) {
        _topDisplay[top_len++] = '-';
        j++;

      } else {
        _topDisplay[top_len++] = a[i++];
      }
    }

    while (i < a_len && j < b_len) {
      _topDisplay[top_len++] = a[i++];
      j++;
    }

    _topDisplay[top_len] = 0;
  }


  int32 bot_len = 0;

  {
    int32 i = 0;
    int32 j = 0;

    for (int32 k = 0;  k < deltaLen;  k++) {
      for (int32 m = 1;  m < abs (delta[k]);  m++) {
        _botDisplay[bot_len++] = b[j++];
        i++;
      }

      if (delta[k] > 0) {
        _botDisplay[bot_len++] = '-';
        i++;

      } else {
        _botDisplay[bot_len++] = b[j++];
      }
    }

    while (j < b_len && i < a_len) {
      _botDisplay[bot_len++] = b[j++];
      i++;
    }

    _botDisplay[bot_len] = 0;
  }

  //  Compute stats, build the result display.

  {
    for (int32 i=0; (i < top_len) || (i < bot_len); i++) {
      char T = _topDisplay[i];
      char B = _botDisplay[i];

      char t = tolower(T);
      char b = tolower(B);

      //  A minor-allele match if the lower case matches, but upper case doesn't
      if      ((t == b) && (T != B)) {
        _resDisplay[i] = '\'';
        gapmatches++;
      }

      //  A free-gap if either is lowercase
      else if (((t == T) && (b == '-')) ||  //  T is lowercase, B is a gap
               ((b == B) && (t == '-'))) {  //  B is lowercase, T is a gap
        _resDisplay[i] = '-';
        freegaps++;
      }

      //  A match if the originals match
      else if ((t == b) && (T == B)) {
        _resDisplay[i] = ' ';
        matches++;
      }

      //  Otherwise, an error
      else {
        _resDisplay[i] = '^';
        errors++;
      }
    }

    _resDisplay[ max(top_len, bot_len) ] = 0;
  }

  //  Really display it?

  if (displayIt == true) {
    for (int32 i=0; (i < top_len) || (i < bot_len); i += DISPLAY_WIDTH) {
      fprintf(stderr, "%s%d\n", prefix, i);

      fprintf(stderr, "%sA: ", prefix);
      for (int32 j=0;  (j < DISPLAY_WIDTH) && (i+j < top_len);  j++)
        putc(_topDisplay[i+j], stderr);
      fprintf(stderr, "\n");

      fprintf(stderr, "%sB: ", prefix);
      for (int32 j=0; (j < DISPLAY_WIDTH) && (i+j < bot_len); j++)
        putc(_botDisplay[i+j], stderr);
      fprintf(stderr, "\n");

      fprintf(stderr, "%s   ", prefix);
      for (int32 j=0; (j<DISPLAY_WIDTH) && (i+j < bot_len) && (i+j < top_len); j++)
        putc(_resDisplay[i+j], stderr);
      fprintf(stderr, "\n");
    }
  }

  //  Update statistics?  Avoid a whole ton of if statements by always counting then changing only here.

  if (saveStats) {
    _matches    = matches;
    _errors     = errors;
    _gapmatches = gapmatches;
    _freegaps   = freegaps;
  }
}
Ejemplo n.º 16
0
/*
 * Display the revision history for a wiki page (template callback)
 */
void tmplput_display_wiki_history(StrBuf *Target, WCTemplputParams *TP)
{
	char pagename[128];
	StrBuf *Buf;
	int row = 0;

	safestrncpy(pagename, bstr("page"), sizeof pagename);
	str_wiki_index(pagename);

	serv_printf("WIKI history|%s", pagename);
	Buf = NewStrBuf();
	StrBuf_ServGetln(Buf);
	if (GetServerStatus(Buf, NULL) == 1) {

		time_t rev_date;
		char rev_date_displayed[64];
		StrBuf *rev_uuid = NewStrBuf();
		StrBuf *author = NewStrBuf();
		StrBuf *node = NewStrBuf();

		wc_printf("<table class=\"wiki_history_background\">");

		wc_printf("<th>%s</th>", _("Date"));
		wc_printf("<th>%s</th>", _("Author"));

		while((StrBuf_ServGetln(Buf) >= 0) &&  strcmp(ChrPtr(Buf), "000")) {

			rev_date = extract_long(ChrPtr(Buf), 1);
			webcit_fmt_date(rev_date_displayed, sizeof rev_date_displayed, rev_date, DATEFMT_FULL);
			StrBufExtract_token(author, Buf, 2, '|');

			wc_printf("<tr bgcolor=\"%s\">", ((row%2) ? "#FFFFFF" : "#DDDDDD"));
			wc_printf("<td>%s</td><td>", rev_date_displayed);
			if (!strcasecmp(ChrPtr(node), (char *)WC->serv_info->serv_nodename)) {
				escputs(ChrPtr(author));
				wc_printf(" @ ");
				escputs(ChrPtr(node));
			}
			else {
				wc_printf("<a href=\"showuser?who=");
				urlescputs(ChrPtr(author));
				wc_printf("\">");
				escputs(ChrPtr(author));
				wc_printf("</a>");
			}
			wc_printf("</td>");

			if (row == 0) {
				wc_printf("<td><a href=\"wiki?page=%s", bstr("page"));
				wc_printf("?go="); urlescputs(ChrPtr(WC->CurRoom.name));
				wc_printf("\">%s</a></td>", _("(show)"));
				wc_printf("<td>(%s)</td>", _("Current version"));
			}

			else {
				wc_printf("<td><a href=\"wiki?page=%s?rev=%s",
					bstr("page"),
					ChrPtr(rev_uuid)
				);
				wc_printf("?go="); urlescputs(ChrPtr(WC->CurRoom.name));
				wc_printf("\">%s</a></td>", _("(show)"));
				wc_printf("<td><a href=\"javascript:GetLoggedInFirst(encodeURIComponent('wiki?page=%s?rev=%s?revert=1'))\">%s</a></td>",
					bstr("page"),
					ChrPtr(rev_uuid),
					_("(revert)")
				);
			}
			wc_printf("</tr>\n");

			/* Extract all fields except the author and date after displaying the row.  This
			 * is deliberate, because the timestamp reflects when the diff was written, not
			 * when the version which it reflects was written.  Similarly, the name associated
			 * with each diff is the author who created the newer version of the page that
			 * made the diff happen.
			 */
			StrBufExtract_token(rev_uuid, Buf, 0, '|');
			StrBufExtract_token(node, Buf, 3, '|');
			++row;
		}

		wc_printf("</table>\n");
		FreeStrBuf(&author);
		FreeStrBuf(&node);
		FreeStrBuf(&rev_uuid);
	}
	else {
		wc_printf("%s", ChrPtr(Buf));
	}

	FreeStrBuf(&Buf);
}
Ejemplo n.º 17
0
static stream_t *open_stream_plugin(const stream_info_t *sinfo,
                                    const char *filename,
                                    int mode, struct MPOpts *options,
                                    int *file_format, int *ret,
                                    char **redirected_url)
{
    void* arg = NULL;
    stream_t* s;
    m_struct_t* desc = (m_struct_t*)sinfo->opts;

    // Parse options
    if(desc) {
        arg = m_struct_alloc(desc);
        if(sinfo->opts_url) {
            m_option_t url_opt =
            { "stream url", arg , CONF_TYPE_CUSTOM_URL, 0, 0 ,0, (void *)sinfo->opts };
            if (m_option_parse(&url_opt, bstr("stream url"), bstr(filename), false, arg) < 0) {
                mp_tmsg(MSGT_OPEN,MSGL_ERR, "URL parsing failed on url %s\n",filename);
                m_struct_free(desc,arg);
                return NULL;
            }
        }
    }
    s = new_stream(-2,-2);
    s->opts = options;
    s->url=strdup(filename);
    s->flags |= mode;
    *ret = sinfo->open(s,mode,arg,file_format);
    if((*ret) != STREAM_OK) {
#ifdef CONFIG_NETWORKING
        if (*ret == STREAM_REDIRECTED && redirected_url) {
            if (s->streaming_ctrl && s->streaming_ctrl->url
                    && s->streaming_ctrl->url->url)
                *redirected_url = strdup(s->streaming_ctrl->url->url);
            else
                *redirected_url = NULL;
        }
        streaming_ctrl_free(s->streaming_ctrl);
#endif
        free(s->url);
        free(s);
        return NULL;
    }

    s->cache_size = 0;
    if (s->streaming_ctrl && s->streaming_ctrl->buffering) {
        // Set default cache size to use if user does not specify it.
        // buffer in KBytes, *5 assuming the prefill is 20% of the buffer.
        s->cache_size = s->streaming_ctrl->prebuffer_size / 1024 * 5;
        if (s->cache_size < 64)
            s->cache_size = 64;
    }

    if(s->type <= -2)
        mp_msg(MSGT_OPEN,MSGL_WARN, "Warning streams need a type !!!!\n");
    if(s->flags & MP_STREAM_SEEK && !s->seek)
        s->flags &= ~MP_STREAM_SEEK;
    if(s->seek && !(s->flags & MP_STREAM_SEEK))
        s->flags |= MP_STREAM_SEEK;

    s->mode = mode;

    mp_msg(MSGT_OPEN,MSGL_V, "STREAM: [%s] %s\n",sinfo->name,filename);
    mp_msg(MSGT_OPEN,MSGL_V, "STREAM: Description: %s\n",sinfo->info);
    mp_msg(MSGT_OPEN,MSGL_V, "STREAM: Author: %s\n", sinfo->author);
    mp_msg(MSGT_OPEN,MSGL_V, "STREAM: Comment: %s\n", sinfo->comment);

    return s;
}
Ejemplo n.º 18
0
void editfloorpic(void){
	char buf[SIZ];
	snprintf(buf, SIZ, "_floorpic_|%s",
		 bstr("which_floor"));
	do_graphics_upload(buf);
}
Ejemplo n.º 19
0
// mkzasm writes zasm_$GOOS_$GOARCH.h,
// which contains struct offsets for use by
// assembly files.  It also writes a copy to the work space
// under the name zasm_GOOS_GOARCH.h (no expansion).
// 
void
mkzasm(char *dir, char *file)
{
	int i, n;
	char *aggr, *p;
	Buf in, b, out, exp;
	Vec argv, lines, fields;

	binit(&in);
	binit(&b);
	binit(&out);
	binit(&exp);
	vinit(&argv);
	vinit(&lines);
	vinit(&fields);
	
	bwritestr(&out, "// auto generated by go tool dist\n\n");
	for(i=0; i<nelem(zasmhdr); i++) {
		if(hasprefix(goarch, zasmhdr[i].goarch) && hasprefix(goos, zasmhdr[i].goos)) {
			bwritestr(&out, zasmhdr[i].hdr);
			goto ok;
		}
	}
	fatal("unknown $GOOS/$GOARCH in mkzasm");
ok:

	// Run 6c -D GOOS_goos -D GOARCH_goarch -I workdir -a -n -o workdir/proc.acid proc.c
	// to get acid [sic] output.
	vreset(&argv);
	vadd(&argv, bpathf(&b, "%s/%sc", tooldir, gochar));
	vadd(&argv, "-D");
	vadd(&argv, bprintf(&b, "GOOS_%s", goos));
	vadd(&argv, "-D");
	vadd(&argv, bprintf(&b, "GOARCH_%s", goarch));
	vadd(&argv, "-I");
	vadd(&argv, bprintf(&b, "%s", workdir));
	vadd(&argv, "-a");
	vadd(&argv, "-n");
	vadd(&argv, "-o");
	vadd(&argv, bpathf(&b, "%s/proc.acid", workdir));
	vadd(&argv, "proc.c");
	runv(nil, dir, CheckExit, &argv);
	readfile(&in, bpathf(&b, "%s/proc.acid", workdir));
	
	// Convert input like
	//	aggr G
	//	{
	//		Gobuf 24 sched;
	//		'Y' 48 stack0;
	//	}
	//	StackMin = 128;
	// into output like
	//	#define g_sched 24
	//	#define g_stack0 48
	//	#define const_StackMin 128
	aggr = nil;
	splitlines(&lines, bstr(&in));
	for(i=0; i<lines.len; i++) {
		splitfields(&fields, lines.p[i]);
		if(fields.len == 2 && streq(fields.p[0], "aggr")) {
			if(streq(fields.p[1], "G"))
				aggr = "g";
			else if(streq(fields.p[1], "M"))
				aggr = "m";
			else if(streq(fields.p[1], "P"))
				aggr = "p";
			else if(streq(fields.p[1], "Gobuf"))
				aggr = "gobuf";
			else if(streq(fields.p[1], "LibCall"))
				aggr = "libcall";
			else if(streq(fields.p[1], "WinCallbackContext"))
				aggr = "cbctxt";
			else if(streq(fields.p[1], "SEH"))
				aggr = "seh";
		}
		if(hasprefix(lines.p[i], "}"))
			aggr = nil;
		if(aggr && hasprefix(lines.p[i], "\t") && fields.len >= 2) {
			n = fields.len;
			p = fields.p[n-1];
			if(p[xstrlen(p)-1] == ';')
				p[xstrlen(p)-1] = '\0';
			bwritestr(&out, bprintf(&b, "#define %s_%s %s\n", aggr, fields.p[n-1], fields.p[n-2]));
		}
		if(fields.len == 3 && streq(fields.p[1], "=")) { // generated from enumerated constants
			p = fields.p[2];
			if(p[xstrlen(p)-1] == ';')
				p[xstrlen(p)-1] = '\0';
			bwritestr(&out, bprintf(&b, "#define const_%s %s\n", fields.p[0], p));
		}
	}

	// Some #defines that are used for .c files.
	if(streq(goos, "windows")) {
		bwritestr(&out, bprintf(&b, "#define cb_max %d\n", MAXWINCB));
	}
	
	xgetenv(&exp, "GOEXPERIMENT");
	bwritestr(&out, bprintf(&b, "#define GOEXPERIMENT \"%s\"\n", bstr(&exp)));
	
	// Write both to file and to workdir/zasm_GOOS_GOARCH.h.
	writefile(&out, file, 0);
	writefile(&out, bprintf(&b, "%s/zasm_GOOS_GOARCH.h", workdir), 0);

	bfree(&in);
	bfree(&b);
	bfree(&out);
	bfree(&exp);
	vfree(&argv);
	vfree(&lines);
	vfree(&fields);
}
Ejemplo n.º 20
0
// setup sets up the tree for the initial build.
static void
setup(void)
{
	int i;
	Buf b;
	char *p;

	binit(&b);

	// Create bin directory.
	p = bpathf(&b, "%s/bin", goroot);
	if(!isdir(p))
		xmkdir(p);

	// Create package directory.
	p = bpathf(&b, "%s/pkg", goroot);
	if(!isdir(p))
		xmkdir(p);
	p = bpathf(&b, "%s/pkg/%s_%s", goroot, gohostos, gohostarch);
	if(rebuildall)
		xremoveall(p);
	xmkdirall(p);
	if(!streq(goos, gohostos) || !streq(goarch, gohostarch)) {
		p = bpathf(&b, "%s/pkg/%s_%s", goroot, goos, goarch);
		if(rebuildall)
			xremoveall(p);
		xmkdirall(p);
	}

	// Create object directory.
	// We keep it in pkg/ so that all the generated binaries
	// are in one tree.  If pkg/obj/libgc.a exists, it is a dreg from
	// before we used subdirectories of obj.  Delete all of obj
	// to clean up.
	bpathf(&b, "%s/pkg/obj/libgc.a", goroot);
	if(isfile(bstr(&b)))
		xremoveall(bpathf(&b, "%s/pkg/obj", goroot));
	p = bpathf(&b, "%s/pkg/obj/%s_%s", goroot, gohostos, gohostarch);
	if(rebuildall)
		xremoveall(p);
	xmkdirall(p);

	// Create tool directory.
	// We keep it in pkg/, just like the object directory above.
	if(rebuildall)
		xremoveall(tooldir);
	xmkdirall(tooldir);

	// Remove tool binaries from before the tool/gohostos_gohostarch
	xremoveall(bpathf(&b, "%s/bin/tool", goroot));

	// Remove old pre-tool binaries.
	for(i=0; i<nelem(oldtool); i++)
		xremove(bpathf(&b, "%s/bin/%s", goroot, oldtool[i]));

	// If $GOBIN is set and has a Go compiler, it must be cleaned.
	for(i=0; gochars[i]; i++) {
		if(isfile(bprintf(&b, "%s%s%c%s", gobin, slash, gochars[i], "g"))) {
			for(i=0; i<nelem(oldtool); i++)
				xremove(bprintf(&b, "%s%s%s", gobin, slash, oldtool[i]));
			break;
		}
	}

	// For release, make sure excluded things are excluded.
	if(hasprefix(goversion, "release.") || hasprefix(goversion, "go")) {
		for(i=0; i<nelem(unreleased); i++)
			if(isdir(bpathf(&b, "%s/%s", goroot, unreleased[i])))
				fatal("%s should not exist in release build", bstr(&b));
	}

	bfree(&b);
}
Ejemplo n.º 21
0
// mkzasm writes zasm_$GOOS_$GOARCH.h,
// which contains struct offsets for use by
// assembly files.  It also writes a copy to the work space
// under the name zasm_GOOS_GOARCH.h (no expansion).
// 
void
mkzasm(char *dir, char *file)
{
	int i, n;
	char *aggr, *p;
	Buf in, b, out;
	Vec argv, lines, fields;

	binit(&in);
	binit(&b);
	binit(&out);
	vinit(&argv);
	vinit(&lines);
	vinit(&fields);
	
	bwritestr(&out, "// auto generated by go tool dist\n\n");
	for(i=0; i<nelem(zasmhdr); i++) {
		if(hasprefix(goarch, zasmhdr[i].goarch) && hasprefix(goos, zasmhdr[i].goos)) {
			bwritestr(&out, zasmhdr[i].hdr);
			goto ok;
		}
	}
	fatal("unknown $GOOS/$GOARCH in mkzasm");
ok:

	// Run 6c -DGOOS_goos -DGOARCH_goarch -Iworkdir -a proc.c
	// to get acid [sic] output.
	vreset(&argv);
	vadd(&argv, bpathf(&b, "%s/%sc", tooldir, gochar));
	vadd(&argv, bprintf(&b, "-DGOOS_%s", goos));
	vadd(&argv, bprintf(&b, "-DGOARCH_%s", goarch));
	vadd(&argv, bprintf(&b, "-I%s", workdir));
	vadd(&argv, "-a");
	vadd(&argv, "proc.c");
	runv(&in, dir, CheckExit, &argv);
	
	// Convert input like
	//	aggr G
	//	{
	//		Gobuf 24 sched;
	//		'Y' 48 stack0;
	//	}
	// into output like
	//	#define g_sched 24
	//	#define g_stack0 48
	//
	aggr = nil;
	splitlines(&lines, bstr(&in));
	for(i=0; i<lines.len; i++) {
		splitfields(&fields, lines.p[i]);
		if(fields.len == 2 && streq(fields.p[0], "aggr")) {
			if(streq(fields.p[1], "G"))
				aggr = "g";
			else if(streq(fields.p[1], "M"))
				aggr = "m";
			else if(streq(fields.p[1], "Gobuf"))
				aggr = "gobuf";
			else if(streq(fields.p[1], "WinCall"))
				aggr = "wincall";
		}
		if(hasprefix(lines.p[i], "}"))
			aggr = nil;
		if(aggr && hasprefix(lines.p[i], "\t") && fields.len >= 2) {
			n = fields.len;
			p = fields.p[n-1];
			if(p[xstrlen(p)-1] == ';')
				p[xstrlen(p)-1] = '\0';
			bwritestr(&out, bprintf(&b, "#define %s_%s %s\n", aggr, fields.p[n-1], fields.p[n-2]));
		}
	}
	
	// Write both to file and to workdir/zasm_GOOS_GOARCH.h.
	writefile(&out, file, 0);
	writefile(&out, bprintf(&b, "%s/zasm_GOOS_GOARCH.h", workdir), 0);

	bfree(&in);
	bfree(&b);
	bfree(&out);
	vfree(&argv);
	vfree(&lines);
	vfree(&fields);
}
Ejemplo n.º 22
0
/*
 * Background ajax call to receive updates from the browser when a note is moved, resized, or updated.
 */
void ajax_update_note(void) {

	char buf[1024];
	int msgnum;
	struct vnote *v = NULL;

        if (!havebstr("note_uid")) {
		begin_ajax_response();
		wc_printf("Received ajax_update_note() request without a note UID.");
		end_ajax_response();
		return;
	}

	serv_printf("EUID %s", bstr("note_uid"));
	serv_getln(buf, sizeof buf);
	if (buf[0] != '2') {
		begin_ajax_response();
		wc_printf("Cannot find message containing vNote with the requested uid!");
		end_ajax_response();
		return;
	}
	msgnum = atol(&buf[4]);
	
	/* Was this request a delete operation?  If so, nuke it... */
	if (havebstr("deletenote")) {
		if (!strcasecmp(bstr("deletenote"), "yes")) {
			serv_printf("DELE %d", msgnum);
			serv_getln(buf, sizeof buf);
			begin_ajax_response();
			wc_printf("%s", buf);
			end_ajax_response();
			return;
		}
	}

	/* If we get to this point it's an update, not a delete */
	v = vnote_new_from_msg(msgnum, 0);
	if (!v) {
		begin_ajax_response();
		wc_printf("Cannot locate a vNote within message %d\n", msgnum);
		end_ajax_response();
		return;
	}

	/* Make any requested changes */
        if (havebstr("top")) {
		v->pos_top = atoi(bstr("top"));
	}
        if (havebstr("left")) {
		v->pos_left = atoi(bstr("left"));
	}
        if (havebstr("height")) {
		v->pos_height = atoi(bstr("height"));
	}
        if (havebstr("width")) {
		v->pos_width = atoi(bstr("width"));
	}
        if (havebstr("red")) {
		v->color_red = atoi(bstr("red"));
	}
        if (havebstr("green")) {
		v->color_green = atoi(bstr("green"));
	}
        if (havebstr("blue")) {
		v->color_blue = atoi(bstr("blue"));
	}
        if (havebstr("value")) {	/* I would have preferred 'body' but InPlaceEditor hardcodes 'value' */
		if (v->body) free(v->body);
		v->body = strdup(bstr("value"));
	}

	/* Serialize it and save it to the message base.  Server will delete the old one. */
	write_vnote_to_server(v);

	begin_ajax_response();
	if (v->body) {
		escputs(v->body);
	}
	end_ajax_response();

	vnote_free(v);
}
Ejemplo n.º 23
0
// mkzruntimedefs writes zruntime_defs_$GOOS_$GOARCH.h,
// which contains Go struct definitions equivalent to the C ones.
// Mostly we just write the output of 6c -q to the file.
// However, we run it on multiple files, so we have to delete
// the duplicated definitions, and we don't care about the funcs
// and consts, so we delete those too.
// 
void
mkzruntimedefs(char *dir, char *file)
{
	int i, skip;
	char *p;
	Buf in, b, out;
	Vec argv, lines, fields, seen;
	
	binit(&in);
	binit(&b);
	binit(&out);
	vinit(&argv);
	vinit(&lines);
	vinit(&fields);
	vinit(&seen);
	
	bwritestr(&out, "// auto generated by go tool dist\n"
		"\n"
		"package runtime\n"
		"import \"unsafe\"\n"
		"var _ unsafe.Pointer\n"
		"\n"
	);

	
	// Run 6c -DGOOS_goos -DGOARCH_goarch -Iworkdir -q
	// on each of the runtimedefs C files.
	vadd(&argv, bpathf(&b, "%s/%sc", tooldir, gochar));
	vadd(&argv, bprintf(&b, "-DGOOS_%s", goos));
	vadd(&argv, bprintf(&b, "-DGOARCH_%s", goarch));
	vadd(&argv, bprintf(&b, "-I%s", workdir));
	vadd(&argv, "-q");
	vadd(&argv, "");
	p = argv.p[argv.len-1];
	for(i=0; i<nelem(runtimedefs); i++) {
		argv.p[argv.len-1] = runtimedefs[i];
		runv(&b, dir, CheckExit, &argv);
		bwriteb(&in, &b);
	}
	argv.p[argv.len-1] = p;
		
	// Process the aggregate output.
	skip = 0;
	splitlines(&lines, bstr(&in));
	for(i=0; i<lines.len; i++) {
		p = lines.p[i];
		// Drop comment, func, and const lines.
		if(hasprefix(p, "//") || hasprefix(p, "const") || hasprefix(p, "func"))
			continue;
		
		// Note beginning of type or var decl, which can be multiline.
		// Remove duplicates.  The linear check of seen here makes the
		// whole processing quadratic in aggregate, but there are only
		// about 100 declarations, so this is okay (and simple).
		if(hasprefix(p, "type ") || hasprefix(p, "var ")) {
			splitfields(&fields, p);
			if(fields.len < 2)
				continue;
			if(find(fields.p[1], seen.p, seen.len) >= 0) {
				if(streq(fields.p[fields.len-1], "{"))
					skip = 1;  // skip until }
				continue;
			}
			vadd(&seen, fields.p[1]);
		}
		if(skip) {
			if(hasprefix(p, "}"))
				skip = 0;
			continue;
		}
		
		bwritestr(&out, p);
	}
	
	writefile(&out, file, 0);

	bfree(&in);
	bfree(&b);
	bfree(&out);
	vfree(&argv);
	vfree(&lines);
	vfree(&fields);
	vfree(&seen);
}
Ejemplo n.º 24
0
// genrun is the generic run implementation.
static void
genrun(Buf *b, char *dir, int mode, Vec *argv, int wait)
{
	int i, p[2], pid;
	Buf cmd;
	char *q;

	while(nbg >= maxnbg)
		bgwait1();

	// Generate a copy of the command to show in a log.
	// Substitute $WORK for the work directory.
	binit(&cmd);
	for(i=0; i<argv->len; i++) {
		if(i > 0)
			bwritestr(&cmd, " ");
		q = argv->p[i];
		if(workdir != nil && hasprefix(q, workdir)) {
			bwritestr(&cmd, "$WORK");
			q += strlen(workdir);
		}
		bwritestr(&cmd, q);
	}
	//if(vflag > 1)
		xprintf("%s\n", bstr(&cmd));

	if(b != nil) {
		breset(b);
		if(pipe(p) < 0)
			fatal("pipe: %s", strerror(errno));
	}

	switch(pid = fork()) {
	case -1:
		fatal("fork: %s", strerror(errno));
	case 0:
		if(b != nil) {
			close(0);
			close(p[0]);
			dup2(p[1], 1);
			dup2(p[1], 2);
			if(p[1] > 2)
				close(p[1]);
		}
		if(dir != nil) {
			if(chdir(dir) < 0) {
				fprintf(stderr, "chdir %s: %s\n", dir, strerror(errno));
				_exit(1);
			}
		}
		vadd(argv, nil);
		execvp(argv->p[0], argv->p);
		fprintf(stderr, "%s\n", bstr(&cmd));
		fprintf(stderr, "exec %s: %s\n", argv->p[0], strerror(errno));
		_exit(1);
	}
	if(b != nil) {
		close(p[1]);
		breadfrom(b, p[0]);
		close(p[0]);
	}

	if(nbg < 0)
		fatal("bad bookkeeping");
	bg[nbg].pid = pid;
	bg[nbg].mode = mode;
	bg[nbg].cmd = btake(&cmd);
	bg[nbg].b = b;
	nbg++;
	
	if(wait)
		bgwait();

	bfree(&cmd);
}
Ejemplo n.º 25
0
int demux_info_add(demuxer_t *demuxer, const char *opt, const char *param)
{
    return demux_info_add_bstr(demuxer, bstr(opt), bstr(param));
}
Ejemplo n.º 26
0
Archivo: build.c Proyecto: hfeeki/go
// shouldbuild reports whether we should build this file.
// It applies the same rules that are used with context tags
// in package go/build, except that the GOOS and GOARCH
// can appear anywhere in the file name, not just after _.
// In particular, they can be the entire file name (like windows.c).
// We also allow the special tag cmd_go_bootstrap.
// See ../go/bootstrap.go and package go/build.
static bool
shouldbuild(char *file, char *dir)
{
	char *name, *p;
	int i, j, ret;
	Buf b;
	Vec lines, fields;

	// On Plan 9, most of the libraries are already present.
	// The main exception is libmach which has been modified
	// in various places to support Go object files.
	if(streq(gohostos, "plan9")) {
		if(streq(dir, "lib9") && !hassuffix(file, "lib9/goos.c"))
			return 0;
		if(streq(dir, "libbio"))
			return 0;
	}
	
	// Check file name for GOOS or GOARCH.
	name = lastelem(file);
	for(i=0; i<nelem(okgoos); i++)
		if(contains(name, okgoos[i]) && !streq(okgoos[i], goos))
			return 0;
	for(i=0; i<nelem(okgoarch); i++)
		if(contains(name, okgoarch[i]) && !streq(okgoarch[i], goarch))
			return 0;

	// Omit test files.
	if(contains(name, "_test"))
		return 0;

	// cmd/go/doc.go has a giant /* */ comment before
	// it gets to the important detail that it is not part of
	// package main.  We don't parse those comments,
	// so special case that file.
	if(hassuffix(file, "cmd/go/doc.go") || hassuffix(file, "cmd\\go\\doc.go"))
		return 0;
	if(hassuffix(file, "cmd/cgo/doc.go") || hassuffix(file, "cmd\\cgo\\doc.go"))
		return 0;

	// Check file contents for // +build lines.
	binit(&b);
	vinit(&lines);
	vinit(&fields);

	ret = 1;
	readfile(&b, file);
	splitlines(&lines, bstr(&b));
	for(i=0; i<lines.len; i++) {
		p = lines.p[i];
		while(*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')
			p++;
		if(*p == '\0')
			continue;
		if(contains(p, "package documentation")) {
			ret = 0;
			goto out;
		}
		if(contains(p, "package main") && !streq(dir, "cmd/go") && !streq(dir, "cmd/cgo")) {
			ret = 0;
			goto out;
		}
		if(!hasprefix(p, "//"))
			break;
		if(!contains(p, "+build"))
			continue;
		splitfields(&fields, lines.p[i]);
		if(fields.len < 2 || !streq(fields.p[1], "+build"))
			continue;
		for(j=2; j<fields.len; j++) {
			p = fields.p[j];
			if((*p == '!' && !matchfield(p+1)) || matchfield(p))
				goto fieldmatch;
		}
		ret = 0;
		goto out;
	fieldmatch:;
	}

out:
	bfree(&b);
	vfree(&lines);
	vfree(&fields);

	return ret;
}
Ejemplo n.º 27
0
int  FileEncoding::getEncoding(const std::string& c, const std::string& h )
{
	enc_ = "UNKNOWN";

	// first look for supported ByteOrder4marks
	if ( hasUTF8_BOM(c) == true )
	{
		hasBOM_ = true;
		enc_ = "UTF-8";
		codePage_ = CP_UTF8;
		return CP_UTF8;
	}

	if ( hasUTF16_BOM(c) == true )
	{
		hasBOM_ = true;
		enc_ = "UTF-16";
		codePage_ = CP_WINUNICODE;
        return CP_WINUNICODE;
	}

	// second check headers for charset specs in content-type
	if ( !h.empty() )
	{
//		mol::RegExp rgxp(PCRE_CASELESS,"content-type.*:(.*);.*charset.*=(.*)");

		std::smatch m;
		std::regex e("content-type.*:(.*);.*charset.*=(.*)");

		if (std::regex_search(h, m, e))
		{
			std::wstring s = mol::towstring(m[2]);
			s = mol::trim(s);

			mol::bstr bstr(s);
			MIMECSETINFO minfo;

			HRESULT hr = multiLang_->GetCharsetInfo(bstr,&minfo);
			if ( hr == S_OK )
			{
				enc_ = mol::tostring(minfo.wszCharset);
				codePage_ = minfo.uiInternetEncoding;
				return minfo.uiInternetEncoding;
			}
		}
	}

	// third, try to find xml decl
	//	<?xml version="1.0" encoding="ISO-8859-1" ?>
	//mol::RegExp reg_xml(PCRE_CASELESS,"<?xml +version *= *('|\")[^'\"]*('|\") +encoding *= *('|\")([^'\"]*)('|\")");
	//if ( reg_xml.match(c) )
	std::smatch m_xml;
	std::regex e_xml("<\\?xml +version *= *('|\")[^'\"]*('|\") +encoding *= *('|\")([^'\"]*)('|\")");

	if (std::regex_search(c, m_xml, e_xml))
	{
		//std::string s = reg_xml(c,4);

		std::wstring s = mol::towstring(m_xml[4]);
		s = mol::trim(s);

		mol::bstr b(s);
		MIMECSETINFO minfo;

		HRESULT hr = multiLang_->GetCharsetInfo(b,&minfo);
		if ( hr == S_OK )
		{
			enc_ = mol::tostring(minfo.wszCharset);
			codePage_ = minfo.uiInternetEncoding;
			return minfo.uiInternetEncoding;
		}
	}

	// forth, search body for meta-tag
	// caseless match <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
	//mol::RegExp reg_con(PCRE_CASELESS,"<meta[^>'\"]*http-equiv *= *('|\")content-type('|\") *content *= *('|\")[^'\"]*charset[^'\"=]*=([^'\"]*)('|\") */? *>");
	//if ( reg_con.match(c) )

	std::smatch m_meta;
	std::regex e_meta("<meta[^>'\"]*http-equiv *= *('|\")content-type('|\") *content *= *('|\")[^'\"]*charset[^'\"=]*=([^'\"]*)('|\") */? *>");

	if (std::regex_search(c, m_meta, e_meta))
	{
		std::string s = mol::tostring(m_meta[4]);
		s = mol::trim(s);

		// can't be UTF-16 - if we matched the *ASCII* string "UTF-16", then encoding is broken!
		if ( s != "UTF-16" ) 
		{
			mol::bstr b(s);
			MIMECSETINFO minfo;

			HRESULT hr = multiLang_->GetCharsetInfo(b,&minfo);
			if ( hr == S_OK )
			{
				enc_ = mol::tostring(minfo.wszCharset);
				codePage_ = minfo.uiInternetEncoding;
				return minfo.uiInternetEncoding;
			}
		}
	}

	// no result yet? start start guessing with IMultiLang
    const int dEncInfoSize = 10;
    int s = dEncInfoSize;
    int l = (int)c.size();
    DetectEncodingInfo dEncInf[dEncInfoSize];
    HRESULT hr = multiLang_->DetectInputCodepage(  MLDETECTCP_HTML, 0,(char*) c.c_str(),&l, dEncInf, &s );

	if ( s )
	{
		DetectEncodingInfo dei = dEncInf[s-1];
		while ( s )
		{
			if ( dEncInf[s-1].nConfidence > 100 )
				if ( dEncInf[s-1].nConfidence >= dei.nConfidence )
					dei = dEncInf[s-1];
			s--;
		}
		MIMECPINFO minfo;
		hr = multiLang_->GetCodePageInfo(dei.nCodePage,dei.nLangID,&minfo);
		if ( hr == S_OK )
		{
			enc_ = mol::tostring(minfo.wszWebCharset);
		}
		codePage_ = dei.nCodePage;
		return dei.nCodePage;
	}	
    return 0;
}