Exemplo n.º 1
0
// puts file from client into memory and directory
int store(rio_t *rio, int connfd)
{
	size_t num; 
	char nameBuf[NAME_SIZE]; 
	char FileName[NAME_SIZE]; 
	char FileSize[4];
	unsigned int filesize, netOrder, stat, replySize; 
	char data_in_file[FILE_SIZE];
	char  *data, *reply; 
	FILE *file; 
	unsigned int maxBytes = 4; 

	if((num = Rio_readnb(rio, nameBuf, NAME_SIZE)) == NAME_SIZE) 
	{
        memcpy(&FileName, &nameBuf, NAME_SIZE);
        printf("Filename  = %s\n", FileName);
    } 
    else 
    {
        printf("Filename  = NONE\n");
        stat = -1;
    }

    if((num = Rio_readnb(rio,FileSize,maxBytes)) == maxBytes)
    {
    	memcpy(&netOrder,&FileSize,maxBytes);
    	filesize = ntohl(netOrder); 
    }
    else
    {
    	stat = -1; 
    }

    if((num = Rio_readnb(rio,data_in_file,filesize)) == filesize)
    {
    	data = (char*) malloc(sizeof(char)*filesize); 

    	if(data == NULL)
    	{
    		fprintf(stderr, "Memory Error\n"); 
    		return -1; 
    	}

    	memcpy(data,&data_in_file,filesize);
    }
    else
    {
    	stat = -1; 
    }

    if((file = Fopen(nameBuf,"w")) != NULL)
    {
    	Fwrite(data, sizeof(char), filesize, file);
    	Fclose(file); 

    	if(addFileList(FileName) == 0)
    	{
    		stat = 0; 
    	} 
    	else
    	{
    		stat = -1; 
    	}
    }
    else
    {
    	stat = -1; 
    }

    free(data); 
    unsigned int currStat = 4; 
    replySize = currStat;

    reply = (char*) malloc (sizeof(char*)*replySize);
    if(reply == NULL) { fprintf(stderr, "Memory Error\n"); return -1; }
    char *replyBuf = reply;

    
    netOrder = htonl(stat);
    memcpy(replyBuf, &netOrder, currStat);
    replyBuf += currStat;

    Rio_writen(connfd, reply, replySize);
    free(reply);

    return stat;

}
Exemplo n.º 2
0
/*
 * Terminate an editing session by attempting to write out the user's
 * file from the temporary.  Save any new stuff appended to the file.
 */
void
edstop(void)
{
	int gotcha, c;
	struct message *mp;
	FILE *obuf, *ibuf, *readstat;
	struct stat statb;
	char tempname[PATHSIZE];

	if (readonly)
		return;
	holdsigs();
	if (Tflag != NULL) {
		if ((readstat = Fopen(Tflag, "w")) == NULL)
			Tflag = NULL;
	}
	for (mp = &message[0], gotcha = 0; mp < &message[msgCount]; mp++) {
		if (mp->m_flag & MNEW) {
			mp->m_flag &= ~MNEW;
			mp->m_flag |= MSTATUS;
		}
		if (mp->m_flag & (MODIFY|MDELETED|MSTATUS))
			gotcha++;
		if (Tflag != NULL && (mp->m_flag & (MREAD|MDELETED)) != 0) {
			char *id;

			if ((id = hfield("article-id", mp)) != NULL)
				fprintf(readstat, "%s\n", id);
		}
	}
	if (Tflag != NULL)
		(void)Fclose(readstat);
	if (!gotcha || Tflag != NULL)
		goto done;
	ibuf = NULL;
	if (stat(mailname, &statb) >= 0 && statb.st_size > mailsize) {
		int fd;

		(void)snprintf(tempname, sizeof(tempname),
		    "%s/mbox.XXXXXXXXXX", tmpdir);
		if ((fd = mkstemp(tempname)) == -1 ||
		    (obuf = Fdopen(fd, "w")) == NULL) {
			warn("%s", tempname);
			relsesigs();
			reset(0);
		}
		if ((ibuf = Fopen(mailname, "r")) == NULL) {
			warn("%s", mailname);
			(void)Fclose(obuf);
			(void)rm(tempname);
			relsesigs();
			reset(0);
		}
		(void)fseeko(ibuf, mailsize, SEEK_SET);
		while ((c = getc(ibuf)) != EOF)
			(void)putc(c, obuf);
		(void)Fclose(ibuf);
		(void)Fclose(obuf);
		if ((ibuf = Fopen(tempname, "r")) == NULL) {
			warn("%s", tempname);
			(void)rm(tempname);
			relsesigs();
			reset(0);
		}
		(void)rm(tempname);
	}
	printf("\"%s\" ", mailname);
	(void)fflush(stdout);
	if ((obuf = Fopen(mailname, "r+")) == NULL) {
		warn("%s", mailname);
		relsesigs();
		reset(0);
	}
	trunc(obuf);
	c = 0;
	for (mp = &message[0]; mp < &message[msgCount]; mp++) {
		if ((mp->m_flag & MDELETED) != 0)
			continue;
		c++;
		if (sendmessage(mp, obuf, NULL, NULL) < 0) {
			warnx("%s", mailname);
			relsesigs();
			reset(0);
		}
	}
	gotcha = (c == 0 && ibuf == NULL);
	if (ibuf != NULL) {
		while ((c = getc(ibuf)) != EOF)
			(void)putc(c, obuf);
		(void)Fclose(ibuf);
	}
	(void)fflush(obuf);
	if (ferror(obuf)) {
		warn("%s", mailname);
		relsesigs();
		reset(0);
	}
	(void)Fclose(obuf);
	if (gotcha) {
		(void)rm(mailname);
		printf("removed\n");
	} else
		printf("complete\n");
	(void)fflush(stdout);

done:
	relsesigs();
}
Exemplo n.º 3
0
int GModel::readSTL(const std::string &name, double tolerance)
{
  FILE *fp = Fopen(name.c_str(), "rb");
  if(!fp){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  // store triplets of points for each solid found in the file
  std::vector<std::vector<SPoint3> > points;
  SBoundingBox3d bbox;

  // "solid", or binary data header
  char buffer[256];
  if(!fgets(buffer, sizeof(buffer), fp)){ fclose(fp); return 0; }

  bool binary = strncmp(buffer, "solid", 5) && strncmp(buffer, "SOLID", 5);

  // ASCII STL
  if(!binary){
    points.resize(1);
    while(!feof(fp)) {
      // "facet normal x y z" or "endsolid"
      if(!fgets(buffer, sizeof(buffer), fp)) break;
      if(!strncmp(buffer, "endsolid", 8) ||
         !strncmp(buffer, "ENDSOLID", 8)){
        // "solid"
        if(!fgets(buffer, sizeof(buffer), fp)) break;
        if(!strncmp(buffer, "solid", 5) ||
           !strncmp(buffer, "SOLID", 5)){
          points.resize(points.size() + 1);
          // "facet normal x y z"
          if(!fgets(buffer, sizeof(buffer), fp)) break;
        }
      }
      // "outer loop"
      if(!fgets(buffer, sizeof(buffer), fp)) break;
      // "vertex x y z"
      for(int i = 0; i < 3; i++){
        if(!fgets(buffer, sizeof(buffer), fp)) break;
        char s1[256];
        double x, y, z;
        if(sscanf(buffer, "%s %lf %lf %lf", s1, &x, &y, &z) != 4) break;
        SPoint3 p(x, y, z);
        points.back().push_back(p);
        bbox += p;
      }
      // "endloop"
      if(!fgets(buffer, sizeof(buffer), fp)) break;
      // "endfacet"
      if(!fgets(buffer, sizeof(buffer), fp)) break;
    }
   }

  // check if we could parse something
  bool empty = true;
  for(unsigned int i = 0; i < points.size(); i++){
    if(points[i].size()){
      empty = false;
      break;
    }
  }
  if(empty) points.clear();

  // binary STL (we also try to read in binary mode if the header told
  // us the format was ASCII but we could not read any vertices)
  if(binary || empty){
    if(binary)
      Msg::Info("Mesh is in binary format");
    else
      Msg::Info("Wrong ASCII header or empty file: trying binary read");
    rewind(fp);
    while(!feof(fp)) {
      char header[80];
      if(!fread(header, sizeof(char), 80, fp)) break;
      unsigned int nfacets = 0;
      size_t ret = fread(&nfacets, sizeof(unsigned int), 1, fp);
      bool swap = false;
      if(nfacets > 100000000){
        Msg::Info("Swapping bytes from binary file");
        swap = true;
        SwapBytes((char*)&nfacets, sizeof(unsigned int), 1);
      }
      if(ret && nfacets){
        points.resize(points.size() + 1);
        char *data = new char[nfacets * 50 * sizeof(char)];
        ret = fread(data, sizeof(char), nfacets * 50, fp);
        if(ret == nfacets * 50){
          for(unsigned int i = 0; i < nfacets; i++) {
            float *xyz = (float *)&data[i * 50 * sizeof(char)];
            if(swap) SwapBytes((char*)xyz, sizeof(float), 12);
            for(int j = 0; j < 3; j++){
              SPoint3 p(xyz[3 + 3 * j], xyz[3 + 3 * j + 1], xyz[3 + 3 * j + 2]);
              points.back().push_back(p);
              bbox += p;
            }
          }
        }
        delete [] data;
      }
    }
  }

  std::vector<GFace*> faces;
  for(unsigned int i = 0; i < points.size(); i++){
    if(points[i].empty()){
      Msg::Error("No facets found in STL file for solid %d", i);
      fclose(fp);
      return 0;
    }
    if(points[i].size() % 3){
      Msg::Error("Wrong number of points (%d) in STL file for solid %d",
                 points[i].size(), i);
      fclose(fp);
      return 0;
    }
    Msg::Info("%d facets in solid %d", points[i].size() / 3, i);
    // create face
    GFace *face = new discreteFace(this, getMaxElementaryNumber(2) + 1);
    faces.push_back(face);
    add(face);
  }

  // create triangles using unique vertices
  double eps = norm(SVector3(bbox.max(), bbox.min())) * tolerance;
  std::vector<MVertex*> vertices;
  for(unsigned int i = 0; i < points.size(); i++)
    for(unsigned int j = 0; j < points[i].size(); j++)
      vertices.push_back(new MVertex(points[i][j].x(), points[i][j].y(),
                                     points[i][j].z()));
  MVertexPositionSet pos(vertices);

  std::set<MFace,Less_Face> unique;
  int nbDuplic = 0;
  for(unsigned int i = 0; i < points.size(); i ++){
    for(unsigned int j = 0; j < points[i].size(); j += 3){
      MVertex *v[3];
      for(int k = 0; k < 3; k++){
        double x = points[i][j + k].x();
        double y = points[i][j + k].y();
        double z = points[i][j + k].z();
        v[k] = pos.find(x, y, z, eps);
      }
      MFace mf (v[0], v[1], v[2]);
      if (unique.find(mf) == unique.end()){
	faces[i]->triangles.push_back(new MTriangle(v[0], v[1], v[2]));
	unique.insert(mf);
      }
      else{
	nbDuplic++;
      }
    }
  }
  if (nbDuplic)
    Msg::Warning("%d duplicate triangles in STL file", nbDuplic);

  _associateEntityWithMeshVertices();
  _storeVerticesInEntities(vertices); // will delete unused vertices

  fclose(fp);
  return 1;
}
Exemplo n.º 4
0
void elasticitySolver::readInputFile(const std::string &fn)
{
  FILE *f = Fopen(fn.c_str(), "r");
  if(!f) {
    Msg::Error("Could not open file '%s'", fn.c_str());
    return;
  }
  char what[256];
  while(!feof(f)) {
    if(fscanf(f, "%s", what) != 1) {
      fclose(f);
      return;
    }
    if(what[0] == '#') {
      char buffer[1024];
      if(fgets(buffer, sizeof(buffer), f) == NULL)
        Msg::Error("Cannot read line.");
    }
    else if(!strcmp(what, "ElasticDomain")) {
      elasticField field;
      int physical;
      if(fscanf(f, "%d %lf %lf", &physical, &field._e, &field._nu) != 3) {
        fclose(f);
        return;
      }
      field._tag = _tag;
      field.g = new groupOfElements(_dim, physical);
      elasticFields.push_back(field);
    }
    else if(!strcmp(what, "LagrangeMultipliers")) {
      LagrangeMultiplierField field;
      int physical;
      double d1, d2, d3, val;
      if(fscanf(f, "%d %lf %lf %lf %lf %lf %d", &physical, &field._tau, &d1,
                &d2, &d3, &val, &field._tag) != 7) {
        fclose(f);
        return;
      }
      SVector3 sv(d1, d2, d3);
      field._d = sv.unit();
      field._f = new simpleFunction<double>(val);
      field.g = new groupOfElements(_dim - 1, physical);
      LagrangeMultiplierFields.push_back(field);
      LagrangeMultiplierSpaces.push_back(
        new ScalarLagrangeFunctionSpaceOfElement(field._tag));
    }
    else if(!strcmp(what, "Void")) {
      elasticField field;
      int physical;
      if(fscanf(f, "%d", &physical) != 1) {
        fclose(f);
        return;
      }
      field._e = field._nu = 0;
      field.g = new groupOfElements(_dim, physical);
      field._tag = 0;
      elasticFields.push_back(field);
    }
    else if(!strcmp(what, "NodeDisplacement")) {
      double val;
      int node, comp;
      if(fscanf(f, "%d %d %lf", &node, &comp, &val) != 3) {
        fclose(f);
        return;
      }
      dirichletBC diri;
      diri.g = new groupOfElements(0, node);
      diri._f = new simpleFunction<double>(val);
      diri._comp = comp;
      diri._tag = node;
      diri.onWhat = BoundaryCondition::ON_VERTEX;
      allDirichlet.push_back(diri);
    }
    else if(!strcmp(what, "EdgeDisplacement")) {
      double val;
      int edge, comp;
      if(fscanf(f, "%d %d %lf", &edge, &comp, &val) != 3) {
        fclose(f);
        return;
      }
      dirichletBC diri;
      diri.g = new groupOfElements(1, edge);
      diri._f = new simpleFunction<double>(val);
      diri._comp = comp;
      diri._tag = edge;
      diri.onWhat = BoundaryCondition::ON_EDGE;
      allDirichlet.push_back(diri);
    }
    else if(!strcmp(what, "FaceDisplacement")) {
      double val;
      int face, comp;
      if(fscanf(f, "%d %d %lf", &face, &comp, &val) != 3) {
        fclose(f);
        return;
      }
      dirichletBC diri;
      diri.g = new groupOfElements(2, face);
      diri._f = new simpleFunction<double>(val);
      diri._comp = comp;
      diri._tag = face;
      diri.onWhat = BoundaryCondition::ON_FACE;
      allDirichlet.push_back(diri);
    }
    else if(!strcmp(what, "NodeForce")) {
      double val1, val2, val3;
      int node;
      if(fscanf(f, "%d %lf %lf %lf", &node, &val1, &val2, &val3) != 4) {
        fclose(f);
        return;
      }
      neumannBC neu;
      neu.g = new groupOfElements(0, node);
      neu._f = new simpleFunction<SVector3>(SVector3(val1, val2, val3));
      neu._tag = node;
      neu.onWhat = BoundaryCondition::ON_VERTEX;
      allNeumann.push_back(neu);
    }
    else if(!strcmp(what, "EdgeForce")) {
      double val1, val2, val3;
      int edge;
      if(fscanf(f, "%d %lf %lf %lf", &edge, &val1, &val2, &val3) != 4) {
        fclose(f);
        return;
      }
      neumannBC neu;
      neu.g = new groupOfElements(1, edge);
      neu._f = new simpleFunction<SVector3>(SVector3(val1, val2, val3));
      neu._tag = edge;
      neu.onWhat = BoundaryCondition::ON_EDGE;
      allNeumann.push_back(neu);
    }
    else if(!strcmp(what, "FaceForce")) {
      double val1, val2, val3;
      int face;
      if(fscanf(f, "%d %lf %lf %lf", &face, &val1, &val2, &val3) != 4) {
        fclose(f);
        return;
      }
      neumannBC neu;
      neu.g = new groupOfElements(2, face);
      neu._f = new simpleFunction<SVector3>(SVector3(val1, val2, val3));
      neu._tag = face;
      neu.onWhat = BoundaryCondition::ON_FACE;
      allNeumann.push_back(neu);
    }
    else if(!strcmp(what, "VolumeForce")) {
      double val1, val2, val3;
      int volume;
      if(fscanf(f, "%d %lf %lf %lf", &volume, &val1, &val2, &val3) != 4) {
        fclose(f);
        return;
      }
      neumannBC neu;
      neu.g = new groupOfElements(3, volume);
      neu._f = new simpleFunction<SVector3>(SVector3(val1, val2, val3));
      neu._tag = volume;
      neu.onWhat = BoundaryCondition::ON_VOLUME;
      allNeumann.push_back(neu);
    }
    else if(!strcmp(what, "MeshFile")) {
      char name[245];
      if(fscanf(f, "%s", name) != 1) {
        fclose(f);
        return;
      }
      setMesh(name);
    }
    else if(!strcmp(what, "CutMeshPlane")) {
      double a, b, c, d;
      if(fscanf(f, "%lf %lf %lf %lf", &a, &b, &c, &d) != 4) {
        fclose(f);
        return;
      }
      int tag = 1;
      gLevelsetPlane ls(a, b, c, d, tag);
      pModel = pModel->buildCutGModel(&ls);
      pModel->writeMSH("cutMesh.msh");
    }
    else if(!strcmp(what, "CutMeshSphere")) {
      double x, y, z, r;
      if(fscanf(f, "%lf %lf %lf %lf", &x, &y, &z, &r) != 4) {
        fclose(f);
        return;
      }
      int tag = 1;
      gLevelsetSphere ls(x, y, z, r, tag);
      pModel = pModel->buildCutGModel(&ls);
      pModel->writeMSH("cutMesh.msh");
    }
    else if(!strcmp(what, "CutMeshMathExpr")) {
      char expr[256];
      if(fscanf(f, "%s", expr) != 1) {
        fclose(f);
        return;
      }
      std::string exprS(expr);
      int tag = 1;
      gLevelsetMathEval ls(exprS, tag);
      pModel = pModel->buildCutGModel(&ls);
      pModel->writeMSH("cutMesh.msh");
    }
    else {
      Msg::Error("Invalid input : '%s'", what);
    }
  }
  fclose(f);
}
Exemplo n.º 5
0
int GModel::readPLY(const std::string &name)
{
  // this is crazy!?
  replaceCommaByDot(name);

  FILE *fp = Fopen(name.c_str(), "r");
  if(!fp){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  std::vector<MVertex*> vertexVector;
  std::map<int, std::vector<MElement*> > elements[5];
  std::map<int, std::vector<double> > properties;

  char buffer[256], str[256], str2[256], str3[256];
  std::string s1;
  int elementary = getMaxElementaryNumber(-1) + 1;
  int nbv, nbf;
  int nbprop = 0;
  int nbView = 0;
  std::vector<std::string> propName;
  while(!feof(fp)) {
    if(!fgets(buffer, sizeof(buffer), fp)) break;
    if(buffer[0] != '#'){ // skip comments
      sscanf(buffer, "%s %s", str, str2);
      if(!strcmp(str, "element") && !strcmp(str2, "vertex")){
	sscanf(buffer, "%s %s %d", str, str2, &nbv);
      }
      if(!strcmp(str, "format") && strcmp(str2, "ascii")){
	Msg::Error("Only reading of ascii PLY files implemented");
        fclose(fp);
	return 0;
      }
      if(!strcmp(str, "property") && strcmp(str2, "list")){
	nbprop++;
	sscanf(buffer, "%s %s %s", str, str2, str3);
	if (nbprop > 3) propName.push_back(s1+str3);
      }
      if(!strcmp(str, "element") && !strcmp(str2, "face")){
	sscanf(buffer, "%s %s %d", str, str2, &nbf);
      }
      if(!strcmp(str, "end_header")){
	nbView = nbprop -3;
	Msg::Info("%d elements", nbv);
	Msg::Info("%d triangles", nbf);
	Msg::Info("%d properties", nbView);

	vertexVector.resize(nbv);
	for(int i = 0; i < nbv; i++) {
	  double x,y,z;
	  char line[10000], *pEnd, *pEnd2, *pEnd3;
	  if(!fgets(line, sizeof(line), fp)){ fclose(fp); return 0; }
	  x = strtod(line, &pEnd);
	  y = strtod(pEnd, &pEnd2);
	  z = strtod(pEnd2, &pEnd3);
	  vertexVector[i] = new MVertex(x, y, z);

	  pEnd = pEnd3;
          std::vector<double> prop(nbView);
	  for (int k = 0; k < nbView; k++){
	    prop[k]=strtod(pEnd, &pEnd2);
	    pEnd = pEnd2;
	    properties[k].push_back(prop[k]);
	  }
	}

	for(int i = 0; i < nbf; i++) {
	  if(!fgets(buffer, sizeof(buffer), fp)) break;
	  int n[3], nbe;
	  sscanf(buffer, "%d %d %d %d", &nbe, &n[0], &n[1], &n[2]);
	  std::vector<MVertex*> vertices;
	  if(!getVertices(3, n, vertexVector, vertices)){ fclose(fp); return 0; }
	  elements[0][elementary].push_back(new MTriangle(vertices));
	}

      }

    }
  }

  for(int i = 0; i < (int)(sizeof(elements) / sizeof(elements[0])); i++)
    _storeElementsInEntities(elements[i]);
  _associateEntityWithMeshVertices();
  _storeVerticesInEntities(vertexVector);

#if defined(HAVE_POST)
  // create PViews here
  std::vector<GEntity*> _entities;
  getEntities(_entities);
  for (int iV=0; iV< nbView; iV++){
    PView *view = new PView();
    PViewDataList *data = dynamic_cast<PViewDataList*>(view->getData());
    for(unsigned int ii = 0; ii < _entities.size(); ii++){
	for(unsigned int i = 0; i < _entities[ii]->getNumMeshElements(); i++){
	  MElement *e = _entities[ii]->getMeshElement(i);
	  int numNodes = e->getNumVertices();
	  std::vector<double> x(numNodes), y(numNodes), z(numNodes);
	  std::vector<double> *out = data->incrementList(1, e->getType());
	  for(int nod = 0; nod < numNodes; nod++) out->push_back((e->getVertex(nod))->x());
	  for(int nod = 0; nod < numNodes; nod++) out->push_back((e->getVertex(nod))->y());
	  for(int nod = 0; nod < numNodes; nod++) out->push_back((e->getVertex(nod))->z());
	  std::vector<double> props;
	  int n[3];
	  n[0] = e->getVertex(0)->getNum()-1;
	  n[1] = e->getVertex(1)->getNum()-1;
	  n[2] = e->getVertex(2)->getNum()-1;
	  if(!getProperties(3, n, properties[iV], props)){ fclose(fp); return 0; }
	  for(int nod = 0; nod < numNodes; nod++) out->push_back(props[nod]);
	}
    }
    data->setName(propName[iV]);
    data->Time.push_back(0);
    data->setFileName("property.pos");
    data->finalize();
  }
#endif

  fclose(fp);

  return 1;
}
Exemplo n.º 6
0
/*
	Load a source module
*/
short LoadSrcModule(short module)
{
	FILE *f;
	char *lp;
	int l,n,lc=0;
	short handle;

	if (cur_module==module)
		return TRUE;
		
	if (src_buf)
	{
		free(src_buf);
		src_buf=NULL;
	}

	if (src)
	{
		free(src);
		src=NULL;
	}
	
	f=fopen(dtab[module].full_path,"r");
	if (!f)
	{
		printf("**source file not found %s\n",dtab[module].full_path);
		return FALSE;
	}
	fseek(f,0L,2);		/* get file size */
	l=ftell(f);
	fseek(f,0L,0);
	fclose(f);
	
	src_buf=(char*)malloc(l*2);
	if (!src_buf)
	{
		printf("**error, out of memory\n");
		return NULL;
	}
	
	handle=(short)Fopen(dtab[module].full_path,O_RDONLY);
	Fread(handle,l,src_buf);
	Fclose(handle);
	
	for(n=0; n<l+1; n++)	
	{
		if(src_buf[n]=='\n')
			lc++;
	}
	
	src_lc=lc;
	src=(char**)malloc(sizeof(char**)*lc);

	n=0; lc=0;
	for(lp=src_buf; n<l+1; n++)
	{
		if(src_buf[n]=='\n')
		{
			src[lc]=lp;
			src_buf[n]='\0';
			lp=src_buf+n+1;			
			lc++;
			if (*lp=='\r')
				lp++;
		}
	}
	
	cur_module=module;
	
	fclose(f);
	
	return TRUE;	
}
Exemplo n.º 7
0
int GModel::readMESH(const std::string &name)
{
  FILE *fp = Fopen(name.c_str(), "r");
  if(!fp){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  char buffer[256];
  if(!fgets(buffer, sizeof(buffer), fp)){ fclose(fp); return 0; }

  char str[256];
  int format;
  sscanf(buffer, "%s %d", str, &format);
  if(format == 3){
    Msg::Error("Medit mesh import only available for ASCII files");
    fclose(fp);
    return 0;
  }

  std::vector<MVertex*> vertexVector;
  std::map<int, std::vector<MElement*> > elements[5];

  while(!feof(fp)) {
    if(!fgets(buffer, 256, fp)) break;
    if(buffer[0] != '#'){ // skip comments and empty lines
      str[0]='\0';
      sscanf(buffer, "%s", str);
      if(!strncmp(buffer, "Dimension 3", 11)){
        // alternative single-line 'Dimension' field used by CGAL
      }
      else if(!strcmp(str, "Dimension")){
        if(!fgets(buffer, sizeof(buffer), fp)) break;
      }
      else if(!strcmp(str, "Vertices")){
        if(!fgets(buffer, sizeof(buffer), fp)) break;
        int nbv;
        sscanf(buffer, "%d", &nbv);
        Msg::Info("%d vertices", nbv);
        vertexVector.resize(nbv);
        for(int i = 0; i < nbv; i++) {
          if(!fgets(buffer, sizeof(buffer), fp)) break;
          int dum;
          double x, y, z;
          sscanf(buffer, "%lf %lf %lf %d", &x, &y, &z, &dum);
          vertexVector[i] = new MVertex(x, y, z);
        }
      }
      else if(!strcmp(str, "Edges")){
        if(!fgets(buffer, sizeof(buffer), fp)) break;
        int nbe;
        sscanf(buffer, "%d", &nbe);
        Msg::Info("%d edges", nbe);
        for(int i = 0; i < nbe; i++) {
          if(!fgets(buffer, sizeof(buffer), fp)) break;
          int n[2], cl;
          sscanf(buffer, "%d %d %d", &n[0], &n[1], &cl);
          for(int j = 0; j < 2; j++) n[j]--;
          std::vector<MVertex*> vertices;
          if(!getVertices(2, n, vertexVector, vertices)){ fclose(fp); return 0; }
          elements[0][cl].push_back(new MLine(vertices));
        }
      }
      else if(!strcmp(str, "EdgesP2")){
        if(!fgets(buffer, sizeof(buffer), fp)) break;
        int nbe;
        sscanf(buffer, "%d", &nbe);
        Msg::Info("%d edges", nbe);
        for(int i = 0; i < nbe; i++) {
          if(!fgets(buffer, sizeof(buffer), fp)) break;
          int n[3], cl;
          sscanf(buffer, "%d %d %d %d", &n[0], &n[1], &n[2], &cl);
          for(int j = 0; j < 3; j++) n[j]--;
          std::vector<MVertex*> vertices;
          if(!getVertices(3, n, vertexVector, vertices)){ fclose(fp); return 0; }
          elements[0][cl].push_back(new MLine3(vertices));
        }
      }
      else if(!strcmp(str, "Triangles")){
        if(!fgets(buffer, sizeof(buffer), fp)) break;
        int nbe;
        sscanf(buffer, "%d", &nbe);
        Msg::Info("%d triangles", nbe);
        for(int i = 0; i < nbe; i++) {
          if(!fgets(buffer, sizeof(buffer), fp)) break;
          int n[3], cl;
          sscanf(buffer, "%d %d %d %d", &n[0], &n[1], &n[2], &cl);
          for(int j = 0; j < 3; j++) n[j]--;
          std::vector<MVertex*> vertices;
          if(!getVertices(3, n, vertexVector, vertices)){ fclose(fp); return 0; }
          elements[1][cl].push_back(new MTriangle(vertices));
        }
      }
      else if(!strcmp(str, "TrianglesP2")){
        if(!fgets(buffer, sizeof(buffer), fp)) break;
        int nbe;
        sscanf(buffer, "%d", &nbe);
        Msg::Info("%d triangles", nbe);
        for(int i = 0; i < nbe; i++) {
          if(!fgets(buffer, sizeof(buffer), fp)) break;
          int n[6], cl;
          sscanf(buffer, "%d %d %d %d %d %d %d",
                 &n[0], &n[1], &n[2], &n[3], &n[4], &n[5], &cl);
          for(int j = 0; j < 6; j++) n[j]--;
          std::vector<MVertex*> vertices;
          if(!getVertices(6, n, vertexVector, vertices)){ fclose(fp); return 0; }
          elements[1][cl].push_back(new MTriangle6(vertices));
        }
      }
      else if(!strcmp(str, "Quadrilaterals")) {
        if(!fgets(buffer, sizeof(buffer), fp)) break;
        int nbe;
        sscanf(buffer, "%d", &nbe);
        Msg::Info("%d quadrangles", nbe);
        for(int i = 0; i < nbe; i++) {
          if(!fgets(buffer, sizeof(buffer), fp)) break;
          int n[4], cl;
          sscanf(buffer, "%d %d %d %d %d", &n[0], &n[1], &n[2], &n[3], &cl);
          for(int j = 0; j < 4; j++) n[j]--;
          std::vector<MVertex*> vertices;
          if(!getVertices(4, n, vertexVector, vertices)){ fclose(fp); return 0; }
          elements[2][cl].push_back(new MQuadrangle(vertices));
        }
      }
      else if(!strcmp(str, "Tetrahedra")) {
        if(!fgets(buffer, sizeof(buffer), fp)) break;
        int nbe;
        sscanf(buffer, "%d", &nbe);
        Msg::Info("%d tetrahedra", nbe);
        for(int i = 0; i < nbe; i++) {
          if(!fgets(buffer, sizeof(buffer), fp)) break;
          int n[4], cl;
          sscanf(buffer, "%d %d %d %d %d", &n[0], &n[1], &n[2], &n[3], &cl);
          for(int j = 0; j < 4; j++) n[j]--;
          std::vector<MVertex*> vertices;
          if(!getVertices(4, n, vertexVector, vertices)){ fclose(fp); return 0; }
          elements[3][cl].push_back(new MTetrahedron(vertices));
        }
      }
      else if(!strcmp(str, "TetrahedraP2")) {
        if(!fgets(buffer, sizeof(buffer), fp)) break;
        int nbe;
        sscanf(buffer, "%d", &nbe);
        Msg::Info("%d tetrahedra", nbe);
        for(int i = 0; i < nbe; i++) {
          if(!fgets(buffer, sizeof(buffer), fp)) break;
          int n[10], cl;
          sscanf(buffer, "%d %d %d %d %d %d %d %d %d %d %d", &n[0], &n[1], &n[2],
                 &n[3],&n[4], &n[5], &n[6], &n[7], &n[9], &n[8], &cl);
          for(int j = 0; j < 10; j++) n[j]--;
          std::vector<MVertex*> vertices;
          if(!getVertices(10, n, vertexVector, vertices)){ fclose(fp); return 0; }
          elements[3][cl].push_back(new MTetrahedron10(vertices));
        }
      }
      else if(!strcmp(str, "Hexahedra")) {
        if(!fgets(buffer, sizeof(buffer), fp)) break;
        int nbe;
        sscanf(buffer, "%d", &nbe);
        Msg::Info("%d hexahedra", nbe);
        for(int i = 0; i < nbe; i++) {
          if(!fgets(buffer, sizeof(buffer), fp)) break;
          int n[8], cl;
          sscanf(buffer, "%d %d %d %d %d %d %d %d %d", &n[0], &n[1], &n[2], &n[3],
                 &n[4], &n[5], &n[6], &n[7], &cl);
          for(int j = 0; j < 8; j++) n[j]--;
          std::vector<MVertex*> vertices;
          if(!getVertices(8, n, vertexVector, vertices)){ fclose(fp); return 0; }
          elements[4][cl].push_back(new MHexahedron(vertices));
        }
      }
    }
  }

  for(int i = 0; i < (int)(sizeof(elements) / sizeof(elements[0])); i++)
    _storeElementsInEntities(elements[i]);
  _associateEntityWithMeshVertices();
  _storeVerticesInEntities(vertexVector);

  fclose(fp);
  return 1;
}
Exemplo n.º 8
0
bool PView::readPOS(const std::string &fileName, int fileIndex)
{
  FILE *fp = Fopen(fileName.c_str(), "rb");
  if(!fp){
    Msg::Error("Unable to open file '%s'", fileName.c_str());
    return false;
  }

  char str[256] = "XXX";
  double version = -1.;
  int format = -1, size = -1, index = -1;

  while(1) {

    while(str[0] != '$'){
      if(!fgets(str, sizeof(str), fp) || feof(fp))
        break;
    }

    if(feof(fp))
      break;

    if(!strncmp(&str[1], "PostFormat", 10)) {

      if(!fscanf(fp, "%lf %d %d\n", &version, &format, &size)){
        Msg::Error("Read error");
        fclose(fp);
        return false;
      }
      if(version < 1.0) {
        Msg::Error("Post-processing file too old (ver. %g < 1.0)", version);
        fclose(fp);
        return false;
      }
      if(size == sizeof(double))
        Msg::Debug("Data is in double precision format (size==%d)", size);
      else {
        Msg::Error("Unknown data size (%d) in post-processing file", size);
        fclose(fp);
        return false;
      }

    }
    else if(!strncmp(&str[1], "View", 4)){
      index++;
      if(fileIndex < 0 || fileIndex == index){
        PViewDataList *d = new PViewDataList();
        if(!d->readPOS(fp, version, format ? true : false)){
          Msg::Error("Could not read data in list format");
          delete d;
          fclose(fp);
          return false;
        }
        else{
          d->setFileName(fileName);
          d->setFileIndex(index);
          new PView(d);
        }
      }

    }

    do {
      if(!fgets(str, sizeof(str), fp) || feof(fp))
        break;
    } while(str[0] != '$');

  }

  fclose(fp);
  return true;
}
Exemplo n.º 9
0
bool PView::readMSH(const std::string &fileName, int fileIndex)
{
  FILE *fp = Fopen(fileName.c_str(), "rb");
  if(!fp){
    Msg::Error("Unable to open file '%s'", fileName.c_str());
    return false;
  }

  GModel *model = GModel::current();
  if(model->empty()){
    Msg::Error("Model is empty: please load a mesh before loading the dataset");
    fclose(fp);
    return false;
  }

  char str[256] = "XXX";
  int index = -1;
  bool binary = false, swap = false;

  while(1) {

    while(str[0] != '$'){
      if(!fgets(str, sizeof(str), fp) || feof(fp))
        break;
    }

    if(feof(fp))
      break;

    if(!strncmp(&str[1], "MeshFormat", 10)) {
      double version;
      if(!fgets(str, sizeof(str), fp)){ fclose(fp); return false; }
      int format, size;
      if(sscanf(str, "%lf %d %d", &version, &format, &size) != 3){
        fclose(fp);
        return false;
      }
      if(format){
        binary = true;
        Msg::Info("View data is in binary format");
        int one;
        if(fread(&one, sizeof(int), 1, fp) != 1){ fclose(fp); return 0; }
        if(one != 1){
          swap = true;
          Msg::Info("Swapping bytes from binary file");
        }
      }
    }
    else if(!strncmp(&str[1], "InterpolationScheme", 19)){
      std::string name;
      if(!fgets(str, sizeof(str), fp)){ fclose(fp); return false; }
      name = ExtractDoubleQuotedString(str, sizeof(str));
      Msg::Info("Reading interpolation scheme '%s'", name.c_str());
      PViewData::removeInterpolationScheme(name);
      int numTypes;
      if(fscanf(fp, "%d", &numTypes) != 1){ fclose(fp); return false; }
      for(int i = 0; i < numTypes; i++){
        int type, numMatrices;
        if(fscanf(fp, "%d %d", &type, &numMatrices) != 2){ fclose(fp); return false; }
        for(int j = 0; j < numMatrices; j++){
          int m, n;
          if(fscanf(fp, "%d %d", &m, &n) != 2){ fclose(fp); return false; }
          fullMatrix<double> mat(m, n);
          for(int k = 0; k < m; k++){
            for(int l = 0; l < n; l++){
              double d;
              if(fscanf(fp, "%lf", &d) != 1){ fclose(fp); return false; }
              mat.set(k, l, d);
            }
          }
          PViewData::addMatrixToInterpolationScheme(name, type, mat);
        }
      }
    }
    else if(!strncmp(&str[1], "NodeData", 8) ||
            !strncmp(&str[1], "ElementData", 11) ||
            !strncmp(&str[1], "ElementNodeData", 15)) {
      index++;
      if(fileIndex < 0 || fileIndex == index){
        PViewDataGModel::DataType type;
        if(!strncmp(&str[1], "NodeData", 8))
          type = PViewDataGModel::NodeData;
        else if(!strncmp(&str[1], "ElementData", 11))
          type = PViewDataGModel::ElementData;
        else
          type = PViewDataGModel::ElementNodeData;
        int numTags;
        // string tags
        std::string viewName, interpolationScheme;
        if(!fgets(str, sizeof(str), fp)){ fclose(fp); return false; }
        if(sscanf(str, "%d", &numTags) != 1){ fclose(fp); return false; }
        for(int i = 0; i < numTags; i++){
          if(!fgets(str, sizeof(str), fp)){ fclose(fp); return false; }
          if(i == 0)
            viewName = ExtractDoubleQuotedString(str, sizeof(str));
          else if(i == 1)
            interpolationScheme = ExtractDoubleQuotedString(str, sizeof(str));
        }
        // double tags
        double time = 0.;
        if(!fgets(str, sizeof(str), fp)){ fclose(fp); return false; }
        if(sscanf(str, "%d", &numTags) != 1){ fclose(fp); return false; }
        for(int i = 0; i < numTags; i++){
          if(!fgets(str, sizeof(str), fp)){ fclose(fp); return false; }
          if(i == 0){
            if(sscanf(str, "%lf", &time) != 1){ fclose(fp); return false; }
          }
        }
        // integer tags
        int timeStep = 0, numComp = 0, numEnt = 0, partition = 0;
        if(!fgets(str, sizeof(str), fp)){ fclose(fp); return false; }
        if(sscanf(str, "%d", &numTags) != 1){ fclose(fp); return false; }
        for(int i = 0; i < numTags; i++){
          if(!fgets(str, sizeof(str), fp)){ fclose(fp); return false; }
          if(i == 0){
            if(sscanf(str, "%d", &timeStep) != 1){ fclose(fp); return false; }
          }
          else if(i == 1){
            if(sscanf(str, "%d", &numComp) != 1){ fclose(fp); return false; }
          }
          else if(i == 2){
            if(sscanf(str, "%d", &numEnt) != 1){ fclose(fp); return false; }
          }
          else if(i == 3){
            if(sscanf(str, "%d", &partition) != 1){ fclose(fp); return false; }
          }
        }
        // either get existing viewData, or create new one
        PView *p = getViewByName(viewName, timeStep, partition);
        PViewDataGModel *d = 0;
        if(p) d = dynamic_cast<PViewDataGModel*>(p->getData());
        bool create = d ? false : true;
        if(create) d = new PViewDataGModel(type);
        if(!d->readMSH(viewName, fileName, fileIndex, fp, binary, swap, timeStep,
                       time, partition, numComp, numEnt, interpolationScheme)){
          Msg::Error("Could not read data in msh file");
          if(create) delete d;
          fclose(fp);
          return false;
        }
        else{
          d->setName(viewName);
          d->setFileName(fileName);
          d->setFileIndex(index);
          if(create) new PView(d);
        }
      }
    }

    do {
      if(!fgets(str, sizeof(str), fp) || feof(fp))
        break;
    } while(str[0] != '$');
  }

  fclose(fp);
  return true;
}
Exemplo n.º 10
0
/* Save_Data()
 * ======================================================================
 */
BOOLEAN
Save_Data( void )
{
    DTA  thedta, *saved;
    int  fd;
    int  *DataPtr;
    long EndIndex;
    BOOLEAN flag;

    flag = FALSE;
    saved = Fgetdta();
    Fsetdta( &thedta );
    if( Fsfirst( FPath, 0 ) <= -1 ) /* Can't find the file... */
    {
        Objc_draw( tree, ROOT, MAX_DEPTH, NULL );
        form_alert( 1, alert2 );
    }
    else
    {
        DataBuf = calloc( 1, thedta.d_length * 2L );

        if( DataBuf )
        {
            fd = Fopen( FPath, 0 );
            if( fd <= 0 )
            {
                form_alert( 1, alert1 );
            }
            else
            {
                Buffer = ( long )DataBuf;
                Buffer = ( Buffer + 15L ) & 0xFFFFFFF0L;
                DataHdr = ( int *)Buffer;

                Fread( fd, thedta.d_length, DataHdr );
                Fclose( fd );

                EndIndex = thedta.d_length;
                DataPtr  = FindString( DataHdr, DataHdr + EndIndex - 8 );
                if( DataPtr )
                {
                    hdr = ( HEADER *)DataPtr;

                    hdr_buffer.quality    = Menu[ MQUALITY ].curvalue;
                    hdr_buffer.nplanes    = Menu[ MCOLOR ].curvalue + 1;
                    hdr_buffer.PageSize   = Menu[ MPAGESIZE ].curvalue;
                    hdr_buffer.xres       = xres_value;
                    hdr_buffer.yres       = yres_value;
                    hdr_buffer.port       = Menu[ MPORT ].curvalue;
                    hdr_buffer.paper_feed = Menu[ MTRAY ].curvalue;

                    *hdr = hdr_buffer;

                    flag = TRUE;
                    fd = Fcreate( FPath, 0 );
                    Fwrite( fd, thedta.d_length, DataHdr );
                    Fclose( fd );
                }
                else
                {
                    Objc_draw( tree, ROOT, MAX_DEPTH, NULL );
                    form_alert( 1, alert3 );
                }
                free( DataBuf );
            }
        }
        else
            form_alert( 1, alert4 );
    }
    Fsetdta( saved );
    return( flag );
}
Exemplo n.º 11
0
/* GetCDrivers()
 * ====================================================================
 * Go thru the list of .sys files and try to load them.
 * Those that we can load, get the header and see if they are of the
 * new driver type. Get the filenames of those that are printer drivers
 * and store them in cdriver. Store their index into the driver array
 * into our cdriver array position.
 */
void
GetCDrivers( void )
{
    DTA  thedta, *saved;
    int  fd;
    int  *DataPtr;
    long EndIndex;
    int  error;

    saved = Fgetdta();
    Fsetdta( &thedta );

    cdriver_count =  0;

    get_bitpath();
    strcpy( FPath, epath );
    strcat( FPath, "\\*.SYS");

    error = Fsfirst( FPath, 0 );	/* Normal file search for 1st file */
    if( error != E_OK )  	/* No such files! */
    {
        return;
    }

    do
    {
        sprintf( line_buf, "%s\\%s", epath, thedta.d_fname );
        DataBuf = calloc( 1, thedta.d_length * 2L );

        if( DataBuf )
        {
            fd = Fopen( line_buf, 0 );
            if( fd > 0 )
            {
                Buffer = ( long )DataBuf;
                Buffer = ( Buffer + 15L ) & 0xFFFFFFF0L;
                DataHdr = ( int *)Buffer;

                Fread( fd, thedta.d_length, DataHdr );
                Fclose( fd );
                EndIndex = thedta.d_length;
                DataPtr  = FindString( DataHdr, DataHdr + EndIndex - 8 );
                if( DataPtr )	/* Look only for new drivers with headers*/
                {
                    hdr = ( HEADER *)DataPtr;
                    hdr_buffer = ( HEADER )*hdr;
                    hdr = &hdr_buffer;

                    /* want only those drivers with real page sizes */
                    if( hdr->config_map & 0x3E )
                    {
                        /* then get the name...*/
                        strcpy( cdrivers[ cdriver_count ], hdr->fname );
                        strcpy( drivers[ cdriver_count ], thedta.d_fname );
                        cdriver_count++;
                    }
                }
            }
            free( DataBuf );
        }
        else
        {
            /* memory error - break out of loop and exit routine */
            form_alert( 1, alert4 );
            break;
        }
    } while ( ( Fsnext() == E_OK ) && ( cdriver_count < MAX_DRIVERS ) );
    SortCDriverNames();
    Fsetdta( saved );
}
Exemplo n.º 12
0
/* Read_Data()
 * ================================================================
 */
BOOLEAN
Read_Data( void )
{
    DTA  thedta, *saved;
    int  fd;
    int  *DataPtr;
    long EndIndex;
    BOOLEAN flag;

    flag = FALSE;
    saved = Fgetdta();
    Fsetdta( &thedta );
    if( Fsfirst( FPath, 0 ) <= -1 ) /* Can't find the file... */
    {
        Objc_draw( tree, ROOT, MAX_DEPTH, NULL );
        form_alert( 1, alert2 );
    }
    else
    {
        DataBuf = calloc( 1, thedta.d_length * 2L );

        if( DataBuf )
        {
            fd = Fopen( FPath, 0 );
            if( fd <= 0 )
            {
                form_alert( 1, alert1 );
            }
            else
            {
                Buffer = ( long )DataBuf;
                Buffer = ( Buffer + 15L ) & 0xFFFFFFF0L;
                DataHdr = ( int *)Buffer;

                Fread( fd, thedta.d_length, DataHdr );
                Fclose( fd );

                EndIndex = thedta.d_length;
                DataPtr  = FindString( DataHdr, DataHdr + EndIndex - 8 );
                if( DataPtr )
                {
                    hdr = ( HEADER *)DataPtr;
                    hdr_buffer = ( HEADER )*hdr;
                    hdr = &hdr_buffer;
                    strcpy( title, hdr->fname );
                    flag = TRUE;
                }
                else
                {
                    Objc_draw( tree, ROOT, MAX_DEPTH, NULL );
                    form_alert( 1, alert3 );
                }
                free( DataBuf );
            }
        }
        else
            form_alert( 1, alert4 );
    }
    Fsetdta( saved );
    return( flag );
}
Exemplo n.º 13
0
/* get_bitpath()
 * ====================================================================
 * Get the font path from the ASSIGN.SYS
 * If there is NO ASSIGN.SYS, we substitute C: or A: instead.
 *
 */
void
get_bitpath( void )
{
    int  i, sys_file;
    long j;
    int  error;
    char *fname;
    int  alen;

    olddma = Fgetdta();
    Fsetdta( &newdma );		/* Point to OUR buffer */

    strcpy( epath, "C:\\ASSIGN.SYS" );
    epath[0] = GetBaseDrive();

    bufptr     = 0L;
    BufferSize = 0L;

    error = Fsfirst( epath, 0 );	/* Normal file search for 1st file */
    if( error == 0 )
    {   /* found it! */
        bufptr = calloc( 1, newdma.d_length * 2L );
        if( bufptr )
        {
            BufferSize = newdma.d_length;

            if( (sys_file = Fopen( epath, 0 )) < 0)
            {
                Fsetdta( olddma );		/* Point to OLD buffer */
                if( bufptr )
                {
                    free( bufptr );
                    bufptr = 0L;
                }
                form_alert( 1, alert1 );
                return;
            }

            path_found = FALSE;
            do
            {
                i = 0;
                alen = (int)Fread( sys_file, BufferSize, bufptr );
                do
                {
                    if( !strncmp( &bufptr[i], "path", 4) ||
                            !strncmp( &bufptr[i], "PATH", 4) )
                    {
                        strcpy( epath, extract_path( &i, alen ) );
                        path_found = TRUE;
                        goto done;
                    }
                    else
                    {
                        while(( bufptr[i] != '\n' ) && ( i < alen )) {
                            ++i;    /* Skip to newline */
                        }
                        ++i;
                    }
                } while( i < alen );
            } while( alen == BufferSize );
done:
            Fclose( sys_file );

            if( bufptr )
            {
                free( bufptr );
                bufptr = 0L;
            }
            j = strlen( epath );
            if( epath[ j - 1 ] == '\\' )
                epath[ j - 1 ] = '\0';
        }
        else
            form_alert( 1, alert1 );
    }
    Fsetdta( olddma );		/* Point to OLD buffer */

    fname = &epath[0];
    fname = strupr( fname );
}
Exemplo n.º 14
0
/* Note: Need condition handler to clean-up allocated structures and close intput file in the event of an error */
struct extcall_package_list *exttab_parse(mval *package)
{
	int		parameter_alloc_values[MAX_ACTUALS], parameter_count, ret_pre_alloc_val, i, fclose_res;
	int		len, keywordlen;
	boolean_t	is_input[MAX_ACTUALS], is_output[MAX_ACTUALS], got_status;
	mstr		callnam, rtnnam, clnuprtn;
	mstr 		val, trans;
	void_ptr_t	pakhandle;
	enum gtm_types	ret_tok, parameter_types[MAX_ACTUALS], pr;
	char		str_buffer[MAX_TABLINE_LEN], *tbp, *end;
	char		str_temp_buffer[MAX_TABLINE_LEN];
	FILE		*ext_table_file_handle;
	struct extcall_package_list	*pak;
	struct extcall_entry_list	*entry_ptr;

	/* First, construct package name environment variable */
	memcpy(str_buffer, PACKAGE_ENV_PREFIX, SIZEOF(PACKAGE_ENV_PREFIX));
	tbp = &str_buffer[SIZEOF(PACKAGE_ENV_PREFIX) - 1];
	if (package->str.len)
	{
		/* guaranteed by compiler */
		assert(package->str.len < MAX_NAME_LENGTH - SIZEOF(PACKAGE_ENV_PREFIX) - 1);
		*tbp++ = '_';
		memcpy(tbp, package->str.addr, package->str.len);
		tbp += package->str.len;
	}
	*tbp = 0;
	/* Now we have the environment name, lookup file name */
	ext_table_file_name = GETENV(str_buffer);
	if (NULL == ext_table_file_name)
	{
		/* Environment variable for the package not found */
		rts_error_csa(CSA_ARG(NULL) VARLSTCNT(4) ERR_ZCCTENV, 2, LEN_AND_STR(str_buffer));
	}
	Fopen(ext_table_file_handle, ext_table_file_name, "r");
	if (NULL == ext_table_file_handle)
	{
		/* Package's external call table could not be found */
		rts_error_csa(CSA_ARG(NULL) VARLSTCNT(4) ERR_ZCCTOPN, 2, LEN_AND_STR(ext_table_file_name));
	}
	ext_source_line_num = 0;
	/* Pick-up name of shareable library */
	tbp = read_table(LIT_AND_LEN(str_buffer), ext_table_file_handle);
	if (NULL == tbp)
	{
		/* External call table is a null file */
		rts_error_csa(CSA_ARG(NULL) VARLSTCNT(4) ERR_ZCCTNULLF, 2, package->str.len, package->str.addr);
	}
	STRNCPY_STR(str_temp_buffer, str_buffer, MAX_TABLINE_LEN);
	val.addr = str_temp_buffer;
	val.len = STRLEN(str_temp_buffer);
	/* Need to copy the str_buffer into another temp variable since
	 * TRANS_LOG_NAME requires input and output buffers to be different.
	 * If there is an env variable present in the pathname, TRANS_LOG_NAME
	 * expands it and return SS_NORMAL. Else it returns SS_NOLOGNAM.
	 * Instead of checking 2 return values, better to check against SS_LOG2LONG
	 * which occurs if the pathname is too long after any kind of expansion.
 	 */
	if (SS_LOG2LONG == TRANS_LOG_NAME(&val, &trans, str_buffer, SIZEOF(str_buffer), dont_sendmsg_on_log2long))
	{
		/* Env variable expansion in the pathname caused buffer overflow */
		rts_error_csa(CSA_ARG(NULL) VARLSTCNT(5) ERR_LOGTOOLONG, 3, val.len, val.addr, SIZEOF(str_buffer) - 1);
	}
	pakhandle = fgn_getpak(str_buffer, INFO);
	if (NULL == pakhandle)
	{
		/* Unable to obtain handle to the shared library */
		rts_error_csa(CSA_ARG(NULL) VARLSTCNT(4) ERR_ZCUNAVAIL, 2, package->str.len, package->str.addr);
	}
	pak = get_memory(SIZEOF(*pak));
	pak->first_entry = 0;
	put_mstr(&package->str, &pak->package_name);
	pak->package_handle = pakhandle;
	pak->package_clnup_rtn = NULL;
	len = STRLEN("GTMSHLIBEXIT");
	/* At this point, we have a valid package, pointed to by pak */
#	ifdef DEBUG_EXTCALL
	FPRINTF(stderr, "GT.M external call opened package name: %s\n", pak->package_name.addr);
#	endif
	for (;;)
	{
		star_found = FALSE;
		tbp = read_table(LIT_AND_LEN(str_buffer), ext_table_file_handle);
		if (NULL == tbp)
			break;
		tbp = exttab_scan_space(str_buffer);
		/* Empty line? */
		if (!*tbp)
			continue;
		/* No, must be entryref or keyword */
		end = scan_ident(tbp);
		if (!end)
			ext_stx_error(ERR_ZCENTNAME, ext_table_file_name);
		keywordlen = end - tbp;
		end = exttab_scan_space(end);
		if ('=' == *end)
		{	/* Keyword before '=' has a string of size == STRLEN("GTMSHLIBEXIT") */
			if (keywordlen == len)
			{
				if (0 == MEMCMP_LIT(tbp, "GTMSHLIBEXIT"))
				{
					/* Skip past the '=' char */
					tbp = exttab_scan_space(end + 1);
					if (*tbp)
					{	/* We have a cleanup routine name */
						clnuprtn.addr = tbp;
						clnuprtn.len = scan_ident(tbp) - tbp;
						clnuprtn.addr[clnuprtn.len] = 0;
						pak->package_clnup_rtn =
						  (clnupfptr)fgn_getrtn(pak->package_handle, &clnuprtn, ERROR);
					} else
						ext_stx_error(ERR_ZCCLNUPRTNMISNG, ext_table_file_name);
					continue;
				}
			}
			ext_stx_error(ERR_ZCINVALIDKEYWORD, ext_table_file_name);
			continue;
		}
		if ('^' == *end)
		{
			end++;
			end = scan_ident(end);
			if (!end)
				ext_stx_error(ERR_ZCENTNAME, ext_table_file_name);
		}
		rtnnam.addr = tbp;
		rtnnam.len = INTCAST(end - tbp);
		tbp = exttab_scan_space(end);
		if (':' != *tbp++)
			ext_stx_error(ERR_ZCCOLON, ext_table_file_name);
		/* Get return type */
		ret_tok = scan_keyword(&tbp);
		/* Check for legal return type */
		switch (ret_tok)
		{
			case gtm_status:
			case gtm_void:
			case gtm_int:
			case gtm_uint:
			case gtm_long:
			case gtm_ulong:
			case gtm_char_star:
			case gtm_float_star:
			case gtm_string_star:
			case gtm_int_star:
			case gtm_uint_star:
			case gtm_long_star:
			case gtm_ulong_star:
			case gtm_double_star:
			case gtm_char_starstar:
			case gtm_pointertofunc:
			case gtm_pointertofunc_star:
			case gtm_jboolean:
			case gtm_jint:
			case gtm_jlong:
			case gtm_jfloat:
			case gtm_jdouble:
			case gtm_jstring:
			case gtm_jbyte_array:
			case gtm_jbig_decimal:
				break;
			default:
				ext_stx_error(ERR_ZCRTNTYP, ext_table_file_name);
		}
		got_status = (ret_tok == gtm_status);
		/* Get call name */
		if ('[' == *tbp)
		{
			if (star_found)
				ret_pre_alloc_val = scan_array_bound(&tbp,ret_tok);
			else
				ext_stx_error(ERR_ZCPREALLVALPAR, ext_table_file_name);
			/* We should allow the pre-allocated value upto to the maximum string size (MAX_STRLEN) plus 1 for the
			 * extra terminating NULL. Negative values would have been caught by scan_array_bound() above.
			 */
			if (ret_pre_alloc_val > MAX_STRLEN + 1)
				ext_stx_error(ERR_ZCPREALLVALINV, ext_table_file_name);
		} else
			ret_pre_alloc_val = -1;
		/* Fix C9E12-002681 */
		if ('%' == *tbp)
			*tbp = '_';
		end = scan_ident(tbp);
		if (!end)
			ext_stx_error(ERR_ZCRCALLNAME, ext_table_file_name);
		callnam.addr = tbp;
		callnam.len = INTCAST(end - tbp);
		tbp = exttab_scan_space(end);
		tbp = exttab_scan_space(tbp);
		for (parameter_count = 0;(MAX_ACTUALS > parameter_count) && (')' != *tbp); parameter_count++)
		{
			star_found = FALSE;
			/* Must have comma if this is not the first parameter, otherwise '(' */
			if (((0 == parameter_count)?'(':',') != *tbp++)
				ext_stx_error(ERR_ZCRPARMNAME, ext_table_file_name);
			tbp = exttab_scan_space(tbp);
			/* Special case: () is ok */
			if ((0 == parameter_count) && (*tbp == ')'))
				break;
			/* Looking for an I, an O or an IO */
			is_input[parameter_count] = is_output[parameter_count] = FALSE;
			if ('I' == *tbp)
			{
				is_input[parameter_count] = TRUE;
				tbp++;
			}
			if ('O' == *tbp)
			{
				is_output[parameter_count] = TRUE;
				tbp++;
			}
			if (((FALSE == is_input[parameter_count]) && (FALSE == is_output[parameter_count]))
			    ||(':' != *tbp++))
				ext_stx_error(ERR_ZCRCALLNAME, ext_table_file_name);
			/* Scanned colon--now get type */
			pr = scan_keyword(&tbp);
			if (gtm_notfound == pr)
				ext_stx_error(ERR_ZCUNTYPE, ext_table_file_name);
			if (gtm_status == pr)
			{
				/* Only one type "status" allowed per call */
				if (got_status)
					ext_stx_error(ERR_ZCMLTSTATUS, ext_table_file_name);
				else
					got_status = TRUE;
			}
			parameter_types[parameter_count] = pr;
			if ('[' == *tbp)
			{
				if (star_found && !is_input[parameter_count])
					parameter_alloc_values[parameter_count] = scan_array_bound(&tbp, pr);
				else
					ext_stx_error(ERR_ZCPREALLVALPAR, ext_table_file_name);
				/* We should allow the pre-allocated value upto to the maximum string size (MAX_STRLEN) plus 1 for
				 * the extra terminating NULL. Negative values would have been caught by scan_array_bound() above.
				 */
				if (parameter_alloc_values[parameter_count] > MAX_STRLEN + 1)
					ext_stx_error(ERR_ZCPREALLVALINV, ext_table_file_name);
			} else
				parameter_alloc_values[parameter_count] = -1;
			tbp = exttab_scan_space(tbp);
		}
		entry_ptr = get_memory(SIZEOF(*entry_ptr));
		entry_ptr->next_entry = pak->first_entry;
		pak->first_entry = entry_ptr;
		entry_ptr->return_type = ret_tok;
		entry_ptr->ret_pre_alloc_val = ret_pre_alloc_val;
		entry_ptr->argcnt = parameter_count;
		entry_ptr->input_mask = array_to_mask(is_input, parameter_count);
		entry_ptr->output_mask = array_to_mask(is_output, parameter_count);
		entry_ptr->parms = get_memory(parameter_count * SIZEOF(entry_ptr->parms[0]));
		entry_ptr->param_pre_alloc_size = get_memory(parameter_count * SIZEOF(intszofptr_t));
		entry_ptr->parmblk_size = (SIZEOF(void *) * parameter_count) + SIZEOF(intszofptr_t);
		for (i = 0 ; i < parameter_count; i++)
		{
			entry_ptr->parms[i] = parameter_types[i];
			assert(gtm_void != parameter_types[i]);
			entry_ptr->parmblk_size += parm_space_needed[parameter_types[i]];
			entry_ptr->param_pre_alloc_size[i] = parameter_alloc_values[i];
		}
		put_mstr(&rtnnam, &entry_ptr->entry_name);
		put_mstr(&callnam, &entry_ptr->call_name);

		/* The reason for passing INFO severity is that PROFILE has several routines listed in
		 * the external call table that are not in the shared library. PROFILE folks would
		 * rather see info/warning messages for such routines at shared library open time,
		 * than error out. These unimplemented routines, they say were not being called from
		 * the application and wouldn't cause any application failures. If we fail to open
		 * the shared libary, or we fail to locate a routine that is called from the
		 * application, we issue rts_error message (in extab_parse.c).
		 */
		entry_ptr->fcn = fgn_getrtn(pak->package_handle, &entry_ptr->call_name, INFO);
#		ifdef DEBUG_EXTCALL
		FPRINTF(stderr, "   package entry point: %s, address: %x\n", entry_ptr->entry_name.addr, entry_ptr->fcn);
#		endif
	}
	FCLOSE(ext_table_file_handle, fclose_res);
	return pak;
}
Exemplo n.º 15
0
/*
 * explode source RPM into the current directory
 * use filters to skip packages and files we do not need
 */
int explodeRPM(const char *source,
        filterfunc filter,
        dependencyfunc provides,
        dependencyfunc deps,
        void* userptr)
{
    char buffer[BUFFERSIZE+1]; /* make space for trailing \0 */
    FD_t fdi;
    Header h;
    char * rpmio_flags = NULL;
    rpmRC rc;
    FD_t gzdi;
    struct archive *cpio;
    struct archive_entry *cpio_entry;
    struct cpio_mydata cpio_mydata;

    rpmts ts;
    rpmVSFlags vsflags;
    const char *compr;

    if (strcmp(source, "-") == 0)
        fdi = fdDup(STDIN_FILENO);
    else
        fdi = Fopen(source, "r.ufdio");

    if (Ferror(fdi)) {
        const char *srcname = (strcmp(source, "-") == 0) ? "<stdin>" : source;
        logMessage(ERROR, "%s: %s\n", srcname, Fstrerror(fdi));
        return EXIT_FAILURE;
    }
    rpmReadConfigFiles(NULL, NULL);

    /* Initialize RPM transaction */
    ts = rpmtsCreate();
    vsflags = 0;

    /* Do not check digests, signatures or headers */
    vsflags |= _RPMVSF_NODIGESTS;
    vsflags |= _RPMVSF_NOSIGNATURES;
    vsflags |= RPMVSF_NOHDRCHK;
    (void) rpmtsSetVSFlags(ts, vsflags);

    rc = rpmReadPackageFile(ts, fdi, "rpm2dir", &h);

    ts = rpmtsFree(ts);

    switch (rc) {
        case RPMRC_OK:
        case RPMRC_NOKEY:
        case RPMRC_NOTTRUSTED:
            break;
        case RPMRC_NOTFOUND:
            logMessage(ERROR, "%s is not an RPM package", source);
            return EXIT_FAILURE;
            break;
        case RPMRC_FAIL:
        default:
            logMessage(ERROR, "error reading header from %s package\n", source);
            return EXIT_FAILURE;
            break;
    }

    /* Retrieve all dependencies and run them through deps function */
    while (deps) {
        struct rpmtd_s td;
        const char *depname;

        if (!headerGet(h, RPMTAG_REQUIRENAME, &td, HEADERGET_MINMEM))
            break;

        /* iterator */
        while ((depname = rpmtdNextString(&td))) {
            if (deps(depname, userptr)) {
                Fclose(fdi);
                return EXIT_BADDEPS;
            }
        }
        rpmtdFreeData(&td);
        break;
    }

    /* Retrieve all provides and run them through provides function */
    while (provides) {
        struct rpmtd_s td;
        const char *depname;
        int found = 0;

        if (!headerGet(h, RPMTAG_PROVIDES, &td, HEADERGET_MINMEM))
            break;

        /* iterator */
        while ((depname = rpmtdNextString(&td))) {
            if (!provides(depname, userptr)) {
                found++;
            }
        }
        rpmtdFreeData(&td);
        if (found<=0)
            return EXIT_BADDEPS;
        break;
    }

    /* Retrieve type of payload compression. */
    compr = headerGetString(h, RPMTAG_PAYLOADCOMPRESSOR);
    if (compr && strcmp(compr, "gzip")) {
        checked_asprintf(&rpmio_flags, "r.%sdio", compr);
    }
    else {
        checked_asprintf(&rpmio_flags, "r.gzdio");
    }

    /* Open uncompressed cpio stream */
    gzdi = Fdopen(fdi, rpmio_flags);
    free(rpmio_flags);

    if (gzdi == NULL) {
        logMessage(ERROR, "cannot re-open payload: %s\n", Fstrerror(gzdi));
        return EXIT_FAILURE;
    }

    /* initialize cpio decompressor */
    cpio = archive_read_new();
    if (cpio==NULL) {
        Fclose(gzdi);
        return -1;
    }

    cpio_mydata.gzdi = gzdi;
    cpio_mydata.buffer = buffer;
    archive_read_support_compression_all(cpio);
    archive_read_support_format_all(cpio);
    rc = archive_read_open(cpio, &cpio_mydata, NULL, rpm_myread, rpm_myclose);

    /* check the status of archive_open */
    if (rc != ARCHIVE_OK){
        Fclose(gzdi);
        return -1;
    }

    /* read all files in cpio archive */
    while ((rc = archive_read_next_header(cpio, &cpio_entry)) == ARCHIVE_OK){
        const struct stat *fstat;
        int64_t fsize;
        const char* filename;
        int needskip = 1; /* do we need to read the data to get to the next header? */
        int offset = 0;
        int towrite = 0;

        filename = archive_entry_pathname(cpio_entry);
        fstat = archive_entry_stat(cpio_entry);
        fsize = archive_entry_size(cpio_entry);

        /* Strip leading slashes */
        while (filename[offset] == '/')
            offset+=1;

        /* Strip leading ./ */
        while (filename[offset] == '.' && filename[offset+1] == '/')
            offset+=2;

        /* Other file type - we do not care except special cases */
        if (!S_ISREG(fstat->st_mode))
            towrite = 1;
        else
            towrite = 2;

        if (filter && filter(filename+offset, fstat, userptr)) {
            /* filter this file */
            towrite = 0;
        }

        /* Create directories */
        char* dirname = strdup(filename+offset);

        /* If the dup fails, let's hope the dirs already exist */
        if (dirname){
            char* dirptr = dirname;
            while (dirptr && *dirptr) {
                dirptr = strchr(dirptr, '/');
                if (dirptr) {
                    *dirptr = 0;
                    mkdir(dirname, 0700);
                    *dirptr = '/';
                    dirptr++;
                }
            }
            free(dirname);
        }

        /* Regular file */
        if (towrite>=2) {
            FILE *fdout = fopen(filename+offset, "w");

            if (fdout==NULL){
                rc = 33;
                break;
            }
            
            rc = archive_read_data_into_fd(cpio, fileno(fdout));
            if (rc!=ARCHIVE_OK) {
                /* XXX We didn't get the file.. well.. */
                needskip = 0;
            } else {
                needskip = 0;
                fclose(fdout);
            }
        }

        /* symlink, we assume that the path contained in symlink
         * is shorter than BUFFERSIZE */
        while (towrite && S_ISLNK(fstat->st_mode)) {
            char symlinkbuffer[BUFFERSIZE-1];

            needskip = 0;
            if ((rc = archive_read_data(cpio, symlinkbuffer, fsize))!=ARCHIVE_OK) {
                /* XXX We didn't get the file.. well.. */
                break;
            }

            if (symlink(buffer, filename+offset)) {
                logMessage(ERROR, "Failed to create symlink %s -> %s", filename+offset, buffer);
            }

            break;
        }

        if(needskip)
            archive_read_data_skip(cpio);
    }

    archive_read_finish(cpio);

    return rc != ARCHIVE_OK;
}
Exemplo n.º 16
0
void lprPrintfile(
	JOBDEF* pjd,
	char* oriFileName,
	char* spoolFileFullName,
	int16 cnId,
	void (*meter)(long totLen, long accumLen, long actLen) )
{
	char fileBuff[FILEBUFFSIZE];
	long fileLength;
	long lenData = 0;
	long lenSent = 0;    
	char o_str[100];
	int	fin;
	char rc;
	char *eM;

	if ( (fin=Fopen(spoolFileFullName, FO_READ)) < 0) {
		eM = "cannot open spool file for read"; goto errExit;
	}

	fileLength = Fseek(0, fin, 2);	/* position to end */
	Fseek(0, fin, 0);

	/* start the lprd protocol for this file */

/* command 0x02 "receive  printer job" */

	o_str[0] = 0x02;
	o_str[1] = '\0';
	strcat(o_str, pjd->rmPrinter);
	strcat(o_str, "\n");
	output(cnId, o_str, (int)strlen(o_str));

	if ( getResponse(cnId) != 0x00 ) {
		uiPrintf(uiH, uiPrERR, "unknown queue|>%s<|on remote host", pjd->rmPrinter);
		return;
	}



/* subcommand 0x02 "receive control file" */

	/* build the control file */
	strcpy(fileBuff,   "H");
	strcat(fileBuff, pjd->hostName);	/* mandatory */
	strcat(fileBuff, "\nP");
	strcat(fileBuff, pjd->userName);	/* mandatory */
	strcat(fileBuff, "\nN");
	strcat(fileBuff, oriFileName);		/* mandatory */
	strcat(fileBuff, "\n");

	if (pjd->optSendMail) {
		strcat(fileBuff,   "M");
		strcat(fileBuff, pjd->userName);
		strcat(fileBuff, "\n");
	}

	if (!pjd->optNoBanner) {
		strcat(fileBuff,   "C");
		strcat(fileBuff, pjd->hostName);	/* class for banner */
		strcat(fileBuff, "\nJ");
		strcat(fileBuff, oriFileName);		/* job name for banner */
		strcat(fileBuff, "\nL");
		strcat(fileBuff, pjd->userName);	/* banner */
		strcat(fileBuff, "\n");
	}

#if 0	/* not supported */
	strcat(fileBuff,   "U");
	strcat(fileBuff, spoolFileName);	/* unlink data file */
	strcat(fileBuff, "\n");
#endif

	if (pjd->optNCopies) {
		strcat(fileBuff,   "#");
		strcat(fileBuff, pjd->optNCopies);
		strcat(fileBuff, "\n");
	}

	if (pjd->optNIndent) {
		strcat(fileBuff,   "I");
		strcat(fileBuff, pjd->optNIndent);
		strcat(fileBuff, "\n");
	}

	if (pjd->optNWidth) {
		strcat(fileBuff,   "W");
		strcat(fileBuff, pjd->optNWidth);
		strcat(fileBuff, "\n");
	}

	if (pjd->optTitle) {
		strcat(fileBuff,   "T");
		strcat(fileBuff, pjd->optTitle);
		strcat(fileBuff, "\n");
	}

	strcat(fileBuff, pjd->optFormat);
	strcat(fileBuff, pjd->spoolFile);
	strcat(fileBuff, "\n");

#ifdef DEBUG
	uiPrintf(uiH, uiPrOK, "%s", fileBuff);
#endif

	o_str[0] = 0x02;
	ltoa(strlen(fileBuff), o_str+1, 10);
	strcat(o_str, " c");
	strcat(o_str, pjd->spoolFile);
	strcat(o_str, "\n");

	output(cnId, o_str, (int)strlen(o_str));
	rc = getResponse(cnId);
	if        (rc == 0x01) {
		eM = "connection messed up, try again"; goto errExit;
	} else if (rc == 0x02) {
		eM = "server out of storage space"; goto errExit;
	} else if (rc != 0x00) {
		eM = "no ack on sub command 3"; goto errExit;
	}

	output(cnId, fileBuff, (int)strlen(fileBuff));

	fileBuff[0] = 0;
	output(cnId, fileBuff, 1);	/* terminator */

	if ( getResponse(cnId) != 0x00 ) {
		eM = "control file not properly transferred"; goto errExit;
	}


/* subcommand 0x03 "receive data file" */

	o_str[0] = 0x03;
	ltoa(fileLength, o_str+1, 10);
	strcat(o_str, " d");
	strcat(o_str, pjd->spoolFile);
	strcat(o_str, "\n");
#ifdef DEBUG
	uiPrintf(uiH, uiPrOK, "%s", o_str+1);
#endif
	output(cnId, o_str, (int)strlen(o_str));

	rc = getResponse(cnId);
	if        (rc == 0x01) {
		eM = "connection messed up, try again"; goto errExit;
	} else if (rc == 0x02) {
		eM = "server out of storage space"; goto errExit;
	} else if (rc != 0x00) {
		eM = "unknown"; goto errExit;
	}


	while ( (lenData = Fread(fin, min(FILEBUFFSIZE, fileLength), fileBuff)) > 0) {
		lenSent += lenData;

		if (meter != NULL)
			(*meter)(fileLength, lenSent, lenData);

		output(cnId, fileBuff, (int)lenData);
	}


	fileBuff[0] = 0;
	output(cnId, fileBuff, 1);	/* terminator */

	Fclose(fin);

	if ( getResponse(cnId) != 0x00 ) {
		eM = "data file not properly transferred"; goto errExit;
	}
#ifdef DEBUG
	uiPrintf(uiH, uiPrOK, "file closed");
#endif
	return;

errExit:
	uiPrintf(uiH, uiPrERR, "%s", eM);
}	/* print_file */
Exemplo n.º 17
0
Arquivo: pack.c Projeto: nforro/rpm
/*
 * This is more than just a little insane:
 * In order to write the signature, we need to know the size and
 * the size and digests of the header and payload, which are located
 * after the signature on disk. We also need a digest of the compressed
 * payload for the main header, and of course the payload is after the
 * header on disk. So we need to create placeholders for both the
 * signature and main header that exactly match the final sizes, calculate
 * the payload digest, then generate and write the real main header to
 * be able to FINALLY calculate the digests we need for the signature
 * header. In other words, we need to write things in the exact opposite
 * order to how the RPM format is laid on disk.
 */
static rpmRC writeRPM(Package pkg, unsigned char ** pkgidp,
		      const char *fileName, char **cookie)
{
    FD_t fd = NULL;
    char * rpmio_flags = NULL;
    char * SHA1 = NULL;
    char * SHA256 = NULL;
    uint8_t * MD5 = NULL;
    char * pld = NULL;
    uint32_t pld_algo = PGPHASHALGO_SHA256; /* TODO: macro configuration */
    rpmRC rc = RPMRC_FAIL; /* assume failure */
    rpm_loff_t archiveSize = 0;
    off_t sigStart, hdrStart, payloadStart, payloadEnd;

    if (pkgidp)
	*pkgidp = NULL;

    rpmio_flags = getIOFlags(pkg);
    if (!rpmio_flags)
	goto exit;

    finalizeDeps(pkg);

    /* Create and add the cookie */
    if (cookie) {
	rasprintf(cookie, "%s %d", buildHost(), (int) (*getBuildTime()));
	headerPutString(pkg->header, RPMTAG_COOKIE, *cookie);
    }

    /* Create a dummy payload digest to get the header size right */
    pld = nullDigest(pld_algo, 1);
    headerPutUint32(pkg->header, RPMTAG_PAYLOADDIGESTALGO, &pld_algo, 1);
    headerPutString(pkg->header, RPMTAG_PAYLOADDIGEST, pld);
    pld = _free(pld);
    
    /* Check for UTF-8 encoding of string tags, add encoding tag if all good */
    if (checkForEncoding(pkg->header, 1))
	goto exit;

    /* Open the output file */
    fd = Fopen(fileName, "w+.ufdio");
    if (fd == NULL || Ferror(fd)) {
	rpmlog(RPMLOG_ERR, _("Could not open %s: %s\n"),
		fileName, Fstrerror(fd));
	goto exit;
    }

    /* Write the lead section into the package. */
    if (rpmLeadWrite(fd, pkg->header)) {
	rpmlog(RPMLOG_ERR, _("Unable to write package: %s\n"), Fstrerror(fd));
	goto exit;
    }

    /* Save the position of signature section */
    sigStart = Ftell(fd);

    /* Generate and write a placeholder signature header */
    SHA1 = nullDigest(PGPHASHALGO_SHA1, 1);
    SHA256 = nullDigest(PGPHASHALGO_SHA256, 1);
    MD5 = nullDigest(PGPHASHALGO_MD5, 0);
    if (rpmGenerateSignature(SHA256, SHA1, MD5, 0, 0, fd))
	goto exit;
    SHA1 = _free(SHA1);
    SHA256 = _free(SHA256);
    MD5 = _free(MD5);

    /* Write a placeholder header. */
    hdrStart = Ftell(fd);
    if (writeHdr(fd, pkg->header))
	goto exit;

    /* Write payload section (cpio archive) */
    payloadStart = Ftell(fd);
    if (cpio_doio(fd, pkg, rpmio_flags, &archiveSize))
	goto exit;
    payloadEnd = Ftell(fd);

    /* Re-read payload to calculate compressed digest */
    fdInitDigestID(fd, pld_algo, RPMTAG_PAYLOADDIGEST, 0);
    if (fdConsume(fd, payloadStart, payloadEnd - payloadStart))
	goto exit;
    fdFiniDigest(fd, RPMTAG_PAYLOADDIGEST, (void **)&pld, NULL, 1);

    /* Insert the payload digest in main header */
    headerDel(pkg->header, RPMTAG_PAYLOADDIGEST);
    headerPutString(pkg->header, RPMTAG_PAYLOADDIGEST, pld);
    pld = _free(pld);

    /* Write the final header */
    if (fdJump(fd, hdrStart))
	goto exit;
    if (writeHdr(fd, pkg->header))
	goto exit;

    /* Calculate digests: SHA on header, legacy MD5 on header + payload */
    fdInitDigestID(fd, PGPHASHALGO_MD5, RPMTAG_SIGMD5, 0);
    fdInitDigestID(fd, PGPHASHALGO_SHA1, RPMTAG_SHA1HEADER, 0);
    fdInitDigestID(fd, PGPHASHALGO_SHA256, RPMTAG_SHA256HEADER, 0);
    if (fdConsume(fd, hdrStart, payloadStart - hdrStart))
	goto exit;
    fdFiniDigest(fd, RPMTAG_SHA1HEADER, (void **)&SHA1, NULL, 1);
    fdFiniDigest(fd, RPMTAG_SHA256HEADER, (void **)&SHA256, NULL, 1);

    if (fdConsume(fd, 0, payloadEnd - payloadStart))
	goto exit;
    fdFiniDigest(fd, RPMTAG_SIGMD5, (void **)&MD5, NULL, 0);

    if (fdJump(fd, sigStart))
	goto exit;

    /* Generate the signature. Now with right values */
    if (rpmGenerateSignature(SHA256, SHA1, MD5, payloadEnd - hdrStart, archiveSize, fd))
	goto exit;

    rc = RPMRC_OK;

exit:
    free(rpmio_flags);
    free(SHA1);
    free(SHA256);

    /* XXX Fish the pkgid out of the signature header. */
    if (pkgidp != NULL) {
	if (MD5 != NULL) {
	    *pkgidp = MD5;
	}
    } else {
	free(MD5);
    }

    Fclose(fd);

    if (rc == RPMRC_OK)
	rpmlog(RPMLOG_NOTICE, _("Wrote: %s\n"), fileName);
    else
	(void) unlink(fileName);

    return rc;
}
Exemplo n.º 18
0
int GModel::readGEOM(const std::string &name)
{
  // this is a format (from geomview?) that Bruno Levy's Graphite code
  // can write
  FILE *fp = Fopen(name.c_str(), "r");
  if(!fp){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  int numNodes, numElements, dummy;
  if(fscanf(fp, "%d %d %d", &numNodes, &numElements, &dummy) != 3){
    fclose(fp);
    return 0;
  }

  if(!numNodes || !numElements){
    Msg::Warning("No vertices or elements found");
    fclose(fp);
    return 0;
  }

  Msg::Info("%d vertices, %d elements", numNodes, numElements);

  std::vector<MVertex*> vertexVector;
  std::map<int, std::vector<MElement*> > elements[1];

  vertexVector.resize(numNodes);
  for(int i = 0; i < numNodes; i++) {
    double x, y, z;
    if(fscanf(fp, "%lf %lf %lf", &x, &y, &z) != 3) break;
    vertexVector[i] = new MVertex(x, y, z);
  }

  for(int i = 0; i < numElements; i++) {
    int N, n[3];
    if(fscanf(fp, "%d", &N) != 1) break;
    switch(N){
    case 3:
      {
        if(fscanf(fp, "%d %d %d", &n[0], &n[1], &n[2]) != 3) break;
        for(int i = 0; i < 3; i++) n[i]--;
        std::vector<MVertex*> vertices;
        if(!getVertices(3, n, vertexVector, vertices)) break;
        elements[0][1].push_back(new MTriangle(vertices));
      }
      break;
    default:
      Msg::Error("Unknown element type in .geom reader");
      break;
    }
  }

  for(int i = 0; i < (int)(sizeof(elements) / sizeof(elements[0])); i++)
    _storeElementsInEntities(elements[i]);
  _associateEntityWithMeshVertices();
  _storeVerticesInEntities(vertexVector);

  fclose(fp);
  return 1;
}
Exemplo n.º 19
0
int GModel::writeMESH(const std::string &name, int elementTagType,
                      bool saveAll, double scalingFactor)
{
  FILE *fp = Fopen(name.c_str(), "w");
  if(!fp){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  if(noPhysicalGroups()) saveAll = true;

  int numVertices = indexMeshVertices(saveAll);

  fprintf(fp, " MeshVersionFormatted 2\n");
  fprintf(fp, " Dimension\n");
  fprintf(fp, " 3\n");

  fprintf(fp, " Vertices\n");
  fprintf(fp, " %d\n", numVertices);
  std::vector<GEntity*> entities;
  getEntities(entities);
  for(unsigned int i = 0; i < entities.size(); i++)
    for(unsigned int j = 0; j < entities[i]->mesh_vertices.size(); j++)
      entities[i]->mesh_vertices[j]->writeMESH(fp, scalingFactor);

  int numEdges = 0, numTriangles = 0, numQuadrangles = 0;
  int numTetrahedra = 0, numHexahedra = 0;
  for(eiter it = firstEdge(); it != lastEdge(); ++it){
    if(saveAll || (*it)->physicals.size()){
      numEdges += (*it)->lines.size();
    }
  }
  for(fiter it = firstFace(); it != lastFace(); ++it){
    if(saveAll || (*it)->physicals.size()){
      numTriangles += (*it)->triangles.size();
      numQuadrangles += (*it)->quadrangles.size();
    }
  }
  for(riter it = firstRegion(); it != lastRegion(); ++it){
    if(saveAll || (*it)->physicals.size()){
      numTetrahedra += (*it)->tetrahedra.size();
      numHexahedra += (*it)->hexahedra.size();
    }
  }

  if(numEdges){
    if(CTX::instance()->mesh.order == 2) // FIXME (check getPolynomialOrder())
      fprintf(fp, " EdgesP2\n");
    else
      fprintf(fp, " Edges\n");
    fprintf(fp, " %d\n", numEdges);
    for(eiter it = firstEdge(); it != lastEdge(); ++it){
      int numPhys = (*it)->physicals.size();
      if(saveAll || numPhys){
        for(unsigned int i = 0; i < (*it)->lines.size(); i++)
          (*it)->lines[i]->writeMESH(fp, elementTagType, (*it)->tag(),
                                     numPhys ? (*it)->physicals[0] : 0);
      }
    }
  }
  if(numTriangles){
    if(CTX::instance()->mesh.order == 2) // FIXME (check getPolynomialOrder())
      fprintf(fp, " TrianglesP2\n");
    else
      fprintf(fp, " Triangles\n");
    fprintf(fp, " %d\n", numTriangles);
    for(fiter it = firstFace(); it != lastFace(); ++it){
      int numPhys = (*it)->physicals.size();
      if(saveAll || numPhys){
        for(unsigned int i = 0; i < (*it)->triangles.size(); i++)
          (*it)->triangles[i]->writeMESH(fp, elementTagType, (*it)->tag(),
                                         numPhys ? (*it)->physicals[0] : 0);
      }
    }
  }
  if(numQuadrangles){
    fprintf(fp, " Quadrilaterals\n");
    fprintf(fp, " %d\n", numQuadrangles);
    for(fiter it = firstFace(); it != lastFace(); ++it){
      int numPhys = (*it)->physicals.size();
      if(saveAll || numPhys){
        for(unsigned int i = 0; i < (*it)->quadrangles.size(); i++)
          (*it)->quadrangles[i]->writeMESH(fp, elementTagType, (*it)->tag(),
                                           numPhys ? (*it)->physicals[0] : 0);
      }
    }
  }
  if(numTetrahedra){
    if(CTX::instance()->mesh.order == 2)
      fprintf(fp, " TetrahedraP2\n"); // FIXME (check getPolynomialOrder())
    else
      fprintf(fp, " Tetrahedra\n");
    fprintf(fp, " %d\n", numTetrahedra);
    for(riter it = firstRegion(); it != lastRegion(); ++it){
      int numPhys = (*it)->physicals.size();
      if(saveAll || numPhys){
        for(unsigned int i = 0; i < (*it)->tetrahedra.size(); i++)
          (*it)->tetrahedra[i]->writeMESH(fp, elementTagType, (*it)->tag(),
                                          numPhys ? (*it)->physicals[0] : 0);
      }
    }
  }
  if(numHexahedra){
    fprintf(fp, " Hexahedra\n");
    fprintf(fp, " %d\n", numHexahedra);
    for(riter it = firstRegion(); it != lastRegion(); ++it){
      int numPhys = (*it)->physicals.size();
      if(saveAll || numPhys){
        for(unsigned int i = 0; i < (*it)->hexahedra.size(); i++)
          (*it)->hexahedra[i]->writeMESH(fp, elementTagType, (*it)->tag(),
                                         numPhys ? (*it)->physicals[0] : 0);
      }
    }
  }

  fprintf(fp, " End\n");

  fclose(fp);
  return 1;
}
Exemplo n.º 20
0
/* Note: need condition handler to clean-up allocated structures and close intput file in the event of an error */
struct extcall_package_list	*exttab_parse(mval *package)
{
	int		parameter_alloc_values[MAXIMUM_PARAMETERS], parameter_count, ret_pre_alloc_val, i, fclose_res;
	boolean_t	is_input[MAXIMUM_PARAMETERS], is_output[MAXIMUM_PARAMETERS], got_status;
	mstr		callnam, rtnnam;
	void_ptr_t	pakhandle;
	enum xc_types	ret_tok, parameter_types[MAXIMUM_PARAMETERS], pr;
	char		str_buffer[MAX_TABLINE_LEN], *tbp, *end;
	FILE		*ext_table_file_handle;
	struct extcall_package_list	*pak;
	struct extcall_entry_list	*entry_ptr;

	error_def(ERR_ZCRTENOTF);
	error_def(ERR_ZCALLTABLE);
	error_def(ERR_ZCUSRRTN);
	error_def(ERR_ZCCTENV);
	error_def(ERR_ZCCTOPN);
	error_def(ERR_ZCCTNULLF);
	error_def(ERR_ZCUNAVAIL);
	error_def(ERR_ZCENTNAME);
	error_def(ERR_ZCCOLON);
	error_def(ERR_ZCRTNTYP);
	error_def(ERR_ZCRCALLNAME);
	error_def(ERR_ZCUNTYPE);
	error_def(ERR_ZCMLTSTATUS);
	error_def(ERR_ZCRPARMNAME);
	error_def(ERR_ZCPREALLVALPAR);
	error_def(ERR_ZCPREALLVALINV);

	/* First, construct package name environment variable */
	memcpy(str_buffer, PACKAGE_ENV_PREFIX, sizeof(PACKAGE_ENV_PREFIX));
	tbp = &str_buffer[sizeof(PACKAGE_ENV_PREFIX) - 1];
	if (package->str.len)
	{
		/* guaranteed by compiler */
		assert(package->str.len < MAX_NAME_LENGTH - sizeof(PACKAGE_ENV_PREFIX) - 1);
		*tbp++ = '_';
		memcpy(tbp, package->str.addr, package->str.len);
		tbp += package->str.len;
	}
	*tbp = 0;
	/* Now we have the environment name, lookup file name */
	ext_table_file_name = GETENV(str_buffer);
	if (NULL == ext_table_file_name)
	{
		/* Environment variable for the package not found */
		rts_error(VARLSTCNT(4) ERR_ZCCTENV, 2, LEN_AND_STR(str_buffer));
	}
	ext_table_file_handle = Fopen(ext_table_file_name, "r");
	if (NULL == ext_table_file_handle)
	{
		/* Package's external call table could not be found */
		rts_error(VARLSTCNT(4) ERR_ZCCTOPN, 2, LEN_AND_STR(ext_table_file_name));
	}
	ext_source_line_num = 0;
	/* pick-up name of shareable library */
	tbp = read_table(LIT_AND_LEN(str_buffer), ext_table_file_handle);
	if (NULL == tbp)
	{
		/* External call table is a null file */
		rts_error(VARLSTCNT(4) ERR_ZCCTNULLF, 2, package->str.len, package->str.addr);
	}
	pakhandle = fgn_getpak(str_buffer, INFO);
	if (NULL == pakhandle)
	{
		/* Unable to obtain handle to the shared library */
		rts_error(VARLSTCNT(4) ERR_ZCUNAVAIL, 2, package->str.len, package->str.addr);
	}
	pak = get_memory(sizeof(*pak));
	pak->first_entry = 0;
	put_mstr(&package->str, &pak->package_name);
	pak->package_handle = pakhandle;
	/* At this point, we have a valid package, pointed to by pak */
#ifdef DEBUG_EXTCALL
	FPRINTF(stderr, "GT.M external call opened package name: %s\n", pak->package_name.addr);
#endif
	for (;;)
	{
		star_found = FALSE;
		tbp = read_table(LIT_AND_LEN(str_buffer), ext_table_file_handle);
		if (NULL == tbp)
			break;
		tbp = scan_space(str_buffer);
		/* empty line? */
		if (!*tbp)
			continue;
		/* No, must be entryref */
		end = scan_ident(tbp);
		if (!end)
			ext_stx_error(ERR_ZCENTNAME, ext_table_file_name);
		if ('^' == *end)
		{
			end++;
			end = scan_ident(end);
			if (!end)
				ext_stx_error(ERR_ZCENTNAME, ext_table_file_name);
		}
		rtnnam.addr = tbp;
		rtnnam.len = INTCAST(end - tbp);
		tbp = scan_space(end);
		if (':' != *tbp++)
			ext_stx_error(ERR_ZCCOLON, ext_table_file_name);
		/* get return type */
		ret_tok = scan_keyword(&tbp);
		/* check for legal return type */
		switch (ret_tok)
		{
			case xc_status:
			case xc_void:
			case xc_int:
			case xc_uint:
			case xc_long:
			case xc_ulong:
			case xc_char_star:
			case xc_float_star:
			case xc_string_star:
			case xc_int_star:
			case xc_uint_star:
			case xc_long_star:
			case xc_ulong_star:
			case xc_double_star:
			case xc_char_starstar:
			case xc_pointertofunc:
			case xc_pointertofunc_star:
				break;
			default:
				ext_stx_error(ERR_ZCRTNTYP, ext_table_file_name);
		}
		got_status = (ret_tok == xc_status);
		/*  get call name */
		if ('[' == *tbp)
		{
			if (star_found)
				ret_pre_alloc_val = scan_array_bound(&tbp,ret_tok);
			else
				ext_stx_error(ERR_ZCPREALLVALPAR, ext_table_file_name);
			/* We should allow the pre-allocated value upto to the maximum string size (MAX_STRLEN) plus 1 for the
			 * extra terminating NULL. Negative values would have been caught by scan_array_bound() above */
			if (ret_pre_alloc_val > MAX_STRLEN + 1)
				ext_stx_error(ERR_ZCPREALLVALINV, ext_table_file_name);
		} else
			ret_pre_alloc_val = -1;
		end = scan_ident(tbp);
		if (!end)
			ext_stx_error(ERR_ZCRCALLNAME, ext_table_file_name);
		callnam.addr = tbp;
		callnam.len = INTCAST(end - tbp);
		tbp = scan_space(end);
		tbp = scan_space(tbp);
		for (parameter_count = 0;(MAXIMUM_PARAMETERS > parameter_count) && (')' != *tbp); parameter_count++)
		{
			star_found = FALSE;
			/* must have comma if this is not the first parameter, otherwise '(' */
			if (((0 == parameter_count)?'(':',') != *tbp++)
				ext_stx_error(ERR_ZCRPARMNAME, ext_table_file_name);
			tbp = scan_space(tbp);
			/* special case: () is ok */
			if ((0 == parameter_count) && (*tbp == ')'))
				break;
			/* looking for an I, an O or an IO */
			is_input[parameter_count] = is_output[parameter_count] = FALSE;
			if ('I' == *tbp)
			{
				is_input[parameter_count] = TRUE;
				tbp++;
			}
			if ('O' == *tbp)
			{
				is_output[parameter_count] = TRUE;
				tbp++;
			}
			if (((FALSE == is_input[parameter_count]) && (FALSE == is_output[parameter_count]))
			    ||(':' != *tbp++))
				ext_stx_error(ERR_ZCRCALLNAME, ext_table_file_name);
			/* scanned colon--now get type */
			pr = scan_keyword(&tbp);
			if (xc_notfound == pr)
				ext_stx_error(ERR_ZCUNTYPE, ext_table_file_name);
			if (xc_status == pr)
			{
				/* Only one type "status" allowed per call */
				if (got_status)
					ext_stx_error(ERR_ZCMLTSTATUS, ext_table_file_name);
				else
					got_status = TRUE;
			}
			parameter_types[parameter_count] = pr;
			if ('[' == *tbp)
			{
				if (star_found && !is_input[parameter_count])
					parameter_alloc_values[parameter_count] = scan_array_bound(&tbp, pr);
				else
					ext_stx_error(ERR_ZCPREALLVALPAR, ext_table_file_name);
				/* We should allow the pre-allocated value upto to the maximum string size (MAX_STRLEN) plus 1 for
				 * the extra terminating NULL. Negative values would have been caught by scan_array_bound() above */
				if (parameter_alloc_values[parameter_count] > MAX_STRLEN + 1)
					ext_stx_error(ERR_ZCPREALLVALINV, ext_table_file_name);
			} else
				parameter_alloc_values[parameter_count] = -1;
			tbp = scan_space(tbp);
		}
		entry_ptr = get_memory(sizeof(*entry_ptr));
		entry_ptr->next_entry = pak->first_entry;
		pak->first_entry = entry_ptr;
		entry_ptr->return_type = ret_tok;
		entry_ptr->ret_pre_alloc_val = ret_pre_alloc_val;
		entry_ptr->argcnt = parameter_count;
		entry_ptr->input_mask = array_to_mask(is_input, parameter_count);
		entry_ptr->output_mask = array_to_mask(is_output, parameter_count);
		entry_ptr->parms = get_memory(parameter_count * sizeof(entry_ptr->parms[0]));
		entry_ptr->param_pre_alloc_size = get_memory(parameter_count * sizeof(intszofptr_t));
		entry_ptr->parmblk_size = (SIZEOF(void *) * parameter_count) + SIZEOF(intszofptr_t);
		for (i = 0 ;  i < parameter_count ;  i++)
		{
			entry_ptr->parms[i] = parameter_types[i];
			entry_ptr->parmblk_size += parm_space_needed[parameter_types[i]];
			entry_ptr->param_pre_alloc_size[i] = parameter_alloc_values[i];
		}
		put_mstr(&rtnnam, &entry_ptr->entry_name);
		put_mstr(&callnam, &entry_ptr->call_name);

		/* the reason for passing INFO severity is that PROFILE has several routines listed in
		 * the external call table that are not in the shared library. PROFILE folks would
		 * rather see info/warning messages for such routines at shared library open time,
		 * than error out. These unimplemented routines, they say were not being called from
		 * the application and wouldn't cause any application failures. If we fail to open
		 * the shared libary, or we fail to locate a routine that is called from the
		 * application, we issue rts_error message (in extab_parse.c) */
		entry_ptr->fcn = fgn_getrtn(pak->package_handle, &entry_ptr->call_name, INFO);
#ifdef DEBUG_EXTCALL
		FPRINTF(stderr, "   package entry point: %s, address: %x\n", entry_ptr->entry_name.addr, entry_ptr->fcn);
#endif
	}
	FCLOSE(ext_table_file_handle, fclose_res);
	return pak;
}
Exemplo n.º 21
0
void load_app_icon(void)
	{
	unsigned long tmp;
	int i, fh, n, len;
	char inf[256]={0};
	char *mono_mask, *mono_data, *col_mask, *col_data;
	CICONBLK *icon=NULL;

	if(	app_icon_mode==1)
		return;
	app_icon_mode = 1;

	strcpy(inf,home);
	strcat(inf,"defaults\\MyTask.ico");
	fh=(int)Fopen(inf,FO_READ);

	if (fh<0L)
		{
		strcpy(inf,home);
		strcat(inf,"MyTask.ico");
		fh=(int)Fopen(inf,FO_READ);
		}

	if (fh>=0L)
		{
		read(fh, &tmp, 4);		n = (int)tmp;
		icons_spec_app = calloc(1,n*sizeof(struct _icons_spec_app));
		memset(icons_spec_app, 0, n*sizeof(struct _icons_spec_app));
		for(i=0; i<n; i++)
			{
			read(fh, &icons_spec_app[i].obj_no, 4);
			read(fh, &tmp, 4);			len = (int)tmp;
			icons_spec_app[i].name = calloc(1,len+1L);
			memset(icons_spec_app[i].name, 0, len+1);
			read(fh, icons_spec_app[i].name, len);
			icons_app.how_many++;

			if(mini_icons!=NULL)
				{
				if(icons_spec_app[i].obj_no<=0)
					{
/*
					OBJECT *tmp=NULL;
					int j=(int)strlen(icons_spec_app[i].name);
					for(; j>0, icons_spec_app[i].name[j]!='\\'; j--)
						;
					if(stic)
						{
						tmp = stic->str_icon(&icons_spec_app[i].name[++j], 2);
						if(tmp)
							icon = (CICONBLK*)(tmp->ob_spec.ciconblk);
						}
					else	*/
						icon = (CICONBLK*)(mini_icons[abs(icons_spec_app[i].obj_no+1)].ob_spec.ciconblk);
					}
				else
					icon = (CICONBLK*)(mini_icons[icons_spec_app[i].obj_no].ob_spec.ciconblk);
				}
			if(stic)				/* Ikonka wzieta ze StIc					*/
				{
				OBJECT *tmp=NULL;
				int j=(int)strlen(icons_spec_app[i].name);
				for(; j>0, icons_spec_app[i].name[j]!='\\'; j--)
					;
				tmp = stic->str_icon(&icons_spec_app[i].name[++j], 2);
				if(tmp)
					icon = (CICONBLK*)(tmp->ob_spec.ciconblk);
				}
			if(icon)				/* Czy mamy jakas ikonke wogole?	*/
				{
				mono_data = (char*)icon->monoblk.ib_pdata;
				mono_mask = (char*)icon->monoblk.ib_pmask;
				col_data = (char*)icon->mainlist->col_data;
				col_mask = (char*)icon->mainlist->col_mask;
				}
			if(icon)
				add_icon((void *)icons_spec_app, APP_TRAY, icons_app.how_many, mono_data, mono_mask, col_data, col_mask);
			}
		if(icon)
			{
			bigbutton->ob_next = -1;
			fix_width();
			move_applications(1);
			icons_spec_app->no = n;
			}
		close(fh);
		}
	}
Exemplo n.º 22
0
callin_entry_list*	citab_parse (void)
{
	int			parameter_count, i, fclose_res;
	uint4			inp_mask, out_mask, mask;
	mstr			labref, callnam;
	enum xc_types		ret_tok, parameter_types[MAXIMUM_PARAMETERS], pr;
	char			str_buffer[MAX_TABLINE_LEN], *tbp, *end;
	FILE			*ext_table_file_handle;
	callin_entry_list	*entry_ptr, *save_entry_ptr = 0;

	error_def(ERR_CITABENV);
	error_def(ERR_CITABOPN);
	error_def(ERR_CIENTNAME);
	error_def(ERR_COLON);
	error_def(ERR_CIRTNTYP);
	error_def(ERR_CIRCALLNAME);
	error_def(ERR_CIDIRECTIVE);
	error_def(ERR_CIRPARMNAME);
	error_def(ERR_CIPARTYPE);
	error_def(ERR_CIUNTYPE);
	error_def(ERR_SYSCALL);
	error_def(ERR_CIMAXPARAM);

	ext_table_file_name = GETENV(CALLIN_ENV_NAME);
	if (!ext_table_file_name) /* environment variable not set */
		rts_error(VARLSTCNT(4) ERR_CITABENV, 2, LEN_AND_STR(CALLIN_ENV_NAME));

	ext_table_file_handle = Fopen(ext_table_file_name, "r");
	if (!ext_table_file_handle) /* call-in table not found */
		rts_error(VARLSTCNT(11) ERR_CITABOPN, 2, LEN_AND_STR(ext_table_file_name),
			  ERR_SYSCALL, 5, LEN_AND_LIT("fopen"), CALLFROM, errno);
	ext_source_line_num = 0;
	while (read_table(LIT_AND_LEN(str_buffer), ext_table_file_handle))
	{
		if (!*(tbp = scan_space(str_buffer)))
			continue;
		if (!(end = scan_ident(tbp)))
			ext_stx_error(ERR_CIRCALLNAME, ext_table_file_name);
		callnam.addr = tbp;
		callnam.len = INTCAST(end - tbp);
		tbp = scan_space(end);
		if (':' != *tbp++)
			ext_stx_error(ERR_COLON, ext_table_file_name);
		ret_tok = scan_keyword(&tbp); /* return type */
		switch (ret_tok) /* return type valid ? */
		{
			case xc_void:
			case xc_char_star:
			case xc_int_star:
			case xc_uint_star:
			case xc_long_star:
			case xc_ulong_star:
			case xc_float_star:
			case xc_double_star:
			case xc_string_star:
				break;
			default:
				ext_stx_error(ERR_CIRTNTYP, ext_table_file_name);
		}
		labref.addr = tbp;
		if ((end = scan_labelref(tbp)))
			labref.len = INTCAST(end - tbp);
		else
			ext_stx_error(ERR_CIENTNAME, ext_table_file_name);
		tbp = scan_space(end);
		inp_mask = out_mask = 0;
		for (parameter_count = 0; (*tbp && ')' != *tbp); parameter_count++)
		{
			if (MAXIMUM_PARAMETERS <= parameter_count)
				ext_stx_error(ERR_CIMAXPARAM, ext_table_file_name);
			/* must have comma if this is not the first parameter, otherwise '(' */
			if (((0 == parameter_count)?'(':',') != *tbp++)
				ext_stx_error(ERR_CIRPARMNAME, ext_table_file_name);
			tbp = scan_space(tbp);
			if ((0 == parameter_count) && (*tbp == ')')) /* special case () */
				break;
			/* looking for an I, a O or an IO */
			mask = (1 << parameter_count);
			inp_mask |= ('I' == *tbp) ? (tbp++, mask) : 0;
			out_mask |= ('O' == *tbp) ? (tbp++, mask) : 0;
			if ((!(inp_mask & mask) && !(out_mask & mask)) || (':' != *tbp++))
				ext_stx_error(ERR_CIDIRECTIVE, ext_table_file_name);
			switch ((pr = scan_keyword(&tbp))) /* valid param type? */
			{
				case xc_int:
				case xc_uint:
				case xc_long:
				case xc_ulong:
				case xc_float:
				case xc_double:
					if (out_mask & mask)
						ext_stx_error(ERR_CIPARTYPE, ext_table_file_name);
					/* fall-thru */
				case xc_char_star:
				case xc_int_star:
				case xc_uint_star:
				case xc_long_star:
				case xc_ulong_star:
				case xc_float_star:
				case xc_double_star:
				case xc_string_star:
					break;
				default:
					ext_stx_error(ERR_CIUNTYPE, ext_table_file_name);
			}
			parameter_types[parameter_count] = pr;
			tbp = scan_space(tbp);
		}
		if (!*tbp)
			ext_stx_error(ERR_CIRPARMNAME, ext_table_file_name);
		entry_ptr = get_memory(sizeof(callin_entry_list));
		entry_ptr->next_entry = save_entry_ptr;
		save_entry_ptr = entry_ptr;
		entry_ptr->return_type = ret_tok;
		entry_ptr->argcnt = parameter_count;
		entry_ptr->input_mask = inp_mask;
		entry_ptr->output_mask = out_mask;
		entry_ptr->parms = get_memory(parameter_count * sizeof(entry_ptr->parms[0]));
		for (i = 0 ;  i < parameter_count ;  i++)
			entry_ptr->parms[i] = parameter_types[i];
		put_mstr(&labref, &entry_ptr->label_ref);
		put_mstr(&callnam, &entry_ptr->call_name);
	}
	FCLOSE(ext_table_file_handle, fclose_res);
	return entry_ptr;
}
Exemplo n.º 23
0
int GModel::readPLY2(const std::string &name)
{
  FILE *fp = Fopen(name.c_str(), "r");
  if(!fp){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  std::vector<MVertex*> vertexVector;
  std::map<int, std::vector<MElement*> > elements[5];

  char buffer[256];
  int elementary = getMaxElementaryNumber(-1) + 1;
  int nbv, nbf;
  while(!feof(fp)) {
    if(!fgets(buffer, sizeof(buffer), fp)) break;
    if(buffer[0] != '#'){ // skip comments
      sscanf(buffer, "%d", &nbv);
      if(!fgets(buffer, sizeof(buffer), fp)) break;
      sscanf(buffer, "%d", &nbf);
      Msg::Info("%d vertices", nbv);
      Msg::Info("%d triangles", nbf);
      vertexVector.resize(nbv);
      for(int i = 0; i < nbv; i++) {
	if(!fgets(buffer, sizeof(buffer), fp)) break;
	double x, y, z;
	int nb = sscanf(buffer, "%lf %lf %lf", &x, &y, &z);
	if (nb !=3){
	  if(!fgets(buffer, sizeof(buffer), fp)) break;
	  sscanf(buffer, "%lf",  &y);
	  if(!fgets(buffer, sizeof(buffer), fp)) break;
	  sscanf(buffer, "%lf",  &z);
	}
	vertexVector[i] = new MVertex(x, y, z);
      }
      for(int i = 0; i < nbf; i++) {
	if(!fgets(buffer, sizeof(buffer), fp)) break;
	int n[3], nbe;
	int nb = sscanf(buffer, "%d %d %d %d", &nbe, &n[0], &n[1], &n[2]);
	if (nb !=4){
	  if(!fgets(buffer, sizeof(buffer), fp)) break;
	  sscanf(buffer, "%d",  &n[0]);
	  if(!fgets(buffer, sizeof(buffer), fp)) break;
	  sscanf(buffer, "%d",  &n[1]);
	  if(!fgets(buffer, sizeof(buffer), fp)) break;
	  sscanf(buffer, "%d",  &n[2]);
	}
	std::vector<MVertex*> vertices;
	if(!getVertices(3, n, vertexVector, vertices)){ fclose(fp); return 0; }
	elements[0][elementary].push_back(new MTriangle(vertices));
      }
    }
  }

  for(int i = 0; i < (int)(sizeof(elements) / sizeof(elements[0])); i++)
    _storeElementsInEntities(elements[i]);
  _associateEntityWithMeshVertices();
  _storeVerticesInEntities(vertexVector);

  fclose(fp);
  return 1;
}
Exemplo n.º 24
0
int
chkdf( char *str, int flag )
{
	REG int 	ret;
	int	first,change;
	int		ret1;

	first = TRUE;
	change = f_rename;
 
	if ( flag == CPFILE )
	{
	  if ( f_rename )
	    goto cc_3;
	    
	  if ( write_save )	/* overwrite existing file	*/
	    return( OK );

cc_1:	  if ( (ret = (WORD)Fopen(fixdst, 0)) >= 0 )	
	  {			 		/* file exist */
	    Fclose( ret );
cc_3:	    ret = edname( str, CPFILE, change );
	    if ( ret == CHECK ) 
	    {
	      if ( f_rename )		/* do rename	*/
	      {
/*	        first = FALSE;	*/
		change = FALSE;
		goto cc_1;
	      } 	
	    }

	    return( ret );	
	  }
	}
	else
	{
	  if ( f_rename )	/* if rename then show box first	*/
	    goto cc_5;
		    
cc_6:	  Dsetdrv(*fixdst - 'A');

	  if ( !( ret = (WORD)Dsetpath( fixdst + 2 ) ) )	/* direcory exist */
	  {
cc_5:	    ret1 = edname( str, CPDIR, change ); 	/* update name conflict box */
	
	    change = FALSE;
	    
	    if ( ( ret1 == CHECK ) ||  			/* user enter new name	*/
	    	 ( ( ret1 == COPY ) && f_rename && first ) )
	    {
	      first = FALSE;
	      goto cc_6;
	    }	

	    return( ret1 );	
	  }
	}

	/* 0xFFDE: path not found. 0xFFDF: file not found. */

	return (((ret == EFILNF)||(ret == EPTHNF))? OK:FALSE);	
}
Exemplo n.º 25
0
/*
 * read_bitmap: Read in bitmap image data from .bmp file.
 *
 * Parameters:
 *  - filename: string name of bitmap file to be read
 *
 * Return value:
 *  - byte vector of bitmap data
 */
vector_t read_bitmap(char *filename)
{
#ifdef IMAGE_IO_DBG
    printf("In read_bitmap, filename: %s\n", filename);
#endif
    char *mode = FILE_MODE;

    /* Read in the bitmap file */
    FILE *image = Fopen(filename, mode);

    /* Extract header bytes */
    uint8_t header[BMP_HEADER_SIZE];
    Fread(header, sizeof(uint8_t), BMP_HEADER_SIZE, image);
   
#ifdef IMAGE_IO_DBG
    printf("Bitmap header: \n");
    for (int i = 0; i < BMP_HEADER_SIZE; i++) {
        printf("%x ", header[i]);
    }
    printf("\n");
#endif
   
    /* Extract width, height from header */
    uint32_t height = read_word_le(header, HEIGHT_OFFSET);
    uint32_t width = read_word_le(header, WIDTH_OFFSET);
    uint32_t num_pix = height * width;
    uint32_t num_bytes = num_pix * NUM_BYTES_IN_PIX;

#ifdef IMAGE_IO_DBG
    printf("Height: %d\n", height);
    printf("Width: %d\n", width);
    printf("Number of pixels: %d\n", num_pix);
    printf("Number of bytes in image: %d\n", num_bytes);
#endif

    /* Read the image data */
    uint8_t *image_data = (uint8_t*) Calloc(num_bytes, sizeof(uint8_t)); 
    uint32_t actual_size;
    if ((actual_size = fread(image_data, 1, num_bytes, image)) < num_bytes) {
#ifdef IMAGE_IO_DBG
        printf("Error: Couldn't read image data, actual_size: %d\n", actual_size);
#endif
        Free(image_data);
        Fclose(image);
        return NULL;
    }

#ifdef IMAGE_IO_DBG
    printf("DATA: \n[ ");
    for (uint32_t i = 0; i < num_bytes; i++) {
        printf("%x ", image_data[i]);
    }
    printf("]\n");
#endif

    uint8_t *reduced_image = (uint8_t*) Calloc(num_bytes / NUM_BYTES_IN_PIX, sizeof(uint8_t)); 
    uint32_t reduced_count = 0;
    for (uint32_t i = 0; i < num_bytes; i++) {
        if (i % NUM_BYTES_IN_PIX == 0) {
            reduced_image[reduced_count] = image_data[i];
            reduced_count++;
        } 
    }

#ifdef IMAGE_IO_DBG
    printf("REDUCED DATA: \n[ ");
    for (uint32_t i = 0; i < num_bytes / NUM_BYTES_IN_PIX; i++) {
        printf("%x ", reduced_image[i]);
    }
    printf("]\n");
#endif
    
    vector_t vec = Vector((size_t) (num_bytes / NUM_BYTES_IN_PIX));
    uint32_t *vector_data = (uint32_t*) Calloc(num_bytes / NUM_BYTES_IN_PIX, 
                                              sizeof(uint32_t));
    /* Copy over image data into vectro data and set the vector's data */
    for (uint32_t i = 0; i < num_bytes / NUM_BYTES_IN_PIX; i++) {
        vector_data[i] = (uint32_t) reduced_image[i];
    }
    assert(vec);
    vec->data = vector_data;
    
#ifdef IMAGE_IO_DBG
    printf("VECTOR DATA: Length: %zu\n[ ", vec->length);
    assert(vec->data);
    for (uint32_t i = 0; i < num_bytes / NUM_BYTES_IN_PIX; i++) {
        printf("%x ", vec->data[i]);
    }
    printf("]\n");
#endif

    Fclose(image);
    Free(image_data); 
    Free(reduced_image); 
    return vec;
}
Exemplo n.º 26
0
WORD
wrfile( char *fstr )
{
	REG int 	ret, retmsg;
	int 		inhand,outhand;
	int		time[2];
	DMABUFFER 	*mydta, *saved;
	char 		*buffer;
	long 		copysiz, bufsiz, wrsiz, tmpsiz; 
	int 		crted,sttime;
	char		buf[2];

	crted = 0;
	sttime = 1;
	retmsg = TRUE;
	rename = 0;
open:					/* open the source file	*/
	if ( ( inhand = (WORD)Fopen(fixsrc, 0) ) < 0 )		
	{				/* seek error or drive not ready */	
/*	  if ( (inhand == E_SEEK) || (inhand == EDRVNR) )
	    return( FALSE );
*/					/* skip	*/
	  if ( ( ret = fill_string( fixsrc, CNTOPEN ) ) == 1 )
	  {
	    updatnum(NUMFILE, --numfiles);
	    return SKIP;
	  }
	  else if (ret == 2)			/* retry */
		  goto open;
		else 				/* abort */
		  goto ww_3;
	}

	if ( !ch_undo() || f_cancel )		/* user want to stop */
	{
	  Fclose( inhand );
ww_3:	  f_abort = 1;
	  return( FALSE );
	}		  

	saved = (DMABUFFER *)Fgetdta();
	Fsetdta(mydta=(DMABUFFER *)malloc( (long)sizeof(DMABUFFER)));

	if ( Fsfirst( fixsrc, 0x37 ) )	
	{
	   retmsg = SKIP;
	   if ( do1_alert( RDERROR ) == 2 )	/* abort */
	   {
	     f_abort = 1;
	     retmsg = FALSE;
	   }
	   goto y2;
	}

	copysiz = mydta->d_fsize;
	buffer = (char *)malloc( copysiz );
	if ( buffer )
	{
	  bufsiz = copysiz;
	}
	else
	{
	  for (bufsiz = 128*1024L; bufsiz >= 1024L; bufsiz /= 2)
	  {
	    if ((buffer = (char *)malloc( bufsiz )) != 0)
	      break;
	  }
	  if (!buffer)
	    goto y2;
	}
  
	Fdatime( &time, inhand, 0 );	/* read the time and date */

rechkd:
	switch(chkdf(fstr, CPFILE))
	{
	    case CHECK:	
	      goto rechkd;

	    case SKIP:	
	      retmsg = SKIP;	
	      goto y1;

	    case QUIT:	
	      f_abort = 1;
	      retmsg = FALSE;
	      goto y1;

	    case FALSE:	
              retmsg = FALSE;
	      goto y1;
	}


	/* if it is move operation, then try rename first	*/

	if ( opcode == OP_MOVE )
	{			/* if same name and path, don't do it */
	  if ( strcmp( fixsrc, fixdst ) )
	    goto y22;
	
	  Fclose( inhand );

	  if ( Frename(0, fixsrc, fixdst) >= 0 )
   	  {	
	    inhand = (WORD)Fopen( fixdst, 0 );
	    if ( !p_timedate )		/* get the new time and date */
	    {
	      time[0] = Tgettime();
	      time[1] = Tgetdate();
	      Fdatime( &time, inhand, 1 ); 	
	    }
y22:	    
	    rename = 1;
	    goto y1;
	  }
	  else
	    inhand = (WORD)Fopen( fixsrc, 0 );		
	}


	while ( copysiz >= 0 ) 	/* let it passes through for zero file */
	{
	  tmpsiz = (copysiz > bufsiz) ? bufsiz : copysiz;
	  if (Fread(inhand, tmpsiz, buffer) < 0)	
	  {
	    retmsg = SKIP;
	    if ( crted )	
	      Fdelete( fixdst );

	    if (do1_alert( RDERROR ) == 2)	
	    {					/* abort */
	      f_abort = 1;
	      retmsg = FALSE;
	    }
	    goto y1;			/* skip */
	  }




create:
	  if ( sttime )
	  {
	    sttime = 0;

	    if ((outhand = (WORD)Fcreate(fixdst, mydta->d_fattr&7)) < 0)	
	    {
	      if ( ( ret = fill_string( fixdst, CNTCRTFL ) ) == 2 )
		goto create;

	      else if (ret == 3)				/* abort */
	      {
		 f_abort = 1;
		 retmsg = FALSE;
	      }
	      else	
		retmsg = SKIP;

	      goto y1;
	    }

	    crted = 1;
	  }

	  if ((wrsiz = Fwrite(outhand, tmpsiz, buffer)) < 0)	
	  {
	     retmsg = SKIP;
	     Fclose(outhand);
	     Fdelete(fixdst);

	    if (do1_alert( WRERROR ) == 2)	
	    {					/* abort */
	      f_abort = 1;
	      retmsg = FALSE;
	    }

	    goto y1;
	   }
				/* check if there are sufficent memory */
	   if (wrsiz != tmpsiz)		
	   { 			/* not sufficent memory ??*/
	      f_abort = 1;
	      retmsg = FALSE;
	      Fclose(outhand);	
	      Fdelete(fixdst);
	      buf[0] = *fixdst;
	      buf[1] = 0;
	      fill_string( buf, STDISKFU );
	      goto y1;
	   }

	   copysiz -= tmpsiz;
	   if ( !copysiz )
	     break;
	}

	if ( p_timedate )
	  Fdatime( &time, outhand, 1 );	

y0:
	Fclose(outhand);
y1:
	free(buffer);
y2:
	updatnum(NUMFILE, --numfiles);
	Fsetdta(saved);
y3:
	Fclose(inhand);
	free(mydta);

	if ( ( opcode == OP_MOVE ) && ( retmsg == TRUE ) )
	  upfdesk( fixsrc, fixdst );
	
	return(retmsg);
}
Exemplo n.º 27
0
/*
 * Save all of the undetermined messages at the top of "mbox"
 * Save all untouched messages back in the system mailbox.
 * Remove the system mailbox, if none saved there.
 */
void
quit(void)
{
	int mcount, p, modify, autohold, anystat, holdbit, nohold;
	FILE *ibuf, *obuf, *fbuf, *rbuf, *readstat, *abuf;
	struct message *mp;
	int c, fd;
	struct stat minfo;
	char *mbox, tempname[PATHSIZE];

	/*
	 * If we are read only, we can't do anything,
	 * so just return quickly.
	 */
	if (readonly)
		return;
	/*
	 * If editing (not reading system mail box), then do the work
	 * in edstop()
	 */
	if (edit) {
		edstop();
		return;
	}

	/*
	 * See if there any messages to save in mbox.  If no, we
	 * can save copying mbox to /tmp and back.
	 *
	 * Check also to see if any files need to be preserved.
	 * Delete all untouched messages to keep them out of mbox.
	 * If all the messages are to be preserved, just exit with
	 * a message.
	 */

	fbuf = Fopen(mailname, "r");
	if (fbuf == NULL)
		goto newmail;
	(void)flock(fileno(fbuf), LOCK_EX);
	rbuf = NULL;
	if (fstat(fileno(fbuf), &minfo) >= 0 && minfo.st_size > mailsize) {
		printf("New mail has arrived.\n");
		(void)snprintf(tempname, sizeof(tempname),
		    "%s/mail.RqXXXXXXXXXX", tmpdir);
		if ((fd = mkstemp(tempname)) == -1 ||
		    (rbuf = Fdopen(fd, "w")) == NULL)
			goto newmail;
#ifdef APPEND
		(void)fseeko(fbuf, mailsize, SEEK_SET);
		while ((c = getc(fbuf)) != EOF)
			(void)putc(c, rbuf);
#else
		p = minfo.st_size - mailsize;
		while (p-- > 0) {
			c = getc(fbuf);
			if (c == EOF)
				goto newmail;
			(void)putc(c, rbuf);
		}
#endif
		(void)Fclose(rbuf);
		if ((rbuf = Fopen(tempname, "r")) == NULL)
			goto newmail;
		(void)rm(tempname);
	}

	/*
	 * Adjust the message flags in each message.
	 */

	anystat = 0;
	autohold = value("hold") != NULL;
	holdbit = autohold ? MPRESERVE : MBOX;
	nohold = MBOX|MSAVED|MDELETED|MPRESERVE;
	if (value("keepsave") != NULL)
		nohold &= ~MSAVED;
	for (mp = &message[0]; mp < &message[msgCount]; mp++) {
		if (mp->m_flag & MNEW) {
			mp->m_flag &= ~MNEW;
			mp->m_flag |= MSTATUS;
		}
		if (mp->m_flag & MSTATUS)
			anystat++;
		if ((mp->m_flag & MTOUCH) == 0)
			mp->m_flag |= MPRESERVE;
		if ((mp->m_flag & nohold) == 0)
			mp->m_flag |= holdbit;
	}
	modify = 0;
	if (Tflag != NULL) {
		if ((readstat = Fopen(Tflag, "w")) == NULL)
			Tflag = NULL;
	}
	for (c = 0, p = 0, mp = &message[0]; mp < &message[msgCount]; mp++) {
		if (mp->m_flag & MBOX)
			c++;
		if (mp->m_flag & MPRESERVE)
			p++;
		if (mp->m_flag & MODIFY)
			modify++;
		if (Tflag != NULL && (mp->m_flag & (MREAD|MDELETED)) != 0) {
			char *id;

			if ((id = hfield("article-id", mp)) != NULL)
				fprintf(readstat, "%s\n", id);
		}
	}
	if (Tflag != NULL)
		(void)Fclose(readstat);
	if (p == msgCount && !modify && !anystat) {
		printf("Held %d message%s in %s\n",
			p, p == 1 ? "" : "s", mailname);
		(void)Fclose(fbuf);
		return;
	}
	if (c == 0) {
		if (p != 0) {
			writeback(rbuf);
			(void)Fclose(fbuf);
			return;
		}
		goto cream;
	}

	/*
	 * Create another temporary file and copy user's mbox file
	 * darin.  If there is no mbox, copy nothing.
	 * If he has specified "append" don't copy his mailbox,
	 * just copy saveable entries at the end.
	 */

	mbox = expand("&");
	mcount = c;
	if (value("append") == NULL) {
		(void)snprintf(tempname, sizeof(tempname),
		    "%s/mail.RmXXXXXXXXXX", tmpdir);
		if ((fd = mkstemp(tempname)) == -1 ||
		    (obuf = Fdopen(fd, "w")) == NULL) {
			warn("%s", tempname);
			(void)Fclose(fbuf);
			return;
		}
		if ((ibuf = Fopen(tempname, "r")) == NULL) {
			warn("%s", tempname);
			(void)rm(tempname);
			(void)Fclose(obuf);
			(void)Fclose(fbuf);
			return;
		}
		(void)rm(tempname);
		if ((abuf = Fopen(mbox, "r")) != NULL) {
			while ((c = getc(abuf)) != EOF)
				(void)putc(c, obuf);
			(void)Fclose(abuf);
		}
		if (ferror(obuf)) {
			warnx("%s", tempname);
			(void)Fclose(ibuf);
			(void)Fclose(obuf);
			(void)Fclose(fbuf);
			return;
		}
		(void)Fclose(obuf);
		if ((fd = open(mbox, O_CREAT | O_TRUNC | O_WRONLY, 0600)) >= 0)
			(void)close(fd);
		if ((obuf = Fopen(mbox, "r+")) == NULL) {
			warn("%s", mbox);
			(void)Fclose(ibuf);
			(void)Fclose(fbuf);
			return;
		}
	}
	if (value("append") != NULL) {
		if ((obuf = Fopen(mbox, "a")) == NULL) {
			warn("%s", mbox);
			(void)Fclose(fbuf);
			return;
		}
		(void)fchmod(fileno(obuf), 0600);
	}
	for (mp = &message[0]; mp < &message[msgCount]; mp++)
		if (mp->m_flag & MBOX)
			if (sendmessage(mp, obuf, saveignore, NULL) < 0) {
				warnx("%s", mbox);
				(void)Fclose(ibuf);
				(void)Fclose(obuf);
				(void)Fclose(fbuf);
				return;
			}

	/*
	 * Copy the user's old mbox contents back
	 * to the end of the stuff we just saved.
	 * If we are appending, this is unnecessary.
	 */

	if (value("append") == NULL) {
		rewind(ibuf);
		c = getc(ibuf);
		while (c != EOF) {
			(void)putc(c, obuf);
			if (ferror(obuf))
				break;
			c = getc(ibuf);
		}
		(void)Fclose(ibuf);
	}
	(void)fflush(obuf);
	trunc(obuf);
	if (ferror(obuf)) {
		warn("%s", mbox);
		(void)Fclose(obuf);
		(void)Fclose(fbuf);
		return;
	}
	(void)Fclose(obuf);
	if (mcount == 1)
		printf("Saved 1 message in mbox\n");
	else
		printf("Saved %d messages in mbox\n", mcount);

	/*
	 * Now we are ready to copy back preserved files to
	 * the system mailbox, if any were requested.
	 */

	if (p != 0) {
		writeback(rbuf);
		(void)Fclose(fbuf);
		return;
	}

	/*
	 * Finally, remove his /var/mail file.
	 * If new mail has arrived, copy it back.
	 */

cream:
	if (rbuf != NULL) {
		abuf = Fopen(mailname, "r+");
		if (abuf == NULL)
			goto newmail;
		while ((c = getc(rbuf)) != EOF)
			(void)putc(c, abuf);
		(void)Fclose(rbuf);
		trunc(abuf);
		(void)Fclose(abuf);
		alter(mailname);
		(void)Fclose(fbuf);
		return;
	}
	demail();
	(void)Fclose(fbuf);
	return;

newmail:
	printf("Thou hast new mail.\n");
	if (fbuf != NULL)
		(void)Fclose(fbuf);
}
Exemplo n.º 28
0
FILE *
collect(struct header *hp, int printheaders)
{
	FILE *fbuf;
	int lc, cc, escape, eofcount, fd, c, t;
	char linebuf[LINESIZE], tempname[PATHSIZE], *cp, getsub;
	sigset_t nset;
	int longline, lastlong, rc;	/* So we don't make 2 or more lines
					   out of a long input line. */

	collf = NULL;
	/*
	 * Start catching signals from here, but we're still die on interrupts
	 * until we're in the main loop.
	 */
	sigemptyset(&nset);
	sigaddset(&nset, SIGINT);
	sigaddset(&nset, SIGHUP);
	sigprocmask(SIG_BLOCK, &nset, NULL);
	if ((saveint = signal(SIGINT, SIG_IGN)) != SIG_IGN)
		signal(SIGINT, collint);
	if ((savehup = signal(SIGHUP, SIG_IGN)) != SIG_IGN)
		signal(SIGHUP, collhup);
	savetstp = signal(SIGTSTP, collstop);
	savettou = signal(SIGTTOU, collstop);
	savettin = signal(SIGTTIN, collstop);
	if (setjmp(collabort) || setjmp(colljmp)) {
		rm(tempname);
		goto err;
	}
	sigprocmask(SIG_UNBLOCK, &nset, NULL);

	noreset++;
	snprintf(tempname, sizeof(tempname), "%s/mail.RsXXXXXXXXXX", tmpdir);
	if ((fd = mkstemp(tempname)) == -1 ||
	    (collf = Fdopen(fd, "w+")) == NULL) {
		warn("%s", tempname);
		goto err;
	}
	rm(tempname);

	/*
	 * If we are going to prompt for a subject,
	 * refrain from printing a newline after
	 * the headers (since some people mind).
	 */
	t = GTO|GSUBJECT|GCC|GNL;
	getsub = 0;
	if (hp->h_subject == NULL && value("interactive") != NULL &&
	    (value("ask") != NULL || value("asksub") != NULL))
		t &= ~GNL, getsub++;
	if (printheaders) {
		puthead(hp, stdout, t);
		fflush(stdout);
	}
	if ((cp = value("escape")) != NULL)
		escape = *cp;
	else
		escape = ESCAPE;
	eofcount = 0;
	hadintr = 0;
	lastlong = 0;
	longline = 0;

	if (!setjmp(colljmp)) {
		if (getsub)
			grabh(hp, GSUBJECT);
	} else {
		/*
		 * Come here for printing the after-signal message.
		 * Duplicate messages won't be printed because
		 * the write is aborted if we get a SIGTTOU.
		 */
cont:
		if (hadintr) {
			fflush(stdout);
			fprintf(stderr,
			"\n(Interrupt -- one more to kill letter)\n");
		} else {
			printf("(continue)\n");
			fflush(stdout);
		}
	}
	for (;;) {
		colljmp_p = 1;
		c = readline(stdin, linebuf, LINESIZE);
		colljmp_p = 0;
		if (c < 0) {
			if (value("interactive") != NULL &&
			    value("ignoreeof") != NULL && ++eofcount < 25) {
				printf("Use \".\" to terminate letter\n");
				continue;
			}
			break;
		}
		lastlong = longline;
		longline = c == LINESIZE - 1;
		eofcount = 0;
		hadintr = 0;
		if (linebuf[0] == '.' && linebuf[1] == '\0' &&
		    value("interactive") != NULL && !lastlong &&
		    (value("dot") != NULL || value("ignoreeof") != NULL))
			break;
		if (linebuf[0] != escape || value("interactive") == NULL ||
		    lastlong) {
			if (putline(collf, linebuf, !longline) < 0)
				goto err;
			continue;
		}
		c = linebuf[1];
		switch (c) {
		default:
			/*
			 * On double escape, just send the single one.
			 * Otherwise, it's an error.
			 */
			if (c == escape) {
				if (putline(collf, &linebuf[1], !longline) < 0)
					goto err;
				else
					break;
			}
			printf("Unknown tilde escape.\n");
			break;
		case 'C':
			/*
			 * Dump core.
			 */
			core();
			break;
		case '!':
			/*
			 * Shell escape, send the balance of the
			 * line to sh -c.
			 */
			shell(&linebuf[2]);
			break;
		case ':':
		case '_':
			/*
			 * Escape to command mode, but be nice!
			 */
			execute(&linebuf[2], 1);
			goto cont;
		case '.':
			/*
			 * Simulate end of file on input.
			 */
			goto out;
		case 'q':
			/*
			 * Force a quit of sending mail.
			 * Act like an interrupt happened.
			 */
			hadintr++;
			collint(SIGINT);
			exit(1);
		case 'x':
			/*
			 * Exit, do not save in dead.letter.
			 */
			goto err;
		case 'h':
			/*
			 * Grab a bunch of headers.
			 */
			grabh(hp, GTO|GSUBJECT|GCC|GBCC);
			goto cont;
		case 't':
			/*
			 * Add to the To list.
			 */
			hp->h_to = cat(hp->h_to, extract(&linebuf[2], GTO));
			break;
		case 's':
			/*
			 * Set the Subject line.
			 */
			cp = &linebuf[2];
			while (isspace((unsigned char)*cp))
				cp++;
			hp->h_subject = savestr(cp);
			break;
		case 'R':
			/*
			 * Set the Reply-To line.
			 */
			cp = &linebuf[2];
			while (isspace((unsigned char)*cp))
				cp++;
			hp->h_replyto = savestr(cp);
			break;
		case 'c':
			/*
			 * Add to the CC list.
			 */
			hp->h_cc = cat(hp->h_cc, extract(&linebuf[2], GCC));
			break;
		case 'b':
			/*
			 * Add to the BCC list.
			 */
			hp->h_bcc = cat(hp->h_bcc, extract(&linebuf[2], GBCC));
			break;
		case 'i':
		case 'A':
		case 'a':
			/*
			 * Insert named variable in message.
			 */
			switch(c) {
				case 'i':
					cp = &linebuf[2];
					while(isspace((unsigned char)*cp))
						cp++;
					break;
				case 'a':
					cp = "sign";
					break;
				case 'A':
					cp = "Sign";
					break;
				default:
					goto err;
			}

			if(*cp != '\0' && (cp = value(cp)) != NULL) {
				printf("%s\n", cp);
				if(putline(collf, cp, 1) < 0)
					goto err;
			}

			break;
		case 'd':
			/*
			 * Read in the dead letter file.
			 */
			if (strlcpy(linebuf + 2, getdeadletter(),
				sizeof(linebuf) - 2)
			    >= sizeof(linebuf) - 2) {
				printf("Line buffer overflow\n");
				break;
			}
			/* FALLTHROUGH */
		case 'r':
		case '<':
			/*
			 * Invoke a file:
			 * Search for the file name,
			 * then open it and copy the contents to collf.
			 */
			cp = &linebuf[2];
			while (isspace((unsigned char)*cp))
				cp++;
			if (*cp == '\0') {
				printf("Interpolate what file?\n");
				break;
			}
			cp = expand(cp);
			if (cp == NULL)
				break;
			if (*cp == '!') {
				/*
				 * Insert stdout of command.
				 */
				char *sh;
				int nullfd, tempfd, rc;
				char tempname2[PATHSIZE];

				if ((nullfd = open("/dev/null", O_RDONLY, 0))
				    == -1) {
					warn("/dev/null");
					break;
				}

				snprintf(tempname2, sizeof(tempname2),
					 "%s/mail.ReXXXXXXXXXX", tmpdir);
				if ((tempfd = mkstemp(tempname2)) == -1 ||
				    (fbuf = Fdopen(tempfd, "w+")) == NULL) {
					warn("%s", tempname2);
					break;
				}
				unlink(tempname2);

				if ((sh = value("SHELL")) == NULL)
					sh = _PATH_CSHELL;

				rc = run_command(sh, 0, nullfd, fileno(fbuf),
				    "-c", cp+1, NULL);

				close(nullfd);

				if (rc < 0) {
					Fclose(fbuf);
					break;
				}

				if (fsize(fbuf) == 0) {
					fprintf(stderr,
					    "No bytes from command \"%s\"\n",
					    cp+1);
					Fclose(fbuf);
					break;
				}

				rewind(fbuf);
			} else if (isdir(cp)) {
				printf("%s: Directory\n", cp);
				break;
			} else if ((fbuf = Fopen(cp, "r")) == NULL) {
				warn("%s", cp);
				break;
			}
			printf("\"%s\" ", cp);
			fflush(stdout);
			lc = 0;
			cc = 0;
			while ((rc = readline(fbuf, linebuf, LINESIZE)) >= 0) {
				if (rc != LINESIZE - 1)
					lc++;
				if ((t = putline(collf, linebuf,
					 rc != LINESIZE - 1)) < 0) {
					Fclose(fbuf);
					goto err;
				}
				cc += t;
			}
			Fclose(fbuf);
			printf("%d/%d\n", lc, cc);
			break;
		case 'w':
			/*
			 * Write the message on a file.
			 */
			cp = &linebuf[2];
			while (*cp == ' ' || *cp == '\t')
				cp++;
			if (*cp == '\0') {
				fprintf(stderr, "Write what file!?\n");
				break;
			}
			if ((cp = expand(cp)) == NULL)
				break;
			rewind(collf);
			exwrite(cp, collf, 1);
			break;
		case 'm':
		case 'M':
		case 'f':
		case 'F':
			/*
			 * Interpolate the named messages, if we
			 * are in receiving mail mode.  Does the
			 * standard list processing garbage.
			 * If ~f is given, we don't shift over.
			 */
			if (forward(linebuf + 2, collf, tempname, c) < 0)
				goto err;
			goto cont;
		case '?':
			if ((fbuf = Fopen(_PATH_TILDE, "r")) == NULL) {
				warn("%s", _PATH_TILDE);
				break;
			}
			while ((t = getc(fbuf)) != EOF)
				putchar(t);
			Fclose(fbuf);
			break;
		case 'p':
			/*
			 * Print out the current state of the
			 * message without altering anything.
			 */
			rewind(collf);
			printf("-------\nMessage contains:\n");
			puthead(hp, stdout, GTO|GSUBJECT|GCC|GBCC|GNL);
			while ((t = getc(collf)) != EOF)
				putchar(t);
			goto cont;
		case '|':
			/*
			 * Pipe message through command.
			 * Collect output as new message.
			 */
			rewind(collf);
			mespipe(collf, &linebuf[2]);
			goto cont;
		case 'v':
		case 'e':
			/*
			 * Edit the current message.
			 * 'e' means to use EDITOR
			 * 'v' means to use VISUAL
			 */
			rewind(collf);
			mesedit(collf, c);
			goto cont;
		}
	}
	goto out;
err:
	if (collf != NULL) {
		Fclose(collf);
		collf = NULL;
	}
out:
	if (collf != NULL)
		rewind(collf);
	noreset--;
	sigprocmask(SIG_BLOCK, &nset, NULL);
	signal(SIGINT, saveint);
	signal(SIGHUP, savehup);
	signal(SIGTSTP, savetstp);
	signal(SIGTTOU, savettou);
	signal(SIGTTIN, savettin);
	sigprocmask(SIG_UNBLOCK, &nset, NULL);
	return (collf);
}
Exemplo n.º 29
0
int SrvrLoadWorldFromFile( uint32_t client_id, FILE *file, INDEX iWorld )
{
	FILE *pFile;
	PWORLD world = GetSetMember( WORLD, &g.worlds, iWorld );
	int sz = 0, cnt, version, size;
	char tag[4]; // read in make sure we're still aligned in the file...
	int linesize;
	int nlines;
	PFLATLAND_MYLINESEG *linearray;
	int wallsize;
	int nwalls;
	PWALL *wallarray;
	int sectorsize;
	int nsectors;
	PSECTOR *sectorarray;
	int namesize;
	int nnames;
	PNAME *namearray;
	int texturesize;
	int ntextures;
	PFLATLAND_TEXTURE *texturearray;

	INDEX texture;

	if( !world )
		return 0;
	{
		char buffer[256];
      GetNameText( iWorld, world->name, buffer, sizeof( buffer ) );
		Fopen( pFile, buffer, "rb" );
	}
	if( !pFile )
      return 0;
	ResetWorld( iWorld ); // make sure this thing is empty );

	sz += fread( tag, 1, 4, pFile );
	if( strncmp( tag, "FLAT", 4 ) ) 
	{
		Log( "Alignment error in file load... totally invalid file." );
		return 0;
	}
	sz += fread( &size, 1, sizeof( size ), pFile );
	if( size < 10 ) // can assume that it was a version ID
		version = size;
	else
		sz = fread( &version, 1, sizeof( version ), pFile );

	if( version < 8 )
	{
		texture = SrvrMakeTexture( client_id, iWorld, SrvrMakeName( client_id, iWorld, WIDE( "Default" ) ) );
		SrvrSetSolidColor( client_id, iWorld, texture, AColor( 43, 76, 180, 0x80 ) );
	}
	Log1( "Loading version: %d", version );

	sz += fread( tag, 1, 4, pFile );
	if( strncmp( tag, "LINE", 4 ) )
	{
		// was not LINE or FLAT tag...
		Log( "Alignment error in file line load." );
		return 0;
	}

	if( version > 9 )
		sz += fread( &linesize, 1, sizeof( linesize ), pFile );

	sz += fread( &nlines, 1, sizeof(nlines), pFile );
	linearray = (PFLATLAND_MYLINESEG*)Allocate( sizeof( PFLATLAND_MYLINESEG ) * nlines );
	for( cnt = 0; cnt < nlines; cnt++ )
	{
		PFLATLAND_MYLINESEG pls;
		LINESEGFILE lsf;
		sz += fread( &lsf, 1, sizeof(LINESEGFILE), pFile );
		pls = GetFromSet( FLATLAND_MYLINESEG, &world->lines );
#ifdef OUTPUT_TO_VIRTUALITY
		pls->pfl = CreateFacetLine( world->object, lsf.r.o, lsf.r.n, lsf.start, lsf.end );
#endif
		linearray[cnt] = pls;
		/* some sort of update line... */
		SetRay( &pls->r, &lsf.r );
		if( version < 9 )
		{
			pls->r.o[1] = -pls->r.o[1];
			pls->r.n[1] = -pls->r.n[1];
		}
		pls->dFrom = lsf.start;
		pls->dTo = lsf.end;

	}

	sz += fread( tag, 1, 4, pFile );
	if( strncmp( tag, "WALL", 4 ) )
	{
		Log( "Alignment error in file wall load." );
		return 0;
	}
	if( version > 9 )
		sz += fread( &wallsize, 1, sizeof( wallsize ), pFile );

	sz += fread( &nwalls, 1, sizeof(nwalls), pFile );
	wallarray = (PWALL*)Allocate( sizeof( PWALL ) * nwalls );
	for( cnt = 0; cnt < nwalls; cnt++ )
	{
		wallarray[cnt] = GetFromSet( WALL, &world->walls );
	}
	for( cnt = 0; cnt < nwalls; cnt++ )
	{
		FILEWALLV1 ReadWall1;
		FILEWALLV2 ReadWall2;
		PWALL pwall;
		pwall = wallarray[cnt];
		if( version < 2 )
		{
			sz += fread( &ReadWall1, 1, sizeof( FILEWALLV1 ), pFile );
			pwall->flags = ReadWall1.flags;
			pwall->iSector = ReadWall1.nSector;

			SetLineWorld( world, pwall->iLine, linearray[ReadWall1.nLine] );

			if( ReadWall1.nWallInto == -1 )
				pwall->iWallInto = INVALID_INDEX;
			else
				pwall->iWallInto = GetMemberIndex( WALL, &world->walls, wallarray[ReadWall1.nWallInto] );
			pwall->iWallStart = GetMemberIndex( WALL, &world->walls, wallarray[ReadWall1.nWallStart] );
			pwall->iWallEnd = GetMemberIndex( WALL, &world->walls, wallarray[ReadWall1.nWallEnd] );
		}
		else 
		{
			sz += fread( &ReadWall2, 1, sizeof( FILEWALLV2 ), pFile );
			pwall->flags = ReadWall2.flags;
			pwall->iSector = ReadWall2.nSector;
			if( ReadWall2.nLine != -1 )
			{
				pwall->iLine = GetMemberIndex( FLATLAND_MYLINESEG, &world->lines, linearray[ReadWall2.nLine] );
				//SetLine( pwall->line, linearray[ReadWall2.nLine] );
			}
			else
			{
				Log( "Wall without line? cant be!" );
				DebugBreak();
				pwall->iLine = INVALID_INDEX;
			}
			if( ReadWall2.nWallInto == -1 )
				pwall->iWallInto = INVALID_INDEX;
			else
				pwall->iWallInto = GetMemberIndex( WALL, &world->walls, wallarray[ReadWall2.nWallInto] );
			pwall->iWallStart = GetMemberIndex( WALL, &world->walls, wallarray[ReadWall2.nWallStart] );
			pwall->iWallEnd = GetMemberIndex( WALL, &world->walls, wallarray[ReadWall2.nWallEnd] );
		}
	}	

	sz += fread( tag, 1, 4, pFile );
	if( strncmp( tag, "SECT", 4 ) )
	{
		Log2( "Alignment error in file sector load. %s(%d)", __FILE__, __LINE__ );
		return 0;
	}
	if( version > 9 )
		sz += fread( &sectorsize, 1, sizeof( sectorsize ), pFile );
	sz += fread( &nsectors, 1, sizeof(nsectors), pFile );
	sectorarray = (PSECTOR*)Allocate( sizeof( PSECTOR ) * nsectors );
	for( cnt = 0; cnt < nsectors; cnt++ )
	{
		FILESECTORV3 ReadSector3;
		FILESECTORV4 ReadSector4;
		FILESECTORV5 ReadSector5;
		FILESECTORV8 ReadSector8;
		INDEX sector;
		sectorarray[cnt] = GetFromSet( SECTOR, &world->sectors );
#ifdef OUTPUT_TO_VIRTUALITY
		sectorarray[cnt]->facet = AddNormalPlane( world->object, VectorConst_0, VectorConst_Z, 0 );
#endif
		sector =  GetMemberIndex( SECTOR, &world->sectors, sectorarray[cnt] );
		if( version < 8 )
		{
			// one texture is sufficient...
			// in fact textures should be highly sharable.
			sectorarray[cnt]->iTexture = texture;
		}
		if( version < 4 )
		{	
			/*
			{
			char name[20];
			sprintf( name, "%d", SectorIDs++ );
			sectorarray[cnt]->name = GetName( &world->names, name );
			}
			*/
			sectorarray[cnt]->iName = INVALID_INDEX;
			sz += fread( &ReadSector3, 1, sizeof( FILESECTORV3 ), pFile );
			sectorarray[cnt]->flags = ReadSector3.flags;
			sectorarray[cnt]->iWorld = iWorld;
			SetRay( &sectorarray[cnt]->r, &ReadSector3.r );
			sectorarray[cnt]->iWall = GetMemberIndex( WALL, &world->walls, wallarray[ReadSector3.nwall] );

			if( version < 3 )
			{
				ComputeSectorOrigin( iWorld, sector);
			}
		}
		else if( version < 5 )
		{
			sz += fread( &ReadSector4, 1, sizeof( FILESECTORV4 ), pFile );
			/*
			{
			char name[20];
			sprintf( name, "%d", ReadSector4.nID );
			sectorarray[cnt]->name = GetName( &world->names, name );
			if( atoi( name ) > SectorIDs )
			SectorIDs = atoi( name );
			}
			*/
			sectorarray[cnt]->iName = INVALID_INDEX;
			sectorarray[cnt]->flags = ReadSector4.flags;
			sectorarray[cnt]->iWorld = iWorld;
			SetRay( &sectorarray[cnt]->r, &ReadSector4.r );
			sectorarray[cnt]->iWall = GetMemberIndex( WALL, &world->walls, wallarray[ReadSector4.nwall] );
		}
		else if( version < 8 )
		{
			sz += fread( &ReadSector5, 1, sizeof( FILESECTORV5 ), pFile );
			sectorarray[cnt]->iName = ReadSector5.nName;
			sectorarray[cnt]->flags = ReadSector5.flags;
			sectorarray[cnt]->iWorld = iWorld;
			SetRay( &sectorarray[cnt]->r, &ReadSector5.r );
			sectorarray[cnt]->iWall = GetMemberIndex( WALL, &world->walls, wallarray[ReadSector5.nwall] );
		}
		else
		{
			sz += fread( &ReadSector8, 1, sizeof( FILESECTORV8 ), pFile );
			sectorarray[cnt]->iName = ReadSector8.nName;
			sectorarray[cnt]->flags = ReadSector8.flags;
			sectorarray[cnt]->iWorld = iWorld;
			SetRay( &sectorarray[cnt]->r, &ReadSector8.r );
			sectorarray[cnt]->iWall = ReadSector8.nwall;
			sectorarray[cnt]->iTexture = ReadSector8.nTexture;
		}
		// walls should all be valid at this point...
		// have valid lines, and valid linkings...
		ComputeSectorPointList( iWorld, sector, NULL );
		ComputeSectorOrigin( iWorld, sector );
#ifdef OUTPUT_TO_VIRTUALITY
		OrderObjectLines( world->object );
#endif
	}

	// fix sector references in walls.
	//for( cnt = 0; cnt < nwalls; cnt++ )
	//{
	//	wallarray[cnt]->iSector = wallarray[cnt]->iSector;
	//}

	for( cnt = 0; cnt < nwalls; cnt++ )
	{
		if( wallarray[cnt]->iLine == INVALID_INDEX )
		{
			SrvrDestroySector( client_id, iWorld, wallarray[cnt]->iSector );
			Log( "attempting to fix broken walls" );
			break;
		}
	}

	if( version >= 5 )
	{
		sz += fread( tag, 1, 4, pFile );
		if( strncmp( tag, "NAME", 4 ) )
		{
			Log2( "Alignment error in name section load. %s(%d)", __FILE__, __LINE__ );
			return 0;
		}
		if( version > 9 )
			sz += fread( &namesize, 1, sizeof( namesize ), pFile );
		sz += fread( &nnames, 1, sizeof(nnames), pFile );
		namearray = (PNAME*)Allocate( sizeof( PNAME ) * nnames );
		for( cnt = 0; cnt < nnames; cnt++ )
		{  	
			namearray[cnt] = GetFromSet( NAME, &world->names );
			if( version < 6 )
			{
				uint32_t length;
 				namearray[cnt]->name = (struct name_data*)Allocate( sizeof( *namearray[cnt]->name ) );
				sz += fread( &length, 1, sizeof( length ), pFile );
            namearray[cnt]->name[0].length = length;
				namearray[cnt]->name[0].name = (TEXTSTR)Allocate( namearray[cnt]->name[0].length + 1 );
 				sz += fread( namearray[cnt]->name[0].name, 1, namearray[cnt]->name[0].length, pFile );
		      namearray[cnt]->name[0].name[namearray[cnt]->name[0].length] = 0;
		      namearray[cnt]->lines = 1;
			}
			else if( version < 7 )
			{
				int l;
				sz += fread( &namearray[cnt]->lines, 1, sizeof( namearray[cnt]->lines ), pFile );
				if( namearray[cnt]->lines )
				{
					namearray[cnt]->name = (struct name_data*)Allocate( sizeof( *namearray[cnt]->name ) * namearray[cnt]->lines );
					for( l = 0; l < namearray[cnt]->lines; l++ )
					{
						sz += fread( &namearray[cnt]->name[l].length, 1, sizeof( namearray[cnt]->name[l].length ), pFile );
						namearray[cnt]->name[l].name = (TEXTSTR)Allocate( namearray[cnt]->name[l].length + 1 );
						sz += fread( namearray[cnt]->name[l].name, 1, namearray[cnt]->name[l].length, pFile );
						namearray[cnt]->name[l].name[namearray[cnt]->name[l].length] = 0;
					}	
				}
				else
					namearray[cnt]->name = NULL;
			}
			else
			{
				int l;
				sz += fread( &namearray[cnt]->flags, 1, sizeof( namearray[cnt]->flags ), pFile );
				sz += fread( &namearray[cnt]->lines, 1, sizeof( namearray[cnt]->lines ), pFile );
				if( namearray[cnt]->lines )
				{
					namearray[cnt]->name = (struct name_data*)Allocate( sizeof( *namearray[cnt]->name ) * namearray[cnt]->lines );
					for( l = 0; l < namearray[cnt]->lines; l++ )
					{
						sz += fread( &namearray[cnt]->name[l].length, 1, sizeof( namearray[cnt]->name[l].length ), pFile );
						namearray[cnt]->name[l].name = (TEXTSTR)Allocate( namearray[cnt]->name[l].length + 1 );
						sz += fread( namearray[cnt]->name[l].name, 1, namearray[cnt]->name[l].length, pFile );
						namearray[cnt]->name[l].name[namearray[cnt]->name[l].length] = 0;
					}	
				}
				else
					namearray[cnt]->name = NULL;
			}
		}
       /*
		for( cnt = 0; cnt < nsectors; cnt++ )
		{
			if( (int)sectorarray[cnt]->iName == -1 )
				sectorarray[cnt]->iName = INVALID_INDEX;
			else
			{
				int n;
				PNAME pName = namearray[(int)sectorarray[cnt]->name];
				if( pName->name && pName->name[0].name )
					if( ( n = atoi( pName->name[0].name ) ) > SectorIDs )
						SectorIDs = n;
				sectorarray[cnt]->name = pName;
			}
	   }
      */
		if( version >= 8 )
		{
			sz += fread( tag, 1, 4, pFile );
			if( strncmp( tag, "TEXT", 4 ) )
			{
				Log2( "Alignment error in texture section load. %s(%d)", __FILE__, __LINE__ );
				return 0;
			}
			if( version > 9 )
				sz += fread( &texturesize, 1, sizeof( texturesize ), pFile );
			sz += fread( &ntextures, 1, sizeof(ntextures), pFile );
			texturearray = (PFLATLAND_TEXTURE*)Allocate( sizeof( PFLATLAND_TEXTURE ) * ntextures );
			for( cnt = 0; cnt < ntextures; cnt++ )
			{
				char flag;
				int nName;
				sz += fread( &nName, 1, sizeof( nName ), pFile );
				texturearray[cnt] = GetFromSet( FLATLAND_TEXTURE, &world->textures );
				texturearray[cnt]->iName = GetMemberIndex( NAME, &world->names, namearray[nName] );
				sz += fread( &flag, 1, sizeof( flag ), pFile );
				texturearray[cnt]->flags.bColor = flag;
				if( flag )
				{
					sz += fread( &texturearray[cnt]->data.color, 1, sizeof(CDATA), pFile );
				}
			}
		   
			//for( cnt = 0; cnt < nsectors; cnt++ )
			//{
			//	int ntexture = (int)sectorarray[cnt]->iTexture;
         //   sectorarray[cnt]->texture = NULL;
			//	SetTexture( sectorarray[cnt]->texture, texturearray[ntexture] );
			//}
			Release( texturearray );
		}

		Release( namearray );
	}

	if( version > 9 )
	{
		if( sz != size )
		{
			Log2( "Total load size %d is not %d", sz, size );
		}
	}

	//for( cnt = 0; cnt < nsectors; cnt++ )
	{
		//PSECTOR pSector = sectorarray[cnt];
		// again with the min/max fetch with
		// spacetree add
		//pSector->spacenode = AddSpaceNode( &world->spacetree, pSector, min, max );
	}

	Release( linearray );
	Release( wallarray );
	Release( sectorarray );
	ValidateWorldLinks(iWorld);
	return version;
}
Exemplo n.º 30
0
void main(void)
{
	long		adr,max,length;
	int		dummy,handle,freq_div=1;
	char		tch;
	DTA		*buf;

	Cconws(CLEAR_HOME);
	Cconws("Amiga 4/6/8 voices & xxCH DSP Replay Routine by Simplet / FATAL DESIGN\r\n");
	Cconws("----------------------------------------------------------------------\r\n\n");

	dummy=Fsfirst(MODNAME,0);
	buf=Fgetdta();
	length=buf->d_length;
	
	if (dummy!=0)
		{
		Cconws("Disk Error!\r\nPress any key...");
		Crawcin();exit();
		}

	Cconws("Allocating Memory...");

	adr=Malloc(length+20832);		/* Workspace takes up to 20832 bytes */
	if (adr<=0)
		{
		Cconws("Error!\r\nNot enough Memory to load!\r\nPress any key...");
		Crawcin();exit();
		}
	
	Cconws("Ok!\r\nLoading Module...");

	handle=Fopen(MODNAME,FO_READ);
	Fread(handle,length,adr);
	Fclose(handle);

	Cconws("\r\nInitialising Module and Samples...");

	dummy=MGTK_Init_Module_Samples(adr,adr+length+20832);
	if (dummy==-3)
		{
		Cconws("Error!\r\n");
		Cconws("Not enough workspace to prepare samples!\r\n");
		Cconws("Press any key...");
		Crawcin();exit();
		}

	Cconws("Ok!\r\nInitialising DSP Program...");

	dummy=MGTK_Init_DSP();
	if (dummy!=0)
		{
		Cconws("Error!\r\n");
		Cconws("DSP Program couldn't be loaded!\r\n");
		Cconws("Press any key...");
		Crawcin();exit();
		}

	Cconws("Ok!\r\n\n");

	MGTK_Save_Sound();
	MGTK_Init_Sound();
	MGTK_Set_Replay_Frequency(freq_div);
	MGTK_Restart_Loop=-1;
	MGTK_Play_Music();

	Cconws("You can use the following keys :\r\n");
	Cconws("  - or + for previous or next music position\r\n");
	Cconws("  / or * for previous or next replay frequency\r\n");
	Cconws("  L for play, P for pause, S for stop\r\n");
	Cconws("  Space to quit\r\n");

	do
		{
		tch=Crawcin();
		switch ( tch-32*((97<=tch) && (tch<=122)) )
			{
			case	'-':	MGTK_Previous_Position();break;
			case '+':	MGTK_Next_Position();break;
			case '/':	if (freq_div>1)
					MGTK_Set_Replay_Frequency(--freq_div);break;
			case '*':	if (freq_div<5)
					MGTK_Set_Replay_Frequency(++freq_div);break;
			case	'L':	MGTK_Play_Music();break;
			case	'P':	MGTK_Pause_Music();break;
			case	'S':	MGTK_Stop_Music();break;
			}
		}
	while (tch!=*" ");
		
	MGTK_Stop_Music();
	MGTK_Restore_Sound();
}