示例#1
0
// packing: use RCO_DATA_COMPRESSION_* constants
uint8_t
write_rco (rRCOFile * rco, char *fn, writerco_options opts)
{
  uint32_t i;
  rRCOFile_writehelper rcoH;

  // delete file if exists
  if (file_exists (fn)) {
    if (remove (fn)) {
      error ("Unable to write to file %s", fn);
      return FALSE;
    }
  }

  rcoH.rco = rco;
  rcoH.fp = fopen (fn, "wb");
  if (!rcoH.fp) {
    error ("Unable to open file %s", fn);
    return FALSE;
  }

  PRFHeader header;

  header.signature = RCO_SIGNATURE;
  header.version =
      (opts.packHeader == RCO_DATA_COMPRESSION_RLZ ? 0x95 : opts.packHeader ==
      RCO_DATA_COMPRESSION_ZLIB ? 0x90 : 0x71);
  if (rco->verId) {		// we won't actually use specified value,
    // rather, we'll require using the minimum
    // version from above
    if (rco->verId > header.version)
      header.version = rco->verId;
  }
  header.null = 0;
  header.compression = (opts.packHeader << 4) | (rco->umdFlag & 0xF);

  header.pMainTable = 0xA4;	// pretty much always the case
  // set other sections to nothing for now
  header.pVSMXTable = header.pTextTable = header.pSoundTable =
      header.pModelTable = header.pImgTable = header.pObjTable =
      header.pAnimTable = RCO_NULL_PTR;
  header.pUnknown = header.pFontTable = RCO_NULL_PTR;

  // don't know positions of text/label/event data too, but we do know the
  // lengths for label/events
  // header.pTextData = header.pLabelData = header.pEventData = 0;
  header.lLabelData = rco->labelsLen;
  header.lEventData = rco->eventsLen;
  header.lTextData = 0;

  // set pointer sections to blank too
  header.pTextPtrs = header.pImgPtrs = header.pModelPtrs = header.pSoundPtrs =
      header.pObjPtrs = header.pAnimPtrs = RCO_NULL_PTR;

  header.lTextPtrs = header.lImgPtrs = header.lModelPtrs = header.lSoundPtrs =
      header.lObjPtrs = header.lAnimPtrs = 0;

  // also blank...
  header.pImgData = header.pSoundData = header.pModelData = RCO_NULL_PTR;
  header.lImgData = header.lSoundData = header.lModelData = 0;

  header.unknown[0] = header.unknown[1] = header.unknown[2] = 0xFFFFFFFF;

  // write resources to a separate file to get around the issue of unknown
  // packed size when writing the header (and you can't change it backed after
  // the header is packed...)
  FILE *fTmp = NULL;

  if ((rco->tblImage && rco->tblImage->numSubentries)
      || (rco->tblSound && rco->tblSound->numSubentries)
      || (rco->tblModel && rco->tblModel->numSubentries)) {
    uint32_t totalPackedLen = 0;
    rRCOEntry *rcoNode;

    fTmp = tmpfile ();

    if (rco->tblImage && rco->tblImage->numSubentries) {
      for (rcoNode = rco->tblImage->firstChild; rcoNode;
	  rcoNode = rcoNode->next) {
	// our compression decision thing
	uint32_t c = ((rRCOImgModelEntry *) (rcoNode->extra))->compression;

	if (((rRCOImgModelEntry *) (rcoNode->extra))->format < RCO_IMG_BMP) {
	  if (opts.packImgCompr != -1)
	    c = opts.packImgCompr;
	} else {
	  if (opts.packImg != -1)
	    c = opts.packImg;
	}

	if (rcoNode->srcLenUnpacked) {
	  rcoNode->srcLen = rco_write_resource (fTmp, rcoNode, c, &opts, rco);
	  if (!rcoNode->srcLen && rcoNode->labelOffset != RCO_NULL_PTR)
	    warning ("[resource] Can't write image resource '%s'!",
		rco->labels + rcoNode->labelOffset);
	}
	rcoNode->srcCompression = c;
	rcoNode->srcAddr = totalPackedLen;

	totalPackedLen +=
	    (rcoNode->srcLen % 4 ? (rcoNode->srcLen / 4) * 4 +
	    4 : rcoNode->srcLen);
      }
      header.lImgData = totalPackedLen;
    }

    totalPackedLen = 0;
    if (rco->tblSound && rco->tblSound->numSubentries) {
      for (rcoNode = rco->tblSound->firstChild; rcoNode;
	  rcoNode = rcoNode->next) {
	if (rcoNode->srcLenUnpacked) {
	  uint32_t packedLen = rco_write_resource (fTmp, rcoNode,
	      RCO_DATA_COMPRESSION_NONE,
	      &opts,
	      rco);

	  if (!packedLen && rcoNode->labelOffset != RCO_NULL_PTR)
	    warning ("[resource] Can't write sound resource '%s'!",
		rco->labels + rcoNode->labelOffset);
	  totalPackedLen += ALIGN_TO_4 (packedLen);
	  // if(totalPackedLen %4) totalPackedLen += 4-(totalPackedLen%4);
	}
      }
      header.lSoundData = totalPackedLen;
    }

    totalPackedLen = 0;
    if (rco->tblModel && rco->tblModel->numSubentries) {
      for (rcoNode = rco->tblModel->firstChild; rcoNode;
	  rcoNode = rcoNode->next) {
	uint32_t c = ((rRCOImgModelEntry *) (rcoNode->extra))->compression;

	if (opts.packModel != -1)
	  c = opts.packModel;

	if (rcoNode->srcLenUnpacked) {
	  rcoNode->srcLen = rco_write_resource (fTmp, rcoNode, c, &opts, rco);
	  if (!rcoNode->srcLen && rcoNode->labelOffset != RCO_NULL_PTR)
	    warning ("[resource] Can't write model resource '%s'!",
		rco->labels + rcoNode->labelOffset);
	}
	rcoNode->srcCompression = c;
	rcoNode->srcAddr = totalPackedLen;

	totalPackedLen +=
	    (rcoNode->srcLen % 4 ? (rcoNode->srcLen / 4) * 4 +
	    4 : rcoNode->srcLen);
      }
      header.lModelData = totalPackedLen;
    }

    rewind (fTmp);
  }

  filewrite (rcoH.fp, &header, sizeof (header));

  rcoH.tables = 0;

  // if compressing, write to memory
  if (opts.packHeader) {
    rcoH.tables = malloc (RCO_WRITE_MEM_BUFFER);
    rcoH.memPos = rcoH.tablesSize = 0;
    rcoH.tablesBuffered = RCO_WRITE_MEM_BUFFER;
    rcoH.memOffset = ftell (rcoH.fp);
  }

  rcoH.sizeImg = rcoH.sizeModel = rcoH.sizeSound = rcoH.sizeText = 0;
  rcoH.longestLangData = 0;

  write_entry (&rcoH, &(rco->tblMain), 0xA4	/* typically where the main
						 * table is written to */ , 0,
      TRUE);

  // fix up object/anim extra data
  {
    if (rco->tblObj)
      rco_write_fix_refs (rco->tblObj, &rcoH, rco, RCO_OBJ_EXTRA_LEN,
	  RCO_OBJ_EXTRA_LEN_NUM, TRUE);
    if (rco->tblAnim)
      rco_write_fix_refs (rco->tblAnim, &rcoH, rco, RCO_ANIM_EXTRA_LEN,
	  RCO_ANIM_EXTRA_LEN_NUM, FALSE);
  }

  {				// write hashtable data

    /* { // special case for text hashes if(rco->numPtrText) { header.pTextPtrs
     * = rcowrite_ftell(&rcoH); for(i=0; i<rco->numPtrText; i++) { uint32_t
     * writePtr = 0; if(rco->ptrText[i].textEntry && rco->ptrText[i].index)
     * writePtr = rco->ptrText[i].textEntry->offset + sizeof(RCOEntry) +
     * sizeof(RCOTextEntry) + (rco->ptrText[i].index -
     * ((rRCOTextEntry*)(rco->ptrText[i].textEntry->extra))->indexes)*sizeof(RCOTextIndex);
     * rco_fwrite(&rcoH, &writePtr, sizeof(uint32_t)); } } } */
    if (rco->tblText) {
      header.pTextPtrs = rcowrite_ftell (&rcoH);
      header.lTextPtrs = 0;

      // generate sorted list of text entries, sorted by languageID
      rRCOEntry **sList = make_sorted_list_of_subentries (rco->tblText,
	  text_hash_table_qsort);

      for (i = 0; i < rco->tblText->numSubentries; i++)
	header.lTextPtrs += write_text_hash_table (&rcoH, sList[i], rco);
      free (sList);

      header.lTextPtrs *= sizeof (uint32_t);
    }

    if (rco->tblImage) {
      header.pImgPtrs = rcowrite_ftell (&rcoH);
      header.lImgPtrs =
	  write_hash_table (&rcoH, rco->tblImage, rco) * sizeof (uint32_t);
    }
    if (rco->tblModel) {
      header.pModelPtrs = rcowrite_ftell (&rcoH);
      header.lModelPtrs =
	  write_hash_table (&rcoH, rco->tblModel, rco) * sizeof (uint32_t);
    }
    if (rco->tblSound) {
      header.pSoundPtrs = rcowrite_ftell (&rcoH);
      header.lSoundPtrs =
	  write_hash_table (&rcoH, rco->tblSound, rco) * sizeof (uint32_t);
    }
    if (rco->tblObj) {
      header.pObjPtrs = rcowrite_ftell (&rcoH);
      header.lObjPtrs =
	  write_hash_table (&rcoH, rco->tblObj, rco) * sizeof (uint32_t);
    }
    if (rco->tblAnim) {
      header.pAnimPtrs = rcowrite_ftell (&rcoH);
      header.lAnimPtrs =
	  write_hash_table (&rcoH, rco->tblAnim, rco) * sizeof (uint32_t);
    }
    /*
     * #define RCO_WRITERCO_WRITE_PTR_SECT(pd, pl, hp) { \ if(pl) { \ hp =
     * rcowrite_ftell(&rcoH); \ for(i=0; i<pl; i++) { \ if(pd[i]) \
     * rco_fwrite(&rcoH, &(((rRCOEntry*)(pd[i]))->offset), sizeof(uint32_t)); \
     * else { \ uint32_t zero = 0; \ rco_fwrite(&rcoH, &zero, sizeof(uint32_t)); \
     * } \ } \ } \ } //RCO_WRITERCO_WRITE_PTR_SECT(rco->ptrText,
     * rco->numPtrText, header.pTextPtrs);
     * RCO_WRITERCO_WRITE_PTR_SECT(rco->ptrImg, rco->numPtrImg,
     * header.pImgPtrs); RCO_WRITERCO_WRITE_PTR_SECT(rco->ptrModel,
     * rco->numPtrModel, header.pModelPtrs);
     * RCO_WRITERCO_WRITE_PTR_SECT(rco->ptrSound, rco->numPtrSound,
     * header.pSoundPtrs); RCO_WRITERCO_WRITE_PTR_SECT(rco->ptrObj,
     * rco->numPtrObj, header.pObjPtrs);
     * RCO_WRITERCO_WRITE_PTR_SECT(rco->ptrAnim, rco->numPtrAnim,
     * header.pAnimPtrs); */
  }

  {				// write label/event data (and text if
    // applicable)

    // write text (note, old behaviour - newer RCOs have text written in a
    // different location)
    if (!opts.packText && rco->tblText && rco->tblText->numSubentries) {
      rRCOEntry *rcoNode;

      header.pTextData = rcowrite_ftell (&rcoH);
      header.lTextData = rcoH.sizeText;
      for (rcoNode = rco->tblText->firstChild; rcoNode; rcoNode = rcoNode->next) {
	rco_write_text_resource (&rcoH, rcoNode, RCO_DATA_COMPRESSION_NONE,
	    &opts, ((rRCOTextEntry *) (rcoNode->extra))->lang,
	    (rco->tblText->lastChild == rcoNode));
      }
    }
    // write label+event data
    header.pLabelData = rcowrite_ftell (&rcoH);
    if (rco->labelsLen)
      rco_fwrite (&rcoH, rco->labels, rco->labelsLen);
    header.pEventData = rcowrite_ftell (&rcoH);
    if (rco->eventsLen)
      rco_fwrite (&rcoH, rco->events, rco->eventsLen);
    else if (rco->tblObj || rco->tblAnim) {	// weird case: if there's
      // object entries, there will
      // be 4 bytes for events; I'll
      // assume this covers anim as
      // well (although there isn't
      // an RCO with anim that
      // doesn't have objects)
      uint32_t zero = 0;

      rco_fwrite (&rcoH, &zero, sizeof (zero));
      header.lEventData = sizeof (zero);
    }
    // the text pointer is weird in that if there's no text, it's set equal to
    // the label pointer; even weirder, some RCOs have a null pointer (for
    // FW5.00 all except lftv_* RCOs have null pointers for pTextData if
    // there's no text)
    // my theory: if compressing, it will be RCO_NULL_PTR, otherwise it'll =
    // header.pLabelData
    // if(!header.lTextData) header.pTextData = RCO_NULL_PTR;
    // if(!header.lTextData) header.pTextData = header.pLabelData;
    if (!header.lTextData)
      header.pTextData = (opts.packHeader ? RCO_NULL_PTR : header.pLabelData);
  }

  // flush compression stuff here
  HeaderComprInfo ci;

  if (opts.packHeader) {
    uint8_t *bufferOut = NULL;

    ci.lenLongestText = rcoH.longestLangData;
    ci.lenUnpacked = rcoH.tablesSize;
    ci.lenPacked = 0;

    if (opts.packHeader == RCO_DATA_COMPRESSION_ZLIB) {
      uint32_t bound = compressBound (rcoH.tablesSize);

      bufferOut = (uint8_t *) malloc (bound);
      ci.lenPacked =
	  zlib_compress (rcoH.tables, rcoH.tablesSize, bufferOut, bound,
	  opts.zlibLevel, opts.zlibMethod);
    } else if (opts.packHeader == RCO_DATA_COMPRESSION_RLZ) {
      bufferOut = (uint8_t *) malloc (rcoH.tablesSize);
      ci.lenPacked =
	  rlz_compress (rcoH.tables, rcoH.tablesSize, bufferOut,
	  rcoH.tablesSize, opts.rlzMode);
    } else {
      error ("lulwut?");
      exit (1);
    }
    int comprMisalign = ci.lenPacked % 4;
    uint32_t packedLen = ci.lenPacked;

    if (rco->eSwap)
      es_headerComprInfo (&ci);
    filewrite (rcoH.fp, &ci, sizeof (ci));
    filewrite (rcoH.fp, bufferOut, packedLen);
    free (bufferOut);

    if (comprMisalign) {	// 4 byte align
      uint32_t zero = 0;

      filewrite (rcoH.fp, &zero, 4 - comprMisalign);
    }
  }
  // write text if packing header
  if (opts.packText && rco->tblText && rco->tblText->numSubentries) {
    rRCOEntry *rcoNode;

    // header.pTextData = rcowrite_ftell(&rcoH);
    header.pTextData = ftell (rcoH.fp);
    header.lTextData = 0;	// rcoH.sizeText;
    for (rcoNode = rco->tblText->firstChild; rcoNode; rcoNode = rcoNode->next) {
      header.lTextData +=
	  rco_write_text_resource (&rcoH, rcoNode, opts.packHeader, &opts,
	  ((rRCOTextEntry *) (rcoNode->extra))->lang,
	  (rco->tblText->lastChild == rcoNode));
    }
  }
  // write resources
  /* { uint32_t totalPackedLen = 0; if(rco->tblImage) { header.pImgData =
   * rcowrite_ftell(&rcoH); header.lImgData = rcoH.sizeImg; // TOxDO: this
   * model actually won't work - we have to update the offsets of ALL the
   * entries after packing... for(i=0; i<rco->tblImage->numSubentries; i++) {
   * uint32_t packedSize = rco_write_resource(&rcoH,
   * &(rco->tblImage->subentries[i]), RCO_DATA_COMPRESSION_NONE); // TOxDO:
   * change this // TOxDO: update packed size value uint32_t curFpos =
   * rcowrite_ftell(rcoH.fp); totalPackedLen += (packedSize % 4 ?
   * (packedSize/4)*4+4 : packedSize); } header.lImgData = totalPackedLen; }
   * totalPackedLen = 0; if(rco->tblSound) { header.pSoundData =
   * rcowrite_ftell(&rcoH); header.lSoundData = rcoH.sizeSound; for(i=0;
   * i<rco->tblSound->numSubentries; i++) { totalPackedLen +=
   * rco_write_resource(&rcoH, &(rco->tblSound->subentries[i]),
   * RCO_DATA_COMPRESSION_NONE); if(totalPackedLen %4) totalPackedLen +=
   * 4-(totalPackedLen%4); } header.lSoundData = totalPackedLen; } // TOxDO:
   * write model resources } */

  if ((rco->tblImage && rco->tblImage->numSubentries)
      || (rco->tblSound && rco->tblSound->numSubentries)
      || (rco->tblModel && rco->tblModel->numSubentries)) {
    // update data pointers
    uint32_t pos = ftell (rcoH.fp);

    if (rco->tblImage && rco->tblImage->numSubentries) {
      header.pImgData = pos;
      pos += header.lImgData;
    }
    if (rco->tblSound && rco->tblSound->numSubentries) {
      header.pSoundData = pos;
      pos += header.lSoundData;
    }
    if (rco->tblModel && rco->tblModel->numSubentries) {
      header.pModelData = pos;
      pos += header.lModelData;
    }
    // copy contents of fTmp across (uses a simple buffered copy)
    uint32_t len = header.lImgData + header.lSoundData + header.lModelData;
    uint8_t buffer[65536];

    while (len) {
      uint32_t readAmt = (len > 65536 ? 65536 : len);

      fileread (fTmp, buffer, readAmt);
      filewrite (rcoH.fp, buffer, readAmt);
      len -= readAmt;
    }

    fclose (fTmp);		// this deletes our temp file
  }
  // fix header
  if (rco->tblVSMX)
    header.pVSMXTable = rco->tblVSMX->offset;
  if (rco->tblText)
    header.pTextTable = rco->tblText->offset;
  if (rco->tblSound)
    header.pSoundTable = rco->tblSound->offset;
  if (rco->tblModel)
    header.pModelTable = rco->tblModel->offset;
  if (rco->tblImage)
    header.pImgTable = rco->tblImage->offset;
  if (rco->tblFont)
    header.pFontTable = rco->tblFont->offset;
  if (rco->tblObj)
    header.pObjTable = rco->tblObj->offset;
  if (rco->tblAnim)
    header.pAnimTable = rco->tblAnim->offset;

  rewind (rcoH.fp);
  if (rco->eSwap)
    es_rcoHeader (&header);
  filewrite (rcoH.fp, &header, sizeof (header));

  // TODO: fix resource pointers?
  // TODO: tie things up etc??

  fclose (rcoH.fp);

  return TRUE;
}
示例#2
0
void MMapFile::resize(int newsize)
{
  release();

  if (newsize > m_iSize)
  {
#ifdef _WIN32
    if (m_hFileMap)
      CloseHandle(m_hFileMap);

    m_hFileMap = 0;
#endif

    m_iSize = newsize;

#ifdef _WIN32
    if (m_hFile == INVALID_HANDLE_VALUE)
    {
      TCHAR buf[MAX_PATH], buf2[MAX_PATH];

      GetTempPath(MAX_PATH, buf);
      GetTempFileName(buf, _T("nsd"), 0, buf2);

      m_hFile = CreateFile(
        buf2,
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE | FILE_FLAG_SEQUENTIAL_SCAN,
        NULL
      );

      m_bTempHandle = TRUE;
    }

    if (m_hFile != INVALID_HANDLE_VALUE)
    {
      m_hFileMap = CreateFileMapping(
        m_hFile,
        NULL,
        m_bReadOnly ? PAGE_READONLY : PAGE_READWRITE,
        0,
        m_iSize,
        NULL
      );
    }
#else
    if (m_hFile == NULL)
    {
      m_hFile = tmpfile();
      if (m_hFile != NULL)
      {
        m_hFileDesc = fileno(m_hFile);
        m_bTempHandle = TRUE;
      }
    }

    // resize
    if (m_hFileDesc != -1)
    {
      unsigned char c = 0;

      if (lseek(m_hFileDesc, m_iSize, SEEK_SET) != (off_t)-1)
      {
        if (read(m_hFileDesc, &c, 1) != -1)
        {
          if (lseek(m_hFileDesc, m_iSize, SEEK_SET) != (off_t)-1)
          {
            if (write(m_hFileDesc, &c, 1) != -1)
            {
              return; // no errors
            }
          }
        }
      }
    }

    m_hFileDesc = -1; // some error occurred, bail
#endif

#ifdef _WIN32
    if (!m_hFileMap)
#else
    if (m_hFileDesc == -1)
#endif
    {
      extern void quit(); extern int g_display_errors;
      if (g_display_errors)
      {
        PrintColorFmtMsg_ERR(_T("\nInternal compiler error #12345: error creating mmap the size of %d.\n"), m_iSize);
      }
      quit();
    }
  }
}
示例#3
0
static int io_tmpfile (lua_State *L) {
  FILE **pf = newfile(L);
  *pf = tmpfile();
  return (*pf == NULL) ? pushresult(L, 0, NULL) : 1;
}
示例#4
0
int write_energies(EMATRIX *ematrix, char *dir, int verbose)
{
	FILE *fp, *fp2;
    int i, j;
    char fname[MAXCHAR_LINE];
    

    
    /* correction on pairwise interaction */
    for (i=0; i<ematrix->n; i++) {
        char conf1_type, conf2_type;
        if (ematrix->conf[i].uniqID[3] == '+' || ematrix->conf[i].uniqID[3] == '-') conf1_type = 'C'; /* one of "C" or "D" */
        else conf1_type = 'D';

        for (j=i; j<ematrix->n; j++) {
            if (ematrix->conf[j].uniqID[3] == '+' || ematrix->conf[j].uniqID[3] == '-') conf2_type = 'C'; /* one of "C" or "D" */
            else conf2_type = 'D';

            /* in a residue ? */
            if(strncmp(ematrix->conf[i].uniqID,ematrix->conf[j].uniqID, 3) ||
            strncmp(ematrix->conf[i].uniqID+5,ematrix->conf[j].uniqID+5, 6)) { /* not in the same residue */
                if (conf1_type == 'C' && conf2_type == 'C') { /* crg-crg corrected average */
                    /* corrected min */
                    if ((ematrix->pw[i][j].crt * ematrix->pw[i][j].ori < 0 || ematrix->pw[j][i].crt * ematrix->pw[j][i].ori < 0)
                      ||((strchr(ematrix->pw[i][j].mark, '?') && strchr(ematrix->pw[j][i].mark, '?')))) { /* abnormal case, sign flipped or both ? marked */
                       if (fabs(ematrix->pw[i][j].ori)>fabs(ematrix->pw[j][i].ori))
                          ematrix->pw[i][j].ele = ematrix->pw[j][i].ele = ematrix->pw[j][i].ori/1.5;
                       else
                          ematrix->pw[i][j].ele = ematrix->pw[j][i].ele = ematrix->pw[i][j].ori/1.5;
                    }
                    else if (strchr(ematrix->pw[i][j].mark, '?') && !strchr(ematrix->pw[j][i].mark, '?')) {
                       ematrix->pw[i][j].ele = ematrix->pw[j][i].ele = ematrix->pw[j][i].crt;
                    }
                    else if (!strchr(ematrix->pw[i][j].mark, '?') && strchr(ematrix->pw[j][i].mark, '?')) {
                       ematrix->pw[i][j].ele = ematrix->pw[j][i].ele = ematrix->pw[i][j].crt;
                    }
                    else {
                       if (fabs(ematrix->pw[i][j].crt)>fabs(ematrix->pw[j][i].crt))
                          ematrix->pw[i][j].ele = ematrix->pw[j][i].ele = ematrix->pw[j][i].crt;
                       else
                          ematrix->pw[i][j].ele = ematrix->pw[j][i].ele = ematrix->pw[i][j].crt;
                    }
                }

                else if (conf1_type == 'D' && conf2_type == 'D') { /* dip-dip corrected average*/
                    ematrix->pw[i][j].ele = ematrix->pw[j][i].ele = (ematrix->pw[i][j].ori+ematrix->pw[j][i].ori)/2.0;
                }
                else { /* crg-dip */
                    /* when sign flipped or both "?" marked, use uncorrected value divided by 1.5 */
                    if ((ematrix->pw[i][j].crt * ematrix->pw[i][j].ori < 0 || ematrix->pw[j][i].crt * ematrix->pw[j][i].ori < 0)
                      ||((strchr(ematrix->pw[i][j].mark, '?') && strchr(ematrix->pw[j][i].mark, '?')))) {
                       ematrix->pw[i][j].ele = ematrix->pw[j][i].ele = (ematrix->pw[i][j].ori+ematrix->pw[j][i].ori)/2.0/1.5;
                    }
                    else if (strchr(ematrix->pw[i][j].mark, '?') && !strchr(ematrix->pw[j][i].mark, '?')) {
                       ematrix->pw[i][j].ele = ematrix->pw[j][i].ele = ematrix->pw[j][i].crt;
                    }
                    else if (!strchr(ematrix->pw[i][j].mark, '?') && strchr(ematrix->pw[j][i].mark, '?')) {
                       ematrix->pw[i][j].ele = ematrix->pw[j][i].ele = ematrix->pw[i][j].crt;
                    }
                    else {
                       ematrix->pw[i][j].ele = ematrix->pw[j][i].ele = (ematrix->pw[i][j].crt+ematrix->pw[j][i].crt)/2.0;
                    }
                }
            }
            else { /* within a residue */
                ematrix->pw[i][j].ele = ematrix->pw[i][j].vdw = ematrix->pw[j][i].ele = ematrix->pw[j][i].vdw = 0.0;
            }
        }
    }
    
    
    /* write out the matrices */
    fp2 = tmpfile();
    /* The firest line is a two-field record, number of comformers and version number separated by white space */
    fprintf(fp2, "%d %s\n", ematrix->n, VERSION);
    fwrite(ematrix->conf, sizeof(CONF_HEAD), ematrix->n, fp2);
    for (i=0; i<ematrix->n; i++) {
	    if (verbose == 1) {
			printf("writing row %05d\r", i);
		}

        fwrite(ematrix->pw[i], sizeof(PAIRWISE), ematrix->n, fp2);
    }
    fputc(EOF, fp2); rewind(fp2);

    sprintf(fname, "%s/%s", dir, ENERGY_TABLE);
    if (!(fp = fopen(fname, "w"))) {
        printf("   Can not open file %s to write. Abort ...\n", fname);
        return USERERR;
    }

    if (def(fp2, fp, 9) != Z_OK) {
        printf("Compress file %s error\n", fname);
        fclose(fp);
        fclose(fp2);
        return USERERR;
    }
    fclose(fp2); fclose(fp);

    /* write head3.lst */
    sprintf(fname, "%s/%s", dir, FN_CONFLIST3);
    if (!(fp = fopen(fname, "w"))) {
        printf("   Can not open file %s to write. Abort ...\n", fname);
        return USERERR;
    }

   fprintf(fp, "iConf CONFORMER     FL  occ    crg   Em0  pKa0 ne nH    vdw0    vdw1    tors    epol   dsolv   extra    history\n");
   for (i=0; i<ematrix->n; i++) {
         fprintf(fp, "%05d %s %c %4.2f %6.3f %5.0f %5.2f %2d %2d %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %10s%c\n",
                                                                    i+1,
                                                                    ematrix->conf[i].uniqID,
                                                                    'f', 0.00,
                                                                    ematrix->conf[i].netcrg,
                                                                    ematrix->conf[i].Em,
                                                                    ematrix->conf[i].pKa,
                                                                    ematrix->conf[i].e,
                                                                    ematrix->conf[i].H,
                                                                    ematrix->conf[i].E_vdw0,
                                                                    ematrix->conf[i].E_vdw1,
                                                                    ematrix->conf[i].E_tors,
                                                                    ematrix->conf[i].E_epol,
                                                                    ematrix->conf[i].E_dsolv,
                                                                    ematrix->conf[i].E_extra,
                                                                    ematrix->conf[i].history,
                                                                    ematrix->conf[i].on);
   }

   fclose(fp);
   return 0;
}
示例#5
0
int start_stunnel(int stunnel_port, int x11vnc_port, int hport, int x11vnc_hport) {
#ifdef SSLCMDS
	char extra[] = ":/usr/sbin:/usr/local/sbin:/dist/sbin";
	char *path, *p, *exe;
	char *stunnel_path = NULL;
	struct stat verify_buf;
	struct stat crl_buf;
	int status, tmp_pem = 0;

	if (stunnel_pid) {
		stop_stunnel();
	}
	stunnel_pid = 0;

	path = getenv("PATH");
	if (! path) {
		path = strdup(extra+1);
	} else {
		char *pt = path;
		path = (char *) malloc(strlen(path)+strlen(extra)+1);
		if (! path) {
			return 0;
		}
		strcpy(path, pt);
		strcat(path, extra);
	}

	exe = (char *) malloc(strlen(path) + 1 + strlen("stunnel4") + 1);

	p = strtok(path, ":");

	exe[0] = '\0';

	while (p) {
		struct stat sbuf;

		sprintf(exe, "%s/%s", p, "stunnel4");
		if (! stunnel_path && stat(exe, &sbuf) == 0) {
			if (! S_ISDIR(sbuf.st_mode)) {
				stunnel_path = exe;
				break;
			}
		}

		sprintf(exe, "%s/%s", p, "stunnel");
		if (! stunnel_path && stat(exe, &sbuf) == 0) {
			if (! S_ISDIR(sbuf.st_mode)) {
				stunnel_path = exe;
				break;
			}
		}

		p = strtok(NULL, ":");
	}
	if (path) {
		free(path);
	}

	if (getenv("STUNNEL_PROG")) {
		free(exe);
		exe = strdup(getenv("STUNNEL_PROG"));
		stunnel_path = exe;
	}

	if (! stunnel_path) {
		free(exe);
		return 0;
	}
	if (stunnel_path[0] == '\0') {
		free(exe);
		return 0;
	}

	/* stunnel */
	if (no_external_cmds || !cmd_ok("stunnel")) {
		rfbLogEnable(1);
		rfbLog("start_stunnel: cannot run external commands in -nocmds mode:\n");
		rfbLog("   \"%s\"\n", stunnel_path);
		rfbLog("   exiting.\n");
		clean_up_exit(1);
	}

	if (! quiet) {
		rfbLog("\n");
		rfbLog("starting ssl tunnel: %s  %d -> %d\n", stunnel_path,
		    stunnel_port, x11vnc_port);
	}

	if (stunnel_pem && strstr(stunnel_pem, "SAVE") == stunnel_pem) {
		stunnel_pem = get_saved_pem(stunnel_pem, 1);
		if (! stunnel_pem) {
			rfbLog("start_stunnel: could not create or open"
			    " saved PEM.\n");	
			clean_up_exit(1);
		}
	} else if (!stunnel_pem) {
		stunnel_pem = create_tmp_pem(NULL, 0);
		if (! stunnel_pem) {
			rfbLog("start_stunnel: could not create temporary,"
			    " self-signed PEM.\n");	
			clean_up_exit(1);
		}
		tmp_pem = 1;
		if (getenv("X11VNC_SHOW_TMP_PEM")) {
			FILE *in = fopen(stunnel_pem, "r");
			if (in != NULL) {
				char line[128];
				fprintf(stderr, "\n");
				while (fgets(line, 128, in) != NULL) {
					fprintf(stderr, "%s", line);
				}
				fprintf(stderr, "\n");
				fclose(in);
			}
		}
	}

	if (ssl_verify) {
		char *file = get_ssl_verify_file(ssl_verify);
		if (file) {
			ssl_verify = file;
		}
		if (stat(ssl_verify, &verify_buf) != 0) {
			rfbLog("stunnel: %s does not exist.\n", ssl_verify);
			clean_up_exit(1);
		}
	}
	if (ssl_crl) {
		if (stat(ssl_crl, &crl_buf) != 0) {
			rfbLog("stunnel: %s does not exist.\n", ssl_crl);
			clean_up_exit(1);
		}
	}

	stunnel_pid = fork();

	if (stunnel_pid < 0) {
		stunnel_pid = 0;
		free(exe);
		return 0;
	}

	if (stunnel_pid == 0) {
		FILE *in;
		char fd[20];
		int i;
		char *st_if = getenv("STUNNEL_LISTEN");

		if (st_if == NULL) {
			st_if = "";
		} else {
			st_if = (char *) malloc(strlen(st_if) + 2);
			sprintf(st_if, "%s:", getenv("STUNNEL_LISTEN"));
		}


		for (i=3; i<256; i++) {
			close(i);
		}

		if (use_stunnel == 3) {
			char sp[30], xp[30], *a = NULL;
			char *st = stunnel_path;
			char *pm = stunnel_pem;
			char *sv = ssl_verify;

			sprintf(sp, "%d", stunnel_port);
			sprintf(xp, "%d", x11vnc_port);

			if (ssl_verify) {
				if(S_ISDIR(verify_buf.st_mode)) {
					a = "-a";
				} else {
					a = "-A";
				}
			}

			if (ssl_crl) {
				rfbLog("stunnel: stunnel3 does not support CRL. %s\n", ssl_crl);
				clean_up_exit(1);
			}
			
			if (stunnel_pem && ssl_verify) {
				/* XXX double check -v 2 */
				execlp(st, st, "-f", "-d", sp, "-r", xp, "-P",
				    "none", "-p", pm, a, sv, "-v", "2",
				    (char *) NULL);
			} else if (stunnel_pem && !ssl_verify) {
				execlp(st, st, "-f", "-d", sp, "-r", xp, "-P",
				    "none", "-p", pm,
				    (char *) NULL);
			} else if (!stunnel_pem && ssl_verify) {
				execlp(st, st, "-f", "-d", sp, "-r", xp, "-P",
				    "none", a, sv, "-v", "2",
				    (char *) NULL);
			} else {
				execlp(st, st, "-f", "-d", sp, "-r", xp, "-P",
				    "none", (char *) NULL);
			}
			exit(1);
		}

		in = tmpfile();
		if (! in) {
			exit(1);
		}

		fprintf(in, "foreground = yes\n");
		fprintf(in, "pid =\n");
		if (stunnel_pem) {
			fprintf(in, "cert = %s\n", stunnel_pem);
		}
		if (ssl_crl) {
			if(S_ISDIR(crl_buf.st_mode)) {
				fprintf(in, "CRLpath = %s\n", ssl_crl);
			} else {
				fprintf(in, "CRLfile = %s\n", ssl_crl);
			}
		}
		if (ssl_verify) {
			if(S_ISDIR(verify_buf.st_mode)) {
				fprintf(in, "CApath = %s\n", ssl_verify);
			} else {
				fprintf(in, "CAfile = %s\n", ssl_verify);
			}
			fprintf(in, "verify = 2\n");
		}
		fprintf(in, ";debug = 7\n\n");
		fprintf(in, "[x11vnc_stunnel]\n");
		fprintf(in, "accept = %s%d\n", st_if, stunnel_port);
		fprintf(in, "connect = %d\n", x11vnc_port);

		if (hport > 0 && x11vnc_hport > 0) {
			fprintf(in, "\n[x11vnc_http]\n");
			fprintf(in, "accept = %s%d\n", st_if, hport);
			fprintf(in, "connect = %d\n", x11vnc_hport);
		}

		fflush(in);
		rewind(in);

		if (getenv("STUNNEL_DEBUG")) {
			char line[1000];
			fprintf(stderr, "\nstunnel config contents:\n\n");
			while (fgets(line, sizeof(line), in) != NULL) {
				fprintf(stderr, "%s", line);
			}
			fprintf(stderr, "\n");
			rewind(in);
		}
		
		sprintf(fd, "%d", fileno(in));
		execlp(stunnel_path, stunnel_path, "-fd", fd, (char *) NULL);
		exit(1);
	}

	free(exe);
	usleep(750 * 1000);

	waitpid(stunnel_pid, &status, WNOHANG); 

	if (ssl_verify && strstr(ssl_verify, "/sslverify-tmp-load-")) {
		/* temporary file */
		usleep(1000 * 1000);
		unlink(ssl_verify);
	}
	if (tmp_pem) {
		/* temporary cert */
		usleep(1500 * 1000);
		unlink(stunnel_pem);
	}

	if (kill(stunnel_pid, 0) != 0) {
		waitpid(stunnel_pid, &status, WNOHANG); 
		stunnel_pid = 0;
		return 0;
	}

	if (! quiet) {
		rfbLog("stunnel pid is: %d\n", (int) stunnel_pid);
	}

	return 1;
#else
	return 0;
#endif
}
示例#6
0
文件: tmail.c 项目: Distrotech/pine
int main (int argc,char *argv[])
{
  FILE *f = NIL;
  int pid,c,ret = 0;
  unsigned long msglen,status = 0;
  char *s,tmp[MAILTMPLEN];
  uid_t ruid = getuid ();
  struct passwd *pwd;
  openlog ("tmail",LOG_PID,LOG_MAIL);
#include "linkage.c"
				/* make sure have some arguments */
  if (--argc < 1) _exit (fail ("usage: tmail [-D] user[+folder]",EX_USAGE));
				/* process all flags */
  while (argc && (*(s = *++argv)) == '-') {
    argc--;			/* gobble this argument */
    switch (s[1]) {		/* what is this flag? */
    case 'D':			/* debug */
      debug = T;		/* don't fork */
      break;
    case 'd':			/* obsolete flag meaning multiple users */
      break;
    case 'I':			/* inbox specifier */
      if (argc--) inbox = cpystr (*++argv);
      else _exit (fail ("missing argument to -I",EX_USAGE));
      break;
    case 'f':			/* new name for this flag */
    case 'r':			/* flag giving return path */
      if (argc--) sender = cpystr (*++argv);
      else _exit (fail ("missing argument to -r",EX_USAGE));
      break;
    default:			/* anything else */
      _exit (fail ("unknown switch",EX_USAGE));
    }
  }

  if (!argc) ret = fail ("no recipients",EX_USAGE);
  else if (!(f = tmpfile ())) ret = fail ("can't make temp file",EX_TEMPFAIL);
  else {			/* build delivery headers */
    if (sender) fprintf (f,"Return-Path: <%s>\015\012",sender);
				/* start Received line: */
    fprintf (f,"Received: via tmail-%s",version);
				/* not root or daemon? */
    if (ruid && !((pwd = getpwnam ("daemon")) && (ruid == pwd->pw_uid))) {
      pwd = getpwuid (ruid);	/* get unprivileged user's information */
      if (inbox) {
	if (pwd) sprintf (tmp,"user %.80s",pwd->pw_name);
	else sprintf (tmp,"UID %ld",(long) ruid);
	strcat (tmp," is not privileged to use -I");
	_exit (fail (tmp,EX_USAGE));
      }
      fputs (" (invoked by ",f);
      if (pwd) fprintf (f,"user %s",pwd->pw_name);
      else fprintf (f,"UID %ld",(long) ruid);
      fputs (")",f);
    }
				/* write "for" if single recipient */
    if (argc == 1) fprintf (f," for %s",*argv);
    fputs ("; ",f);
    rfc822_date (tmp);
    fputs (tmp,f);
    fputs ("\015\012",f);
				/* copy text from standard input */
    if (!fgets (tmp,MAILTMPLEN-1,stdin) || !(s = strchr (tmp,'\n')) ||
	(s == tmp) || s[1]) _exit (fail ("bad first message line",EX_USAGE));
    if (s[-1] == '\015') {	/* nuke leading "From " line */
      if ((tmp[0] != 'F') || (tmp[1] != 'r') || (tmp[2] != 'o') ||
	  (tmp[3] != 'm') || (tmp[4] != ' ')) fputs (tmp,f);
      while ((c = getchar ()) != EOF) putc (c,f);
    }
    else {
      mm_log ("tmail called with LF-only newlines",WARN);
      if ((tmp[0] != 'F') || (tmp[1] != 'r') || (tmp[2] != 'o') ||
	  (tmp[3] != 'm') || (tmp[4] != ' ')) {
	*s++ = '\015';		/* overwrite NL with CRLF */
	*s++ = '\012';
	*s = '\0';		/* tie off string */
	fputs (tmp,f);		/* write line */
      }
				/* copy text from standard input */
      while ((c = getchar ()) != EOF) {
				/* add CR if needed */
	if (c == '\012') putc ('\015',f);
	putc (c,f);
      }
    }
    msglen = ftell (f);		/* size of message */
    fflush (f);			/* make sure all changes written out */

    if (ferror (f)) ret = fail ("error writing temp file",EX_TEMPFAIL);
    else if (!msglen) ret = fail ("empty message",EX_TEMPFAIL);
				/* single delivery */
    else if (argc == 1) ret = deliver (f,msglen,*argv);
    else do {			/* multiple delivery uses daughter forks */
      if ((pid = fork ()) < 0) ret = fail (strerror (errno),EX_OSERR);
      else if (pid) {		/* mother process */
	grim_pid_reap_status (pid,NIL,(void *) status);
				/* normal termination? */
	if (!ret) ret = (status & 0xff) ? EX_SOFTWARE : (status & 0xff00) >> 8;
      }
				/* daughter process */
      else _exit (deliver (f,msglen,*argv));
    } while (--argc && *argv++);
    mm_dlog (ret ? "error in delivery" : "all recipients delivered");
  }
示例#7
0
文件: htags.c 项目: luchachen/global
/**
 * makehtml: make html files
 *
 *	@param[in]	total	number of files.
 */
static void
makehtml(int total)
{
	GFIND *gp;
	FILE *anchor_stream;
	const char *path;
	int count = 0;

	/*
	 * Create anchor stream for anchor_load().
	 */
	anchor_stream = tmpfile();
#if defined(_WIN32) && !defined(__CYGWIN__)
	/*
	 * tmpfile is created in the root, which user's can't write on Vista+.
	 * Use _tempnam and open it directly.
	 */
	if (anchor_stream == NULL) {
		char *name = _tempnam(tmpdir, "htags");
		anchor_stream = fopen(name, "w+bD");
		free(name);
	}
#endif
	gp = gfind_open(dbpath, NULL, other_files ? GPATH_BOTH : GPATH_SOURCE, 0);
	while ((path = gfind_read(gp)) != NULL) {
		if (gp->type == GPATH_OTHER)
			fputc(' ', anchor_stream);
		fputs(path, anchor_stream);
		fputc('\n', anchor_stream);
	}
	gfind_close(gp);
	/*
	 * Prepare anchor stream for anchor_load().
	 */
	anchor_prepare(anchor_stream);
	/*
	 * For each path in GPATH, convert the path into HTML file.
	 */
	gp = gfind_open(dbpath, NULL, other_files ? GPATH_BOTH : GPATH_SOURCE, 0);
	while ((path = gfind_read(gp)) != NULL) {
		char html[MAXPATHLEN];

		if (gp->type == GPATH_OTHER && !other_files)
			continue;
		/*
		 * load tags belonging to the path.
		 * The path must be start "./".
		 */
		anchor_load(path);
		/*
		 * inform the current path name to lex() function.
		 */
		save_current_path(path);
		count++;
		path += 2;		/* remove './' at the head */
		message(" [%d/%d] converting %s", count, total, path);
		snprintf(html, sizeof(html), "%s/%s/%s.%s", distpath, SRCS, path2fid(path), HTML);
		src2html(path, html, gp->type == GPATH_OTHER);
	}
	gfind_close(gp);
}
示例#8
0
uint8 ArchDrive::open_file(int channel, const uint8 *name, int name_len)
{
	uint8 plain_name[NAMEBUF_LENGTH];
	int plain_name_len;
	int mode = FMODE_READ;
	int type = FTYPE_DEL;
	int rec_len = 0;
	parse_file_name(name, name_len, plain_name, plain_name_len, mode, type, rec_len);

	// Channel 0 is READ, channel 1 is WRITE
	if (channel == 0 || channel == 1) {
		mode = channel ? FMODE_WRITE : FMODE_READ;
		if (type == FTYPE_DEL)
			type = FTYPE_PRG;
	}

	bool writing = (mode == FMODE_WRITE || mode == FMODE_APPEND);

	// Wildcards are only allowed on reading
	if (writing && (strchr((const char *)plain_name, '*') || strchr((const char *)plain_name, '?'))) {
		set_error(ERR_SYNTAX33);
		return ST_OK;
	}

	// Allow only read accesses
	if (writing) {
		set_error(ERR_WRITEPROTECT);
		return ST_OK;
	}

	// Relative files are not supported
	if (type == FTYPE_REL) {
		set_error(ERR_UNIMPLEMENTED);
		return ST_OK;
	}

	// Find file
	int num;
	if (find_first_file(plain_name, plain_name_len, num)) {

		// Open temporary file
		if ((file[channel] = tmpfile()) != NULL) {

			// Write load address (.t64 only)
			if (archive_type == TYPE_T64) {
				fwrite(&file_info[num].sa_lo, 1, 1, file[channel]);
				fwrite(&file_info[num].sa_hi, 1, 1, file[channel]);
			}

			// Copy file contents from archive file to temp file
			uint8 *buf = new uint8[file_info[num].size];
			fseek(the_file, file_info[num].offset, SEEK_SET);
			fread(buf, file_info[num].size, 1, the_file);
			fwrite(buf, file_info[num].size, 1, file[channel]);
			rewind(file[channel]);
			delete[] buf;

			if (mode == FMODE_READ)	// Read and buffer first byte
				read_char[channel] = getc(file[channel]);
		}
	} else
		set_error(ERR_FILENOTFOUND);

	return ST_OK;
}
示例#9
0
uint8 ArchDrive::open_directory(int channel, const uint8 *pattern, int pattern_len)
{
	// Special treatment for "$0"
	if (pattern[0] == '0' && pattern_len == 1) {
		pattern++;
		pattern_len--;
	}

	// Skip everything before the ':' in the pattern
	uint8 *t = (uint8 *)memchr(pattern, ':', pattern_len);
	if (t) {
		t++;
		pattern_len -= t - pattern;
		pattern = t;
	}

	// Create temporary file
	if ((file[channel] = tmpfile()) == NULL)
		return ST_OK;

	// Create directory title
	uint8 buf[] = "\001\004\001\001\0\0\022\042                \042 00 2A";
	for (int i=0; i<16 && dir_title[i]; i++)
		buf[i + 8] = dir_title[i];
	fwrite(buf, 1, 32, file[channel]);

	// Create and write one line for every directory entry
	vector<c64_dir_entry>::const_iterator i, end = file_info.end();
	for (i = file_info.begin(); i != end; i++) {

		// Include only files matching the pattern
		if (pattern_len == 0 || match(pattern, pattern_len, (uint8 *)i->name)) {

			// Clear line with spaces and terminate with null byte
			memset(buf, ' ', 31);
			buf[31] = 0;

			uint8 *p = (uint8 *)buf;
			*p++ = 0x01;	// Dummy line link
			*p++ = 0x01;

			// Calculate size in blocks (254 bytes each)
			int n = (i->size + 254) / 254;
			*p++ = n & 0xff;
			*p++ = (n >> 8) & 0xff;

			p++;
			if (n < 10) p++;	// Less than 10: add one space
			if (n < 100) p++;	// Less than 100: add another space

			// Convert and insert file name
			*p++ = '\"';
			uint8 *q = p;
			for (int j=0; j<16 && i->name[j]; j++)
				*q++ = i->name[j];
			*q++ = '\"';
			p += 18;

			// File type
			switch (i->type) {
				case FTYPE_DEL:
					*p++ = 'D';
					*p++ = 'E';
					*p++ = 'L';
					break;
				case FTYPE_SEQ:
					*p++ = 'S';
					*p++ = 'E';
					*p++ = 'Q';
					break;
				case FTYPE_PRG:
					*p++ = 'P';
					*p++ = 'R';
					*p++ = 'G';
					break;
				case FTYPE_USR:
					*p++ = 'U';
					*p++ = 'S';
					*p++ = 'R';
					break;
				case FTYPE_REL:
					*p++ = 'R';
					*p++ = 'E';
					*p++ = 'L';
					break;
				default:
					*p++ = '?';
					*p++ = '?';
					*p++ = '?';
					break;
			}

			// Write line
			fwrite(buf, 1, 32, file[channel]);
		}
	}
示例#10
0
int main(int argc, char **argv) {
	FILE *input_file = NULL;
	int l_flag = 0, a_flag = 0, v_flag = 0; // output flags

	if(argc > 1) {
		int i;
		for(i = 1; i < argc; i++) {
			// last arg must be the input_file
			if((i+1) == argc) {
				input_file = fopen(argv[i], "r");
				if(!input_file) {
					printf("File %s not found.\n", argv[1]);
					exit(EXIT_FAILURE);
				}
			} else {
				if(argv[i][0] == '-') {
					int j;
					for(j = 1; j < strlen(argv[i]); j++) {
						if(argv[i][j] == 'l') l_flag = 1;
						else if(argv[i][j] == 'a') a_flag = 1;
						else if(argv[i][j] == 'v') v_flag = 1;
						else {
							printf("Unknown option: %s\n", argv[i]);
							exit(EXIT_FAILURE);
						}
					}
				}
			}
		}
	} else {
		printf("Usage: pl0-compiler [-l] [-a] [-v] /path/to/input_file\n");
		exit(EXIT_FAILURE);
	}

	FILE *lexeme_file = tmpfile();

	pl0_lex(input_file, lexeme_file, l_flag);
	fclose(input_file);

	rewind(lexeme_file);

	int error_code = pl0_parse(lexeme_file, a_flag);
	fclose(lexeme_file);

	if(error_code == 0) {
		FILE *code_file = tmpfile();
		print_code(code_file);
		rewind(code_file);

		if(v_flag) {
			printf("Running in PM/0\n");
			printf("===============\n\n");
		}

		error_code = pm0(code_file, v_flag);

		if(v_flag) {
			printf("\n===============\n\n");
		}
		if(!error_code) {
			if(v_flag) {
				printf("Finished without error.\n");
			}
		} else {
			printf("Error number %d.\n", error_code);
		}

		fclose(code_file);
	} else {
		printf("Error number %d, %s\n", error_code, get_parse_error(error_code));
	}

	return EXIT_SUCCESS;
}
示例#11
0
bool importXML::importOne(const QString &pFileName)
{

  QDomDocument doc(pFileName);
  if (!openDomDocument(pFileName, doc))
    return false;

  QString tmpfileName; // only set if we translate the file with XSLT
  if (DEBUG)
      qDebug("importXML::importOne(%s) doctype = %s",
             qPrintable(pFileName), qPrintable(doc.doctype().name()));
  if (doc.doctype().name() != "xtupleimport")
  {
    QString xsltfile;
    q.prepare("SELECT * FROM xsltmap "
              "WHERE ((xsltmap_doctype=:doctype OR xsltmap_doctype='')"
              "   AND (xsltmap_system=:system   OR xsltmap_system=''));");
    q.bindValue(":doctype", doc.doctype().name());
    q.bindValue(":system", doc.doctype().systemId());
    q.exec();
    if (q.first())
    {
      xsltfile = q.value("xsltmap_import").toString();
      //TODO: what if more than one row is found?
    }
    else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return false;
    }
    else
    {
      systemError(this,
                  tr("<p>Could not find a map for doctype '%1' and "
                     "system id '%2'. "
                     "Write an XSLT stylesheet to convert this to valid xtuple"
                     "import XML and add it to the Map of XSLT Import Filters.")
                      .arg(doc.doctype().name()).arg(doc.doctype().systemId()));
      return false;
    }

    // TODO: switch to use ExportHelper::XSLTConvert()?
    QTemporaryFile tmpfile(_defaultXMLDir + QDir::separator() +
                           doc.doctype().name() + "TOxtupleimport");
    tmpfile.setAutoRemove(false);
    if (! tmpfile.open())
    {
      systemError(this, tr("<p>Could not create a temporary file."));
      return false;
    }
    tmpfileName = tmpfile.fileName();
    tmpfile.close();

    if (_metrics->boolean("XSLTLibrary"))
    {
      systemError(this, "XSLT via internal library not yet supported");
      return false;
    }
    else
    {
      QStringList args = _externalCmd.split(" ", QString::SkipEmptyParts);
      QString command = args[0];
      args.removeFirst();
      args.replaceInStrings("%f", pFileName);
      if (QFile::exists(xsltfile))
        args.replaceInStrings("%x", xsltfile);
      else if (QFile::exists(_defaultXSLTDir + QDir::separator() + xsltfile))
        args.replaceInStrings("%x", _defaultXSLTDir + QDir::separator() + xsltfile);
      else
      {
        systemError(this, tr("Cannot find the XSLT file as either %1 or %2")
                          .arg(xsltfile)
                          .arg(_defaultXSLTDir + QDir::separator() + xsltfile));
        return false;
      }

      QProcess xslt(this);
      xslt.setStandardOutputFile(tmpfileName);
      xslt.start(command, args);
      QString commandline = command + " " + args.join(" ");
      QString errOutput;
      /* TODO: make the entire file-processing asynchronous
         this will keep the UI snappy and handle spurious errors
         like the occasional waitForFinished failure if the processing
         runs faster than expected.
       */
      if (! xslt.waitForStarted())
        errOutput = tr("Error starting XSLT Processing: %1\n%2")
                          .arg(commandline)
                          .arg(QString(xslt.readAllStandardError()));
      if (! xslt.waitForFinished())
        errOutput = tr("The XSLT Processor encountered an error: %1\n%2")
                          .arg(commandline)
                          .arg(QString(xslt.readAllStandardError()));
      if (xslt.exitStatus() !=  QProcess::NormalExit)
        errOutput = tr("The XSLT Processor did not exit normally: %1\n%2")
                          .arg(commandline)
                          .arg(QString(xslt.readAllStandardError()));
      if (xslt.exitCode() != 0)
        errOutput = tr("The XSLT Processor returned an error code: %1\nreturned %2\n%3")
                          .arg(commandline)
                          .arg(xslt.exitCode())
                          .arg(QString(xslt.readAllStandardError()));

      if (! errOutput.isEmpty())
      {
        systemError(this, errOutput);
        return false;
      }

      if (! openDomDocument(tmpfileName, doc))
        return false;
    }
  }

  /* xtupleimport format is very straightforward:
      top level element is xtupleimport
        second level elements are all table/view names (default to api schema)
          third level elements are all column names
     and there are no text nodes until third level

     wrap the import of an entire file in a single transaction so
     we can reimport files which have failures. however, if a
     view-level element has the ignore attribute set to true then
     rollback just that view-level element if it generates an error.
  */

  // the silent attribute provides the user the option to turn off 
  // the interactive message for the view-level element


  q.exec("BEGIN;");
  if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return false;
  }

  XSqlQuery rollback;
  rollback.prepare("ROLLBACK;");

  for (QDomElement viewElem = doc.documentElement().firstChildElement();
       ! viewElem.isNull();
       viewElem = viewElem.nextSiblingElement())
  {
    QStringList columnNameList;
    QStringList columnValueList;

    bool ignoreErr = (viewElem.attribute("ignore", "false").isEmpty() ||
                      viewElem.attribute("ignore", "false") == "true");

    bool silent = (viewElem.attribute("silent", "false").isEmpty() ||
                   viewElem.attribute("silent", "false") == "true");

    QString mode = viewElem.attribute("mode", "insert");
    QStringList keyList;
    if (! viewElem.attribute("key").isEmpty())
      keyList = viewElem.attribute("key").split(QRegExp(",\\s*"));

    QString viewName = viewElem.tagName();
    if (viewName.indexOf(".") > 0)
      ; // viewName contains . so accept that it's schema-qualified
    else if (! viewElem.attribute("schema").isEmpty())
      viewName = viewElem.attribute("schema") + "." + viewName;
    else // backwards compatibility - must be in the api schema
      viewName = "api." + viewName;

    // TODO: fix QtXML classes so they read default attribute values from the DTD
    // then remove this code
    if (mode.isEmpty())
      mode = "insert";
    else if (mode == "update" && keyList.isEmpty())
    {
      if (! viewElem.namedItem(viewName + "_number").isNull())
        keyList.append(viewName + "_number");
      else if (! viewElem.namedItem("order_number").isNull())
        keyList.append("order_number");
      else if (! ignoreErr)
      {
        rollback.exec();
        systemError(this, tr("Cannot process %1 element without a key attribute"));
        return false;
      }
      if (! viewElem.namedItem("line_number").isNull())
        keyList.append("line_number");
    }
    // end of code to remove

    QString savepointName = viewName;
    savepointName.remove(".");
    if (ignoreErr)
      q.exec("SAVEPOINT " + savepointName + ";");

    QRegExp apos("\\\\*'");

    for (QDomElement columnElem = viewElem.firstChildElement();
         ! columnElem.isNull();
         columnElem = columnElem.nextSiblingElement())
    {
      QString value = columnElem.attribute("value").isEmpty() ?
                              columnElem.text() : columnElem.attribute("value");

      columnNameList.append(columnElem.tagName());

      if (value.trimmed() == "[NULL]")
        columnValueList.append("NULL");
      else if (value.trimmed().startsWith("SELECT"))
        columnValueList.append("(" + value.trimmed() + ")");
      else if (columnElem.attribute("quote") == "false")
        columnValueList.append(value);
      else
        columnValueList.append("'" + value.replace(apos, "''") + "'");
    }

    QString sql;
    if (mode == "update")
    {
      QStringList whereList;
      for (int i = 0; i < keyList.size(); i++)
        whereList.append("(" + keyList[i] + "=" +
                         columnValueList[columnNameList.indexOf(keyList[i])] + ")");

      for (int i = 0; i < columnNameList.size(); i++)
        columnNameList[i].append("=" + columnValueList[i]);

      sql = "UPDATE " + viewName + " SET " +
            columnNameList.join(", ") +
            " WHERE (" + whereList.join(" AND ") + ");";
    }
    else if (mode == "insert")
      sql = "INSERT INTO " + viewName + " (" +
            columnNameList.join(", ") +
            " ) SELECT " +
            columnValueList.join(", ") + ";" ;
    else
    {
      if (ignoreErr)
        q.exec("ROLLBACK TO SAVEPOINT " + savepointName + ";");
      else
      {
        rollback.exec();
        systemError(this, tr("Could not process %1: invalid mode %2")
                            .arg(viewElem.tagName()).arg(mode));
        return false;
      }
    }

    if (DEBUG) qDebug("About to run this: %s", qPrintable(sql));
    q.exec(sql);
    if (q.lastError().type() != QSqlError::NoError)
    {
      if (ignoreErr)
      {
        QString warning = q.lastError().databaseText();
        q.exec("ROLLBACK TO SAVEPOINT " + savepointName + ";");
        if (! silent)
        {
          QMessageBox::warning(this, tr("Ignoring Error"),
                             tr("Ignoring database error while importing %1:\n\n%2")
                              .arg(viewElem.tagName())
                              .arg(warning));
        }                  
      }
      else
      {
        rollback.exec();
        systemError(this, tr("Error importing %1 %2\n\n").arg(pFileName).arg(tmpfileName) + q.lastError().databaseText(), __FILE__, __LINE__);
        return false;
      }
    }
    else if (ignoreErr)
      q.exec("RELEASE SAVEPOINT " + savepointName + ";");
  }

  q.exec("COMMIT;");
  if (q.lastError().type() != QSqlError::NoError)
  {
    rollback.exec();
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return false;
  }

  QFile file(pFileName);
  if (_metrics->value("XMLSuccessTreatment") == "Delete")
  {
    if (! file.remove())
    {
      systemError(this, tr("Could not remove %1 after successful processing (%2).")
                        .arg(pFileName).arg(file.error()));
      return false;
    }
  }
  else if (_metrics->value("XMLSuccessTreatment") == "Rename")
  {
    QString suffix = _metrics->value("XMLSuccessSuffix");
    if (suffix.isEmpty())
      suffix = ".done";

    QString newname = pFileName + suffix;
    for (int i = 0; QFile::exists(newname) ; i++)
      newname = pFileName + suffix + "." + QString::number(i);

    if (! file.rename(newname))
    {
      systemError(this, tr("Could not rename %1 to %2 after successful processing (%3).")
                        .arg(pFileName).arg(file.error()));
      return false;
    }
  }
  else if (_metrics->value("XMLSuccessTreatment") == "Move")
  {
    QString donedirName = _metrics->value("XMLSuccessDir");
    if (donedirName.isEmpty())
      donedirName = "done";
    if (QDir::isRelativePath(donedirName))
      donedirName = _defaultXMLDir + QDir::separator() + donedirName;

    QDir donedir(donedirName);
    if (! donedir.exists())
      donedir.mkpath(donedirName);

    QString newname = donedirName + QDir::separator() + QFileInfo(file).fileName(); 
    if (QFile::exists(newname))
      newname = newname + QDate::currentDate().toString(".yyyy.MM.dd");
    if (QFile::exists(newname))
      newname = newname + QDateTime::currentDateTime().toString(".hh.mm");
    if (QFile::exists(newname))
      newname = newname + QDateTime::currentDateTime().toString(".ss");

    if (! file.rename(newname))
    {
      systemError(this, tr("<p>Could not move %1 to %2 after successful processing (%3).")
                        .arg(pFileName).arg(newname).arg(file.error()));
      return false;
    }
  }

  // else if (_metrics->value("XMLSuccessTreatment") == "None") {}

  return true;
}
示例#12
0
文件: stdio.c 项目: 12019/picoC
void StdioTmpfile(struct ParseState *Parser, struct Value *ReturnValue, struct Value **Param, int NumArgs) 
{
    ReturnValue->Val->Pointer = tmpfile();
}
/**
 * @brief Writes decompressed text to file.
 * @details write_to_file receives a pointer to a vector of words, a filename, and the number of words. It writes the content of the string vector to a file. It returns -1 if there was an error and 0 if the operation was succesful. If the file received doesn't have a .palz extension, it will be replaced. Otherwise, a new file, with the same name but no .palz extension, will be created.
 * 
 * @param words Pointer to data which will be saved in the file.
 * @param filename Name of the original (compressed) file.
 * @param int Number of words in the dictionary.
 * @return Returns 0 on success.
 */
int write_to_file (char** words, char *filename, FILE* compressed, unsigned int numberOfWords, int function) {
	
	FILE *newDoc = tmpfile();
	unsigned int code = 0;

	//Decompress
	int bytes = bytes_for_int(numberOfWords+15);
	unsigned int prev_code = 0;
	while (running && fread(&code, bytes , 1, compressed)>0) {

		if(code > numberOfWords+14) {
			fprintf(stderr, "Failed: %s is corrupted\n", filename);
			if(function ==1) {
				exit(1);
			} else {
				return 0;
			}
		}
		//detect repetitions
		if (code == 0 ) {
			//check if prev code exists and is separator
			//read next line
			fread(&code, bytes , 1, compressed);
			while (code != 0) {
				fputs (words[prev_code], newDoc);
				code--;
				}
				
			}//code is not a repetition
			else {
				fputs (words[code], newDoc);
				prev_code = code;
			}
	}

	if (!feof(compressed)){
		fprintf(stderr, "fread() on %s failed.\n", filename);
	}


	//Searches and removes .palz extension if it exists
	char *ptr = NULL;
	ptr = strrchr(filename, '.');
	if (ptr != NULL && strcasecmp(ptr, ".palz") == 0 && running == 1)
	{
		*ptr = 0; 
	}

	//Write to file
	FILE *outFile = NULL;
	rewind(newDoc);
	outFile = fopen(filename, "w");

	//Copy from the temporary file to the permanent file
	char buffer[8096];
	int n;
	while( (n=fread(buffer, 1, 8096, newDoc)) > 0) {
	 	fwrite(buffer, 1, n, outFile);
	}
	fflush(outFile);
	fclose(newDoc);


	//Return the compression ratio
	float outFileSize;
	float compressedSize;
	compressedSize = ftell(compressed);
	outFileSize = ftell(outFile);
	printf("Compression ratio: %s %4.2f%%\n", filename, compression_ratio(compressedSize, outFileSize));

	if ((fclose(outFile) != 0) || ((fclose(compressed) != 0) && (running == 1))) {
		printf("fclose() failed.\n");
		exit(1);
	}
	
	return 0; //success
}
示例#14
0
int main(int argc,char *argv[])
{
    signed int i;
    if (argc<3) 
		{
		cry_out("Failed","not enough args",1);
		return 1;
		};
    FILE* fp[argc-1];
;
    if ((fp[argc-2] = fopen(argv[argc-1],"w"))!=NULL) {}
    else 
		{
		cry_out("Failed to create file",argv[argc-1],1);
		code=2;
		return code;
		}
;
    FILE* tmp_store[3];
    long int size[3];
    long int j;
    for (j=0;j<3;j++) 
		{
		size[j]=0;
		}
;

    for (j=0;j<3;j++)
        {
        if ((tmp_store[j] =tmpfile())!=NULL) {}
        else {cry_out("Failed to create tempfile","tempfile",1);code=4;goto finish_1;}
        }
;
    for (i=0;i<argc-2;i++)
		{
		fp[i] = NULL;
		if ((fp[i] = fopen(argv[i+1],"r"))!=NULL) 
			{
			unsigned int* w_buf;
			if ((w_buf =(unsigned int*)malloc(filelength(fileno(fp[i]))*sizeof(int)))!=NULL)
				{
				size[0] = munch(fp[i],fp[argc-2],argv[i+1],w_buf);
				long int j;
				for (j=size[0]-1;j>0;j--)
					{
					long int k;
					for (k=0;k<j;k++)
						{
						if (w_buf[k]>w_buf[k+1])
							{
							unsigned int temp = w_buf[k];
							w_buf[k] = w_buf[k+1];
							w_buf[k+1] = temp;
							}			
						}
					}
				for (j=0;j<size[0];j++)
				{fprintf(tmp_store[0],"%d ",w_buf[j]);}
				fseek(tmp_store[0],0,SEEK_SET);
				fseek(tmp_store[1],0,SEEK_SET);
				fseek(tmp_store[2],0,SEEK_SET);
;
				long int a = size[0]-1;
				long int b = size[1]-1;
				unsigned int _a = 0;
				fscanf(tmp_store[0],"%d",&_a);
				unsigned int _b =0;
				fscanf(tmp_store[1],"%d",&_b);
				while ((a>=0)&&(b>=0))
					{
					unsigned int _c;
					if (_a>_b)
						{
						_c=_b;
						fscanf(tmp_store[1],"%d",&_b);
						--b;
						}
					else
						{
						_c=_a;
						fscanf(tmp_store[0],"%d",&_a);
						--a;
						}
					fprintf(tmp_store[2],"%d ",_c);
					}
				while (a>=0)
					{
					fprintf(tmp_store[2],"%d ",_a);
					fscanf(tmp_store[0],"%d",&_a);
					--a;
					}
				while (b>=0)
					{
					fprintf(tmp_store[2],"%d ",_b);
					fscanf(tmp_store[1],"%d",&_b);
					--b;
					}
					;
					free(w_buf);
					FILE* swap = tmp_store[1];
					tmp_store[1] = tmp_store[2];
					tmp_store[2] = swap;
					size[1]+=size[0];
					size[0]=size[2]=0;
					if (((tmp_store[0]=tmpfile())!=NULL)&&((tmp_store[2]=tmpfile())!=NULL)) {}
					else 
						{
						cry_out("Failed to create tempfile","tempfile",1);
						code=4;
						goto finish_1;
						}
					}
				else
					{
					cry_out("Out of memory","Out of memory",1);
					code=5;
					goto finish_1;
					}
				}
            else {cry_out("Failed to open file",argv[i+1],1);code=3;goto finish_1;}
		}
;
	fseek(tmp_store[1],0,SEEK_SET);
	for (j=0;j<size[1];j++)
		{
		unsigned int a;
		fscanf(tmp_store[1],"%d",&a);
		fprintf(fp[argc-2],"%d ",a);
		}
;
finish_1:
	for (;i>=0;i--)
		{
		if (fp[i]!=NULL) {fclose(fp[i]);}
		}
	fclose(fp[argc-2]);
	rmtmp();
	return code;
}
示例#15
0
// Tests that we can only have a consistent and correct fpos_t when using
// f*pos functions (i.e. fpos doesn't get inside a multi byte character).
TEST(STDIO_TEST, consistent_fpos_t) {
  ASSERT_STREQ("C.UTF-8", setlocale(LC_CTYPE, "C.UTF-8"));
  uselocale(LC_GLOBAL_LOCALE);

  FILE* fp = tmpfile();
  ASSERT_TRUE(fp != NULL);

  wchar_t mb_one_bytes = L'h';
  wchar_t mb_two_bytes = 0x00a2;
  wchar_t mb_three_bytes = 0x20ac;
  wchar_t mb_four_bytes = 0x24b62;

  // Write to file.
  ASSERT_EQ(mb_one_bytes, static_cast<wchar_t>(fputwc(mb_one_bytes, fp)));
  ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fputwc(mb_two_bytes, fp)));
  ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fputwc(mb_three_bytes, fp)));
  ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fputwc(mb_four_bytes, fp)));

  rewind(fp);

  // Record each character position.
  fpos_t pos1;
  fpos_t pos2;
  fpos_t pos3;
  fpos_t pos4;
  fpos_t pos5;
  EXPECT_EQ(0, fgetpos(fp, &pos1));
  ASSERT_EQ(mb_one_bytes, static_cast<wchar_t>(fgetwc(fp)));
  EXPECT_EQ(0, fgetpos(fp, &pos2));
  ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fgetwc(fp)));
  EXPECT_EQ(0, fgetpos(fp, &pos3));
  ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fgetwc(fp)));
  EXPECT_EQ(0, fgetpos(fp, &pos4));
  ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fgetwc(fp)));
  EXPECT_EQ(0, fgetpos(fp, &pos5));

#if defined(__BIONIC__)
  // Bionic's fpos_t is just an alias for off_t. This is inherited from OpenBSD
  // upstream. Glibc differs by storing the mbstate_t inside its fpos_t. In
  // Bionic (and upstream OpenBSD) the mbstate_t is stored inside the FILE
  // structure.
  ASSERT_EQ(0, static_cast<off_t>(pos1));
  ASSERT_EQ(1, static_cast<off_t>(pos2));
  ASSERT_EQ(3, static_cast<off_t>(pos3));
  ASSERT_EQ(6, static_cast<off_t>(pos4));
  ASSERT_EQ(10, static_cast<off_t>(pos5));
#endif

  // Exercise back and forth movements of the position.
  ASSERT_EQ(0, fsetpos(fp, &pos2));
  ASSERT_EQ(mb_two_bytes, static_cast<wchar_t>(fgetwc(fp)));
  ASSERT_EQ(0, fsetpos(fp, &pos1));
  ASSERT_EQ(mb_one_bytes, static_cast<wchar_t>(fgetwc(fp)));
  ASSERT_EQ(0, fsetpos(fp, &pos4));
  ASSERT_EQ(mb_four_bytes, static_cast<wchar_t>(fgetwc(fp)));
  ASSERT_EQ(0, fsetpos(fp, &pos3));
  ASSERT_EQ(mb_three_bytes, static_cast<wchar_t>(fgetwc(fp)));
  ASSERT_EQ(0, fsetpos(fp, &pos5));
  ASSERT_EQ(WEOF, fgetwc(fp));

  fclose(fp);
}
示例#16
0
static int io_tmpfile (lua_State *L) {
  LStream *p = newfile(L);
  p->f = tmpfile();
  return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
}
int main(int argc, char *argv[]) {
    FILE *pipe;
    int args = 0;
    char buffer[256] = { 0 };
    char url_buffer[4096] = { 0 };
    char encoded_url_buffer[4096] = { 0 };
    conf_t conf = { { 0 }, { 0 }, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };

    CURL *curl;
    CURLcode res;

    // check if debug is ON
    if(argc > 1) {
        if(strcmp(argv[1], "--debug") == 0) {
            DEBUG = 1;
        }
    }

    // get database configuration
    if(read_config(&conf)) {
        return 1;
    }

    // format beginning of URL
    strcat(encoded_url_buffer, conf.url);
    strcat(encoded_url_buffer, "?");

    if(DEBUG) {
        printf("System Info:\n\n");
    }

    if(conf.cpu_cores) {
        pipe = popen("cat /proc/cpuinfo | grep processor | wc -l", "r");
        fgets(buffer, 256, pipe);
        buffer[strlen(buffer) - 1] = 0;
        strcat(url_buffer, "cpu_cores=");
        strcat(url_buffer, buffer);
        args = 1;
        if(DEBUG) printf("cpu_cores = %s\n", buffer);
        fclose(pipe);
    }

    if(conf.cpu_load) {
        // save top output to tmp file
        pipe = popen("top -n 2 > /tmp/mor_top_tmp.txt", "r");

        // wait for 2 iterations to complete
        sleep(5);

        // read tmp file
        pipe = popen("cat /tmp/mor_top_tmp.txt | grep 'Cpu(s)' | tail -n+2 | sed 's/.*, *\\([0-9.]*\\)%\\id.*/\\1/' | awk '{print  100 - $5}'", "r");
        fgets(buffer, 256, pipe);
        buffer[strlen(buffer) - 1] = 0;
        if(args) strcat(url_buffer, "&");
        strcat(url_buffer, "cpu_load=");
        strcat(url_buffer, buffer);
        args = 1;
        if(DEBUG) printf("cpu_load = %s\n", buffer);
        fclose(pipe);

        // remove tpm file
        pipe = popen("rm -fr /tmp/mor_top_tmp.txt", "r");
        fclose(pipe);
    }

    if(conf.ram_total || conf.ram_free || conf.ram_used || conf.ram_buffers) {
        char var1[256];
        char var2[256];
        char var3[256];
        char var4[256];
        pipe = popen("free -k | grep -Po '\\d+' | head -n 5", "r");
        fscanf(pipe, "%s %s %s %s %s", var1, var2, var3, var4, var4);
        if(conf.ram_total) {
            if(args) strcat(url_buffer, "&");
            strcat(url_buffer, "ram_total=");
            strcat(url_buffer, var1);
            args = 1;
            if(DEBUG) printf("ram_total = %s\n", var1);
        }
        if(conf.ram_used) {
            if(args) strcat(url_buffer, "&");
            strcat(url_buffer, "ram_used=");
            strcat(url_buffer, var2);
            args = 1;
            if(DEBUG) printf("ram_used = %s\n", var2);
        }
        if(conf.ram_free) {
            if(args) strcat(url_buffer, "&");
            strcat(url_buffer, "ram_free=");
            strcat(url_buffer, var3);
            args = 1;
            if(DEBUG) printf("ram_free = %s\n", var3);
        }
        if(conf.ram_buffers) {
            if(args) strcat(url_buffer, "&");
            strcat(url_buffer, "ram_buffers=");
            strcat(url_buffer, var4);
            args = 1;
            if(DEBUG) printf("ram_buffers = %s\n", var4);
        }
        fclose(pipe);
    }

    if(conf.mysql) {
        pipe = popen("service mysqld status | grep -o 'running'", "r");;
        fgets(buffer, 256, pipe);
        buffer[strlen(buffer) - 1] = 0;
        if(args) strcat(url_buffer, "&");
        strcat(url_buffer, "mysql=");
        if(strcmp(buffer, "running") == 0) {
            strcat(url_buffer, "1");
            if(DEBUG) printf("mysql = 1\n");
        } else {
            strcat(url_buffer, "0");
            if(DEBUG) printf("mysql = 0\n");
        }
        args = 1;
        fclose(pipe);
    }

    if(conf.httpd) {
        pipe = popen("service httpd status | grep -o 'running'", "r");;
        fgets(buffer, 256, pipe);
        buffer[strlen(buffer) - 1] = 0;
        if(args) strcat(url_buffer, "&");
        strcat(url_buffer, "httpd=");
        if(strcmp(buffer, "running") == 0) {
            strcat(url_buffer, "1");
            if(DEBUG) printf("httpd = 1\n");
        } else {
            strcat(url_buffer, "0");
            if(DEBUG) printf("httpd = 0\n");
        }
        args = 1;
        fclose(pipe);
    }

    if(conf.asterisk) {
        pipe = popen("service asterisk status | grep -o 'running'", "r");;
        fgets(buffer, 256, pipe);
        buffer[strlen(buffer) - 1] = 0;
        if(args) strcat(url_buffer, "&");
        strcat(url_buffer, "asterisk=");
        if(strcmp(buffer, "running") == 0) {
            strcat(url_buffer, "1");
            if(DEBUG) printf("asterisk = 1\n");
        } else {
            strcat(url_buffer, "0");
            if(DEBUG) printf("asterisk = 0\n");
        }
        args = 1;
        fclose(pipe);
    }

    if(conf.hdd) {
        char pipe_buffer[256] = { 0 };

        sprintf(pipe_buffer, "df -h %s | grep -Po '[0-9]+%%' | sed 's|%%||'", conf.file_system);

        pipe = popen(pipe_buffer, "r");

        fgets(buffer, 256, pipe);
        buffer[strlen(buffer) - 1] = 0;
        if(args) strcat(url_buffer, "&");
        strcat(url_buffer, "hdd=");
        strcat(url_buffer, buffer);
        if(DEBUG) printf("hdd = %s\n", buffer);
        args = 1;
        fclose(pipe);
    }

    if(args) {
        encode_url(url_buffer, encoded_url_buffer);

        if(DEBUG) {
            printf("\nHTTP Request:\n\n");
            printf("%s\n\n", encoded_url_buffer);
        } else {
            FILE *curl_resp = tmpfile();

            curl_global_init(CURL_GLOBAL_ALL);
            curl = curl_easy_init();
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_resp);

            if(curl) {
                curl_easy_setopt(curl, CURLOPT_URL, encoded_url_buffer);
                res = curl_easy_perform(curl);
                if(res != CURLE_OK) {
                    fprintf(stderr, "cURL error %d\n", res);
                }
            } else {
                fprintf(stderr, "Cannot initiate cURL\n");
                return 1;
            }

            curl_easy_cleanup(curl);
            curl_global_cleanup();

            fclose(curl_resp);
        }
    }

    return 0;
}
示例#18
0
int main (int argc, char **argv)
{
    LIBMTP_raw_device_t * rawdevices;
    int numrawdevices;
    LIBMTP_error_number_t err;
    int i;

    int opt;
    extern int optind;
    extern char *optarg;

    while ((opt = getopt(argc, argv, "d")) != -1 ) {
        switch (opt) {
        case 'd':
            LIBMTP_Set_Debug(LIBMTP_DEBUG_PTP | LIBMTP_DEBUG_DATA);
            break;
        }
    }

    argc -= optind;
    argv += optind;

    LIBMTP_Init();

    fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n");

    fprintf(stdout, "Listing raw device(s)\n");
    err = LIBMTP_Detect_Raw_Devices(&rawdevices, &numrawdevices);
    switch(err) {
    case LIBMTP_ERROR_NO_DEVICE_ATTACHED:
        fprintf(stdout, "   No raw devices found.\n");
        return 0;
    case LIBMTP_ERROR_CONNECTING:
        fprintf(stderr, "Detect: There has been an error connecting. Exiting\n");
        return 1;
    case LIBMTP_ERROR_MEMORY_ALLOCATION:
        fprintf(stderr, "Detect: Encountered a Memory Allocation Error. Exiting\n");
        return 1;
    case LIBMTP_ERROR_NONE:
    {
        int i;

        fprintf(stdout, "   Found %d device(s):\n", numrawdevices);
        for (i = 0; i < numrawdevices; i++) {
            if (rawdevices[i].device_entry.vendor != NULL ||
                    rawdevices[i].device_entry.product != NULL) {
                fprintf(stdout, "   %s: %s (%04x:%04x) @ bus %d, dev %d\n",
                        rawdevices[i].device_entry.vendor,
                        rawdevices[i].device_entry.product,
                        rawdevices[i].device_entry.vendor_id,
                        rawdevices[i].device_entry.product_id,
                        rawdevices[i].bus_location,
                        rawdevices[i].devnum);
            } else {
                fprintf(stdout, "   %04x:%04x @ bus %d, dev %d\n",
                        rawdevices[i].device_entry.vendor_id,
                        rawdevices[i].device_entry.product_id,
                        rawdevices[i].bus_location,
                        rawdevices[i].devnum);
            }
        }
    }
    break;
    case LIBMTP_ERROR_GENERAL:
    default:
        fprintf(stderr, "Unknown connection error.\n");
        return 1;
    }

    /* Iterate over connected MTP devices */
    fprintf(stdout, "Attempting to connect device(s)\n");
    for (i = 0; i < numrawdevices; i++) {
        LIBMTP_mtpdevice_t *device;
        LIBMTP_devicestorage_t *storage;
        char *friendlyname;
        char *syncpartner;
        char *sectime;
        char *devcert;
        uint16_t *filetypes;
        uint16_t filetypes_len;
        uint8_t maxbattlevel;
        uint8_t currbattlevel;
        int ret;

        device = LIBMTP_Open_Raw_Device_Uncached(&rawdevices[i]);
        if (device == NULL) {
            fprintf(stderr, "Unable to open raw device %d\n", i);
            continue;
        }

        LIBMTP_Dump_Errorstack(device);
        LIBMTP_Clear_Errorstack(device);
        LIBMTP_Dump_Device_Info(device);

        printf("MTP-specific device properties:\n");
        // The friendly name
        friendlyname = LIBMTP_Get_Friendlyname(device);
        if (friendlyname == NULL) {
            fprintf(stdout, "   Friendly name: (NULL)\n");
        } else {
            fprintf(stdout, "   Friendly name: %s\n", friendlyname);
            free(friendlyname);
        }
        syncpartner = LIBMTP_Get_Syncpartner(device);
        if (syncpartner == NULL) {
            fprintf(stdout, "   Synchronization partner: (NULL)\n");
        } else {
            fprintf(stdout, "   Synchronization partner: %s\n", syncpartner);
            free(syncpartner);
        }

        // Some battery info
        ret = LIBMTP_Get_Batterylevel(device, &maxbattlevel, &currbattlevel);
        if (ret == 0) {
            fprintf(stdout, "   Battery level %d of %d (%d%%)\n",currbattlevel, maxbattlevel,
                    (int) ((float) currbattlevel/ (float) maxbattlevel * 100.0));
        } else {
            // Silently ignore. Some devices does not support getting the
            // battery level.
            LIBMTP_Clear_Errorstack(device);
        }

        ret = LIBMTP_Get_Supported_Filetypes(device, &filetypes, &filetypes_len);
        if (ret == 0) {
            uint16_t i;

            printf("libmtp supported (playable) filetypes:\n");
            for (i = 0; i < filetypes_len; i++) {
                fprintf(stdout, "   %s\n", LIBMTP_Get_Filetype_Description(filetypes[i]));
            }
        } else {
            LIBMTP_Dump_Errorstack(device);
            LIBMTP_Clear_Errorstack(device);
        }

        // Secure time XML fragment
        ret = LIBMTP_Get_Secure_Time(device, &sectime);
        if (ret == 0 && sectime != NULL) {
            fprintf(stdout, "\nSecure Time:\n%s\n", sectime);
            free(sectime);
        } else {
            // Silently ignore - there may be devices not supporting secure time.
            LIBMTP_Clear_Errorstack(device);
        }

        // Device certificate XML fragment
        if (rawdevices[i].device_entry.vendor_id == 0x041e) {
            /*
             * This code is currently disabled except for vendors we
             * know does support it: all devices say that
             * they support getting a device certificate but a lot of
             * them obviously doesn't, instead they crash when you try
             * to obtain it.
             */
            ret = LIBMTP_Get_Device_Certificate(device, &devcert);
            if (ret == 0 && devcert != NULL) {
                fprintf(stdout, "\nDevice Certificate:\n%s\n", devcert);
                free(devcert);
            } else {
                fprintf(stdout, "Unable to acquire device certificate, perhaps this device "
                        "does not support this\n");
                LIBMTP_Dump_Errorstack(device);
                LIBMTP_Clear_Errorstack(device);
            }
        }

        /* Try to get Media player device info XML file... */
        /* Loop over storages */
        for (storage = device->storage; storage != 0; storage = storage->next) {
            LIBMTP_file_t *files;

            /* Get file listing for the root directory, no other dirs */
            files = LIBMTP_Get_Files_And_Folders(device,
                                                 storage->id,
                                                 0);

            if (files != NULL) {
                LIBMTP_file_t *file, *tmp;
                file = files;
                while (file != NULL) {
                    if (!strcmp(file->filename, "WMPInfo.xml") ||
                            !strcmp(file->filename, "WMPinfo.xml") ||
                            !strcmp(file->filename, "default-capabilities.xml")) {
                        if (file->item_id != 0) {
                            /* Dump this file */
                            FILE *xmltmp = tmpfile();
                            int tmpfiledescriptor = fileno(xmltmp);

                            if (tmpfiledescriptor != -1) {
                                int ret = LIBMTP_Get_Track_To_File_Descriptor(device,
                                          file->item_id,
                                          tmpfiledescriptor,
                                          NULL,
                                          NULL);
                                if (ret == 0) {
                                    uint8_t *buf = NULL;
                                    uint32_t readbytes;

                                    buf = malloc(XML_BUFSIZE);
                                    if (buf == NULL) {
                                        printf("Could not allocate %08x bytes...\n", XML_BUFSIZE);
                                        LIBMTP_Dump_Errorstack(device);
                                        LIBMTP_Clear_Errorstack(device);
                                        free(rawdevices);
                                        return 1;
                                    }

                                    lseek(tmpfiledescriptor, 0, SEEK_SET);
                                    readbytes = read(tmpfiledescriptor, (void*) buf, XML_BUFSIZE);

                                    if (readbytes >= 2 && readbytes < XML_BUFSIZE) {
                                        fprintf(stdout, "\n%s file contents:\n", file->filename);
                                        dump_xml_fragment(buf, readbytes);
                                    } else {
                                        perror("Unable to read file");
                                        LIBMTP_Dump_Errorstack(device);
                                        LIBMTP_Clear_Errorstack(device);
                                    }
                                    free(buf);
                                } else {
                                    LIBMTP_Dump_Errorstack(device);
                                    LIBMTP_Clear_Errorstack(device);
                                }
                                fclose(xmltmp);
                            }
                        }
                    }
                    tmp = file;
                    file = file->next;
                    LIBMTP_destroy_file_t(tmp);
                }
            }
        }
        LIBMTP_Release_Device(device);
    } /* End For Loop */

    free(rawdevices);

    printf("OK.\n");

    return 0;
}
示例#19
0
文件: ffopen.c 项目: erget/wgrib2
FILE *ffopen(const char *filename, const char *mode)
{
    struct opened_file *ptr;
    struct stat stat_buf;  /* test for pipes */
    int is_read_file, i;
    const char *p;

    /* see if is a read/write file */
    is_read_file = 0;
    p = mode;
    while (*p) {
	if (*p++ == 'r') is_read_file = 1;
    }

    if (strcmp(filename,"-") == 0) {
	if (is_read_file) return stdin;
	flush_mode = 1;
	return stdout;
    }

    if (strncmp(filename,"@mem:",5) == 0) {
	fatal_error("option does not suport memory files %s", filename);
    }

    /* see if file has already been opened */
	
    ptr = opened_file_start;
    while (ptr != NULL) {
	if (strcmp(filename,ptr->name) == 0) {
	    if (ptr->usage_count == 0) {			/* reuse of opened file */
		if (is_read_file && !ptr->is_read_file) {	/* was write, now read */
		     i = fflush(ptr->handle);
		     if (i) fprintf(stderr,"WARNING: wgrib2 could not flush %s in write->read\n", ptr->name);
                     fseek(ptr->handle, 0L, SEEK_SET);		/* rewind file */
		}
		ptr->is_read_file = is_read_file;
	    }
	    if (is_read_file != ptr->is_read_file)  {
		fatal_error("ffopen: file can only read or write not both: %s", ptr->name);
	    }
	    (ptr->usage_count)++;
	    return ptr->handle;
	}
	ptr = ptr->next;
    }

    ptr = (struct opened_file *) malloc( sizeof(struct opened_file) );
    if (ptr == NULL) fatal_error("ffopen: memory allocation problem (%s)", filename);
    ptr->name = (char *) malloc(strlen(filename) + 1);
    if (ptr->name == NULL) fatal_error("ffopen: memory allocation problem (%s)", filename);

    strncpy(ptr->name, filename, strlen(filename)+1);
    ptr->is_read_file = is_read_file;
    ptr->usage_count = 1;
    ptr->do_not_close_flag = 1;		// default is not to close file file

    /* check if filename is @tmp:XXX or just XXX */
    if (strlen(filename) > 5 && strncmp(filename, "@tmp:", 5) == 0) {
	if (is_read_file) {
	    /* remove ptr */
	    free(ptr->name);
	    free(ptr);
	    fatal_error("ffopen: creating temporary file for read is not a good idea (%s)", filename);
	}
        ptr->handle = tmpfile();	/* ISO C to generate temporary file */
        if (ptr->handle == NULL) {
	    /* remove ptr */
	    free(ptr->name);
	    free(ptr);
	    fatal_error("ffopen: could not open tmpfile %s", filename);
	}
        /* add ptr to linked list */
        ptr->next = opened_file_start;
        opened_file_start = ptr;
        return ptr->handle;
    }

    /* disk file or pipe */
    ptr->handle = fopen(filename,mode);
    if (ptr->handle == NULL) {
	free(ptr->name);
	free(ptr);
	// fatal_error("ffopen: could not open %s", filename);
	return NULL;
    }

    /* check if output is to a pipe */
    if (is_read_file == 0) {
	if (stat(filename, &stat_buf) == -1) {
	    /* remove ptr */
	    free(ptr->name);
	    free(ptr);
	    fatal_error("ffopen: could not stat file: %s", filename);
	}
        if (S_ISFIFO(stat_buf.st_mode)) {
	    flush_mode  = 1;
	}
    }

    /* add ptr to linked list */
    ptr->next = opened_file_start;
    opened_file_start = ptr;
    return ptr->handle;
}
示例#20
0
文件: tosspkt.c 项目: ftnapps/FTNd
/*
 * Process one message from message packet.
 *
 *  0   - no more messages
 *  1   - more messages
 *  2   - bad file
 *  3   - bad message header
 *  4   - unable to open temp file
 *  5   - unexpected end of packet
 *  >10 - import error
 */
int getmessage(FILE *pkt, faddr *p_from, faddr *p_to)
{
    char	    buf[MAX_LINE_LENGTH +1], *orig = NULL, *p, *l, *r, *subj = NULL;
    int		    tmp, rc, maxrc = 0, result, flags, cost;
    static faddr    f, t;
    faddr	    *o;
    time_t	    mdate = 0L;
    FILE	    *fp;
    unsigned char   buffer[0x0e];

    Nopper();

    result = fread(&buffer, 1, sizeof(buffer), pkt);
    if (result == 0) {
	Syslog('m', "Zero bytes message, assume end of pkt");
	return 0;
    }

    switch (tmp = (buffer[0x01] << 8) + buffer[0x00]) {
	case 0:	if (result == 2)
		    return 0;
		else {
		    Syslog('!', "Junk after logical end of packet, skipped");
		    return 5;

		}
	case 2:	break;

	default:Syslog('!', "bad message type: 0x%04x",tmp);
		return 2;
    }

    if (result != 14) {
	Syslog('!', "Unexpected end of packet");
	return 5;
    }

    memset(&f, 0, sizeof(f));
    memset(&t, 0, sizeof(t));
    f.node = (buffer[0x03] << 8) + buffer[0x02];
    t.node = (buffer[0x05] << 8) + buffer[0x04];
    f.net  = (buffer[0x07] << 8) + buffer[0x06];
    t.net  = (buffer[0x09] << 8) + buffer[0x08];
    flags  = (buffer[0x0b] << 8) + buffer[0x0a];
    cost   = (buffer[0x0d] << 8) + buffer[0x0c];

    /*
     * Read the DateTime, toUserName, fromUserName and subject fields
     * from the packed message. The stringlength is +1 for the right
     * check. This is different then in ifmail's original code.
     */
    if (aread(buf, sizeof(buf)-1, pkt)) {
	if (strlen(buf) > 20)
	    Syslog('!', "date too long (%d) \"%s\"", strlen(buf), printable(buf, 0));
	mdate = parsefdate(buf, NULL);
	if (aread(buf, sizeof(buf)-1, pkt)) {
	    Syslog('!', "date not null-terminated: \"%s\"",buf);
	    return 3;
	}
    }

    if (aread(buf, sizeof(buf)-1, pkt)) {
	if (strlen(buf) > 36)
	    Syslog('!', "to name too long (%d) \"%s\"", strlen(buf), printable(buf, 0));
	t.name = xstrcpy(buf);
	if (aread(buf, sizeof(buf)-1, pkt)) {
	    if (*(p=t.name+strlen(t.name)-1) == '\n')
		*p = '\0';
	    Syslog('!', "to name not null-terminated: \"%s\"",buf);
	    return 3;
	}
    }

    if (aread(buf, sizeof(buf)-1, pkt)) {
	if (strlen(buf) > 36)
	    Syslog('!', "from name too long (%d) \"%s\"", strlen(buf), printable(buf, 0));
	f.name = xstrcpy(buf);
	if (aread(buf, sizeof(buf)-1, pkt)) {
	    if (*(p=f.name+strlen(f.name)-1) == '\n') 
		*p = '\0';
	    Syslog('!', "from name not null-terminated: \"%s\"",buf);
	    return 3;
	}
    }
	
    if (aread(buf, sizeof(buf)-1, pkt)) {
	if (strlen(buf) > 72)
	    Syslog('!', "subject too long (%d) \"%s\"", strlen(buf), printable(buf, 0));
	subj = xstrcpy(buf);
	if (aread(buf, sizeof(buf)-1, pkt)) {
	    if (*(p=subj+strlen(subj)-1) == '\n') 
		*p = '\0';
	    subj = xstrcat(subj,(char *)"\\n");
	    subj = xstrcat(subj,buf);
	    Syslog('!', "subj not null-terminated: \"%s\"",buf);
	    return 3;
	}
    }

    if (feof(pkt) || ferror(pkt)) {
	Syslog('!', "Could not read message header, aborting");
	return 3;
    }

    if ((fp = tmpfile()) == NULL) {
	WriteError("$unable to open temporary file");
	return 4;
    }

    /*
     * Read the text from the .pkt file
     */
    while (aread(buf,sizeof(buf)-1,pkt)) {

	fputs(buf, fp);

	/*
	 * Extract info from Origin line if found.
	 */
	if (!strncmp(buf," * Origin:",10)) {
	    p=buf+10;
	    while (*p == ' ') 
		p++;
	    if ((l=strrchr(p,'(')) && (r=strrchr(p,')')) && (l < r)) {
		*l = '\0';
		*r = '\0';
		l++;
		if ((o = parsefnode(l))) {
		    f.point = o->point;
		    f.node = o->node;
		    f.net = o->net;
		    f.zone = o->zone;
		    if (o->domain) 
			f.domain=o->domain;
		    o->domain=NULL;
		    tidy_faddr(o);
		}
	    } else
		if (*(l=p+strlen(p)-1) == '\n')
		    *l='\0';
		for (l=p+strlen(p)-1;*l == ' ';l--) 
		    *l='\0'; 
		orig = xstrcpy(p);
	}
    }

    rc = importmsg(p_from, &f, &t, orig, subj, mdate, flags, cost, fp, p_to->zone);
    if (rc)
	rc+=10;
    if (rc > maxrc) 
	maxrc = rc;

    fclose(fp);

    if(f.name) 
	free(f.name); 
    f.name=NULL;

    if(t.name) 
	free(t.name); 
    t.name=NULL;

    if(f.domain) 
	free(f.domain); 
    f.domain=NULL;

    if(t.domain) 
	free(t.domain); 
    t.domain=NULL;

    if (subj)
	free(subj);
    subj = NULL;

    if (orig)
	free(orig);
    orig = NULL;

    if (feof(pkt) || ferror(pkt)) {
	WriteError("Unexpected end of packet");
	return 5;
    }
    return 1;
}
示例#21
0
int load_energies(EMATRIX *ematrix, char *dir, int verbose)
/* this program returns number of conformers loaded, or -1 if no exsiting energy table */
{
	int i, n_conf;
    char sbuff[128];
    FILE *fp, *fp2;
    CONF_HEAD *conf;
    PAIRWISE *pw;
    char version[128];

    /* Obtain the first line of the energy lookup table, which is the number of conformers */
    sprintf(sbuff, "%s/%s", dir, ENERGY_TABLE);
    if (!(fp = fopen(sbuff, "r"))) {
        printf("energies.opp not found\n");
        return -1;
    }

    // unzip the energies.opp
    fp2 = tmpfile();
    inf(fp, fp2);
    rewind(fp2);
    fclose(fp);


    fgets(sbuff, sizeof(sbuff), fp2);
    if (sscanf(sbuff, "%d %s", &n_conf, version) != 2) {

       printf("   Version mismatch: Opp file was made by pre-MCCE2.3 and this program is for %s\n", VERSION);
       printf("                     Use oppconvert to fix the mismatch\n");
       return USERERR;
    }

    if (strncmp(VERSION, version, 7)) {
    	/* Do not check the version any more, xz 07-06-2013.
       printf("   Version mismatch: Opp file was made by %s and this program is for %s\n", version, VERSION);
       printf("                     Use oppconvert to fix the mismatch\n");
       return USERERR;
         */
    }

    /* allocate memeory */
    if (ematrix->n > 0) {  /* existing table */
       if (ematrix->n != n_conf) {
          printf("error in loading Energy lookup table size %d on to %d\n", n_conf, ematrix->n);
          return USERERR;
       }
    }
    else {
       if (!(ematrix->conf = (CONF_HEAD *) calloc(n_conf, sizeof(CONF_HEAD)))) {
          printf("   Memory error in A load_energies\n");
          return 0; /* none loaded and memory cleared */
       }
       if (!(ematrix->pw = (PAIRWISE **) calloc(n_conf, sizeof(PAIRWISE *)))) {
          printf("   Memory error in B load_energies\n");
          return 0; /* none loaded and memory cleared */
       }
       for (i=0; i<n_conf; i++) {
          if (!(ematrix->pw[i] = (PAIRWISE *) calloc(n_conf, sizeof(PAIRWISE)))) {
             printf("   Memory error in C load_energies\n");
             return 0; /* none loaded and memory cleared */
          }
       }
       ematrix->n = n_conf;
    }

    /* Buffer of head part */
    if (!(conf = (CONF_HEAD *) calloc(n_conf, sizeof(CONF_HEAD)))){
          printf("   Memory error loading head in load_energies\n");
          return USERERR;
    }
    if (!(pw = (PAIRWISE *) calloc(n_conf, sizeof(PAIRWISE)))){
          printf("   Memory error loading PW buffer in load_energies\n");
          return USERERR;
    }


    if (fread(conf, sizeof(CONF_HEAD), ematrix->n, fp2) != n_conf) {
        printf("   Error in loading pairwise interaction headers at position %d\n", i);
        return USERERR;
    }
    for (i=0; i<ematrix->n; i++) {
        fread(pw, sizeof(PAIRWISE), ematrix->n, fp2);
		if ( verbose == 1 ) {
			printf("reading row %05d\r", i); fflush(stdout);
		}
        
        if (conf[i].on == 't') {
           memcpy(&ematrix->conf[i], &conf[i], sizeof(CONF_HEAD));
           memcpy(ematrix->pw[i], pw, ematrix->n*sizeof(PAIRWISE));
        }
        if (ematrix->conf[i].on != 't') /* initilize even if not a valid delphi run */
           memcpy(&ematrix->conf[i], &conf[i], sizeof(CONF_HEAD));
    }
    if ( verbose == 1) {
		printf("\n"); fflush(stdout);
    }
    free(conf);
    free(pw);
    fclose(fp2);
    return n_conf;
}
示例#22
0
文件: pcpd.c 项目: zixia/nospam
static struct PCP_new_eventid *readnewevent(struct PCP *pcp)
{
	struct PCP_save_event se;
	struct readnewevent_s rne;
	struct PCP_new_eventid *ne;
	const char *cp;
	struct proxy_list *p;
	int first_save=1;

	if (!deleted_eventid)
		proxy_list_rset();

	/* Open new proxy connections */

	while ((cp=strtok(NULL, " ")) != NULL)
	{
		char *errmsg, *q;
		char *n=strdup(cp);
		struct proxy_list *pcp;

		if (!n)
		{
			syslog(LOG_ALERT, "Out of memory.");
			exit(1);
		}

		if (proxy_userid)
		{
			printf("500-Cannot create proxy in proxy mode.\n");
			free(n);
			errno=EIO;
			return (NULL);
		}

		strcpy(n, cp);
		pcp=proxy(n, &errmsg);

		if (pcp)
		{
			pcp->flags |= PROXY_NEW;
			free(n);
			continue;
		}

		if (force_flag)
		{
			pcp->flags |= PROXY_IGNORE;
			free(n);
			continue;
		}

		while (errmsg && (q=strchr(errmsg, '\n')) != 0)
			*q='/';
		printf("500-%s: %s\n", n, errmsg ? errmsg:"Failed to create a proxy connection.");
		free(n);
		proxy_list_rset();
		return (NULL);
	}

	memset(&se, 0, sizeof(se));
	if ((rne.tmpfile=tmpfile()) == NULL)
		return (NULL);
	time(&rne.last_noop_time);

	rne.seeneol=1;
	rne.seendot=0;
	rne.seeneof=0;
	rne.cnt=0;
	rne.pcp=pcp;
	pcpdtimer_init(&rne.inactivity_timeout);
	rne.inactivity_timeout.handler=&inactive;
	pcpdtimer_install(&rne.inactivity_timeout, 300);

	for (p=proxy_list; p; p=p->next)
	{
		struct PCP_save_event se;

		if ( !(p->flags & PROXY_NEW))
			continue;

		if (fseek(rne.tmpfile, 0L, SEEK_SET) < 0
		    || lseek(fileno(rne.tmpfile), 0L, SEEK_SET) < 0)
		{
			int save_errno=errno;
			proxy_list_rset();
			pcpdtimer_triggered(&rne.inactivity_timeout);
			fclose(rne.tmpfile);
			errno=save_errno;
			return (NULL);
		}

		memset(&se, 0, sizeof(se));
		if (first_save)
		{
			se.write_event_func_misc_ptr= &rne;
			se.write_event_func=readnewevent_callback;
		}
		else
			se.write_event_fd=fileno(rne.tmpfile);

		if ((p->newevent=pcp_new_eventid(p->proxy,
						 p->old_event_id,
						 &se)) == NULL)
		{
			pcpdtimer_triggered(&rne.inactivity_timeout);

			if (force_flag)
			{
				/* Force it through */

				p->flags &= ~PROXY_NEW;
				p->flags |= PROXY_IGNORE;
				continue;
			}

			proxy_error(p->userid,
				    pcp_errmsg(p->proxy));
			proxy_list_rset();
			fclose(rne.tmpfile);
			errno=EIO;
			return (NULL);
		}
		if (first_save)
			pcpdtimer_triggered(&rne.inactivity_timeout);
		first_save=0;
	}


	if (first_save)
	{
		se.write_event_func_misc_ptr= &rne;
		se.write_event_func=readnewevent_callback;
	}
	else
		se.write_event_fd=fileno(rne.tmpfile);

	if (mkparticipants(&se) || fseek(rne.tmpfile, 0L, SEEK_SET) < 0
	    || lseek(fileno(rne.tmpfile), 0L, SEEK_SET) < 0)
	{
		int save_errno=errno;

		proxy_list_rset();
		fclose(rne.tmpfile);
		errno=save_errno;
		return (NULL);
	}

	if ((ne=pcp_new_eventid(pcp, deleted_eventid, &se)) == NULL)
	{
		while (!rne.seeneof)
		{
			char buf[512];

			readnewevent_callback(buf, sizeof(buf), &se);
		}
	}
	pcpdtimer_triggered(&rne.inactivity_timeout);
	if (first_save)
	{
		if (fflush(rne.tmpfile) || ferror(rne.tmpfile))
		{
			int save_errno=errno;

			proxy_list_rset();
			fclose(rne.tmpfile);
			errno=save_errno;
			return (NULL);
		}
	}

	notbooked=1;
	fclose(rne.tmpfile);
	return (ne);
}
示例#23
0
uint8 T64Drive::open_directory(int channel, char *filename)
{
    char buf[] = "\001\004\001\001\0\0\022\042                \042 00 2A";
    char str[NAMEBUF_LENGTH];
    char pattern[NAMEBUF_LENGTH];
    char *p, *q;
    int i, num;
    int filemode;
    int filetype;

    // Special treatment for "$0"
    if (strlen(filename) == 1 && filename[0] == '0')
        filename += 1;

    // Convert filename ('$' already stripped), filemode/type are ignored
    convert_filename(filename, pattern, &filemode, &filetype);

    // Create temporary file
    if ((file[channel] = tmpfile()) == NULL)
        return ST_OK;

    // Create directory title
    p = &buf[8];
    for (i=0; i<16 && dir_title[i]; i++)
        *p++ = dir_title[i];
    fwrite(buf, 1, 32, file[channel]);

    // Create and write one line for every directory entry
    for (num=0; num<num_files; num++) {

        // Include only files matching the pattern
        if (match(pattern, file_info[num].name)) {

            // Clear line with spaces and terminate with null byte
            memset(buf, ' ', 31);
            buf[31] = 0;

            p = buf;
            *p++ = 0x01;	// Dummy line link
            *p++ = 0x01;

            // Calculate size in blocks (254 bytes each)
            i = (file_info[num].length + 254) / 254;
            *p++ = i & 0xff;
            *p++ = (i >> 8) & 0xff;

            p++;
            if (i < 10) p++;	// Less than 10: add one space
            if (i < 100) p++;	// Less than 100: add another space

            // Convert and insert file name
            strcpy(str, file_info[num].name);
            *p++ = '\"';
            q = p;
            for (i=0; i<16 && str[i]; i++)
                *q++ = str[i];
            *q++ = '\"';
            p += 18;

            // File type
            switch (file_info[num].type) {
            case FTYPE_PRG:
                *p++ = 'P';
                *p++ = 'R';
                *p++ = 'G';
                break;
            case FTYPE_SEQ:
                *p++ = 'S';
                *p++ = 'E';
                *p++ = 'Q';
                break;
            case FTYPE_USR:
                *p++ = 'U';
                *p++ = 'S';
                *p++ = 'R';
                break;
            case FTYPE_REL:
                *p++ = 'R';
                *p++ = 'E';
                *p++ = 'L';
                break;
            default:
                *p++ = '?';
                *p++ = '?';
                *p++ = '?';
                break;
            }

            // Write line
            fwrite(buf, 1, 32, file[channel]);
        }
    }
示例#24
0
size_t format_image(uint8_t **out, int render_fmt, int misc_int, VInfo *ji, uint8_t *buf) {
#ifdef HAVE_WINDOWS
  char tfn[64] = "";
#endif
#ifdef __USE_XOPEN2K8
  size_t rs = 0;
  FILE *x = open_memstream((char**) out, &rs);
#else
  FILE *x = tmpfile();
#endif
#ifdef HAVE_WINDOWS
  if (!x) {
    // wine and ancient version of windows don't support tmpfile()
    // srand is per thread :(
    struct timeval tv;
    gettimeofday(&tv, NULL);
    srand(tv.tv_sec * tv.tv_usec * 100000);
    snprintf(tfn, sizeof(tfn), "harvid.tmp.%d", rand());
    x = fopen(tfn, "w+b"); // we should really use open(tfn, O_RDWR | O_CREAT | O_EXCL, 0600); and fdopen
  }
#endif
  if (!x) {
    dlog(LOG_ERR, "IMF: tmpfile() creation failed.\n");
    return(0);
  }

  switch (render_fmt) {
    case 1:
      {
        if (misc_int < 5 || misc_int > 100)
          misc_int = JPEG_QUALITY;
      if (write_jpeg(ji, buf, misc_int, x))
        dlog(LOG_ERR, "IMF: Could not write jpeg\n");
      break;
      }
    case 2:
      if (write_png(ji, buf, x))
        dlog(LOG_ERR, "IMF: Could not write png\n");
      break;
    case 3:
      if (write_ppm(ji, buf, x))
        dlog(LOG_ERR, "IMF: Could not write ppm\n");
      break;
    default:
        dlog(LOG_ERR, "IMF: Unknown outformat %d\n", render_fmt);
        fclose(x);
        return 0;
      break;
  }
#ifdef __USE_XOPEN2K8
  fclose(x);
  return rs;
#elif defined HAVE_WINDOWS
  if (strlen(tfn) > 0) {
    fclose(x);
    x = fopen(tfn, "rb");
  } else {
    fflush(x);
  }
#else
  fflush(x);
#endif
  /* re-read image from tmp-file */
  fseek (x , 0 , SEEK_END);
  long int rsize = ftell (x);
  rewind(x);
  if (fseek(x, 0L, SEEK_SET) < 0) {
    dlog(LOG_WARNING, "IMF: fseek failed\n");
  }
  fflush(x);
  *out = (uint8_t*) malloc(rsize*sizeof(uint8_t));
  if (fread(*out, sizeof(char), rsize, x) != rsize) {
    dlog(LOG_WARNING, "IMF: short read. - possibly incomplete image\n");
  }
  fclose(x);
#ifdef HAVE_WINDOWS
  if (strlen(tfn) > 0) {
    unlink(tfn);
  }
#endif
  return (rsize);
}
示例#25
0
/*---------
 * readline
 *---------
 */
static int my_init_readline(char *name)
{
    int  i = 0;
    int  fd = 0;
    int  tmplen = 0;
    char *buf   = NULL;
    FILE *tmpfp = (FILE *)NULL;

    char nametmp[] = ".inputrc.XXXXXX";
    char tmpcmd[] = "rm -rf ";
    char *rc[] = {
            "#$include /etc/inputrc\n",
            "set editing-mode emacs\n",
            "set bell-style none\n",
            "set input-meta on\n",
            "set convert-meta on\n",
            "set output-meta on\n",
            "TAB: complete\n ",
            "Meta-Rubout: backward-kill-word\n",
            "\"\\C-a\": beginning-of-line\n",
            "\"\\C-e\": end-of-line\n",
            "\"\\C-f\": forward-char\n",
            "\"\\C-b\": backward-char\n",
            "\"\\C-p\": previous-history\n",
            "\"\\C-n\": next-history  \n",
            "\"\\C-k\": kill-line  \n",
            "\"\\C-u\": unix-line-discard \n",
            "\"\\C-d\": delete-char  \n",
            "\"\\C-h\": backward-delete-char  \n",
//            "\"  \":   \n",
            "\"\x7F\": backward-delete-char  \n",
            NULL
        };


    /********
     inputrc
     ********/
    fd = mkstemp(nametmp);
    //dbg("tmpfile:%s\n", nametmp);
    if (fd == -1) {
        fprintf(stderr, "fopen tmpfile error.");
        return -1;
    }

    for(i=0; rc[i] != NULL; i++) {
        tmplen = strlen(rc[i]);
        if (write(fd, rc[i], tmplen) != tmplen) {
            fprintf(stderr, "WARN: write inputrc fail(line: %d, func: %s).\n",
                __LINE__, __FUNCTION__);
        }
    }
    close(fd);
    fd = 0;

    rl_read_init_file(nametmp); 

    myrm(nametmp);

    rl_redisplay_function = myrl_noredisplay;  //remove outputs of readline();
    //rl_bind_key_in_map();//

    /*tmp file for rl_outstream*/
    tmpfp = tmpfile();
    if (!tmpfp) {
        fprintf(stderr, "can't open tmp stream for rl_outstream!\n");
        return -1;
    }
    rl_outstream = tmpfp;

    if ((fd = mkstemp(name)) == -1) {
        fprintf(stderr, "tmpfile err.\n");
        close(fd);
        return -1;
    }
    close(fd);

    return 0;
}
示例#26
0
/****************************************************************************
  Read the request string (or part of it) from the metaserver.
****************************************************************************/
static void meta_read_response(struct server_scan *scan)
{
  char buf[4096];
  int result;

  if (!scan->meta.fp) {
#ifdef WIN32_NATIVE
    char filename[MAX_PATH];

    GetTempPath(sizeof(filename), filename);
    cat_snprintf(filename, sizeof(filename), "fctmp%d", myrand(1000));

    scan->meta.fp = fc_fopen(filename, "w+b");
#else
    scan->meta.fp = tmpfile();
#endif

    if (!scan->meta.fp) {
      scan->error_func(scan, _("Could not open temp file."));
    }
  }

  while (1) {
    result = fc_readsocket(scan->sock, buf, sizeof(buf));

    if (result < 0) {
      if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) {
	/* Keep waiting. */
	return;
      }
      scan->error_func(scan, fc_strerror(fc_get_errno()));
      return;
    } else if (result == 0) {
      fz_FILE *f;
      char str[4096];

      /* We're done! */
      rewind(scan->meta.fp);

      f = fz_from_stream(scan->meta.fp);
      assert(f != NULL);

      /* skip HTTP headers */
      /* XXX: TODO check for magic Content-Type: text/x-ini -vasc */
      while (fz_fgets(str, sizeof(str), f) && strcmp(str, "\r\n") != 0) {
	/* nothing */
      }

      /* XXX: TODO check for magic Content-Type: text/x-ini -vasc */

      /* parse HTTP message body */
      scan->servers = parse_metaserver_data(f);
      scan->meta.state = META_DONE;

      /* 'f' (hence 'meta.fp') was closed in parse_metaserver_data(). */
      scan->meta.fp = NULL;

      if (NULL == scan->servers) {
        my_snprintf(str, sizeof(str),
                    _("Failed to parse the metaserver data from http://%s."),
                    scan->meta.name);
        scan->error_func(scan, str);
      }

      return;
    } else {
      if (fwrite(buf, 1, result, scan->meta.fp) != result) {
	scan->error_func(scan, fc_strerror(fc_get_errno()));
      }
    }
  }
}
示例#27
0
int uwsgi_proto_zeromq_accept(struct wsgi_request *wsgi_req, int fd) {

	zmq_msg_t message;
	char *req_uuid = NULL;
	size_t req_uuid_len = 0;
	char *req_id = NULL;
	size_t req_id_len = 0;
	char *req_path = NULL;
	size_t req_path_len = 0;
#ifdef UWSGI_JSON
	json_t *root;
	json_error_t error;
#endif
	char *mongrel2_req = NULL;
	size_t mongrel2_req_size = 0;
	int resp_id_len;
	uint32_t events = 0;
	char *message_ptr;
	size_t message_size = 0;
	char *post_data;


#ifdef ZMQ_EVENTS
	size_t events_len = sizeof(uint32_t);
	if (uwsgi.edge_triggered == 0) {
		if (zmq_getsockopt(pthread_getspecific(uwsgi.zmq_pull), ZMQ_EVENTS, &events, &events_len) < 0) {
			uwsgi_error("zmq_getsockopt()");
			uwsgi.edge_triggered = 0;
			return -1;
		}
	}
#endif

	if (events & ZMQ_POLLIN || uwsgi.edge_triggered) {
		wsgi_req->do_not_add_to_async_queue = 1;
		wsgi_req->proto_parser_status = 0;
		zmq_msg_init(&message);
		if (zmq_recv(pthread_getspecific(uwsgi.zmq_pull), &message, uwsgi.zeromq_recv_flag) < 0) {
			if (errno == EAGAIN) {
				uwsgi.edge_triggered = 0;
			}
			else {
				uwsgi_error("zmq_recv()");
			}
			zmq_msg_close(&message);
			return -1;
		}
		uwsgi.edge_triggered = 1;
		message_size = zmq_msg_size(&message);
		//uwsgi_log("%.*s\n", (int) wsgi_req->proto_parser_pos, zmq_msg_data(&message));
		if (message_size > 0xffff) {
			uwsgi_log("too much big message %d\n", message_size);
			zmq_msg_close(&message);
			wsgi_req->do_not_log = 1;
			return -1;
		}

		message_ptr = zmq_msg_data(&message);

		// warning mongrel2_req_size will contains a bad value, but this is not a problem...
		post_data = uwsgi_split4(message_ptr, message_size, ' ', &req_uuid, &req_uuid_len, &req_id, &req_id_len, &req_path, &req_path_len, &mongrel2_req, &mongrel2_req_size);
		if (post_data == NULL) {
			uwsgi_log("cannot parse message (split4 phase)\n");
			zmq_msg_close(&message);
			wsgi_req->do_not_log = 1;
			return -1;
		}

		// fix post_data, mongrel2_req and mongrel2_req_size
		post_data = uwsgi_netstring(mongrel2_req, message_size - (mongrel2_req - message_ptr), &mongrel2_req, &mongrel2_req_size);
		if (post_data == NULL) {
			uwsgi_log("cannot parse message (body netstring phase)\n");
			zmq_msg_close(&message);
			wsgi_req->do_not_log = 1;
			return -1;
		}

		// ok ready to parse tnetstring/json data and build uwsgi request
		if (mongrel2_req[mongrel2_req_size] == '}') {
			if (uwsgi_mongrel2_tnetstring_parse(wsgi_req, mongrel2_req, mongrel2_req_size)) {
				zmq_msg_close(&message);
				wsgi_req->do_not_log = 1;
				return -1;
			}
		}
		else {
#ifdef UWSGI_JSON
#ifdef UWSGI_DEBUG
			uwsgi_log("JSON %d: %.*s\n", mongrel2_req_size, mongrel2_req_size, mongrel2_req);
#endif
			// add a zero to the end of buf
			mongrel2_req[mongrel2_req_size] = 0;
			root = json_loads(mongrel2_req, 0, &error);
			if (!root) {
				uwsgi_log("error parsing JSON data: line %d %s\n", error.line, error.text);
				zmq_msg_close(&message);
				wsgi_req->do_not_log = 1;
				return -1;
			}

			if (uwsgi_mongrel2_json_parse(root, wsgi_req)) {
				json_decref(root);
				zmq_msg_close(&message);
				wsgi_req->do_not_log = 1;
				return -1;
			}

			json_decref(root);
#else
			uwsgi_log("JSON support not enabled (recompile uWSGI with libjansson support, or re-configure mongrel2 with \"protocol='tnetstring'\". skip request\n");
#endif
		}

		// pre-build the mongrel2 response_header
		wsgi_req->proto_parser_buf = uwsgi_malloc(req_uuid_len + 1 + 11 + 1 + req_id_len + 1 + 1);
		memcpy(wsgi_req->proto_parser_buf, req_uuid, req_uuid_len);
		((char *) wsgi_req->proto_parser_buf)[req_uuid_len] = ' ';
		resp_id_len = uwsgi_num2str2(req_id_len, wsgi_req->proto_parser_buf + req_uuid_len + 1);
		((char *) wsgi_req->proto_parser_buf)[req_uuid_len + 1 + resp_id_len] = ':';

		memcpy((char *) wsgi_req->proto_parser_buf + req_uuid_len + 1 + resp_id_len + 1, req_id, req_id_len);

		memcpy((char *) wsgi_req->proto_parser_buf + req_uuid_len + 1 + resp_id_len + 1 + req_id_len, ", ", 2);
		wsgi_req->proto_parser_pos = (uint64_t) req_uuid_len + 1 + resp_id_len + 1 + req_id_len + 1 + 1;

		// handle post data
		if (wsgi_req->post_cl > 0 && !wsgi_req->async_post) {
			if (uwsgi_netstring(post_data, message_size - (post_data - message_ptr), &message_ptr, &wsgi_req->post_cl)) {
#ifdef UWSGI_DEBUG
				uwsgi_log("post_size: %d\n", wsgi_req->post_cl);
#endif
				wsgi_req->async_post = tmpfile();
				if (fwrite(message_ptr, wsgi_req->post_cl, 1, wsgi_req->async_post) != 1) {
					uwsgi_error("fwrite()");
					zmq_msg_close(&message);
					return -1;
				}
				rewind(wsgi_req->async_post);
				wsgi_req->body_as_file = 1;
			}
		}


		zmq_msg_close(&message);

		return 0;
	}

	return -1;
}
示例#28
0
int main(int argc, char *argv[])
{
	char *password_file = NULL;
	char *username = NULL;
	bool create_new = false;
	bool delete_user = false;
	FILE *fptr, *ftmp;
	char password[MAX_BUFFER_LEN];
	int rc;
	bool do_update_file = false;
	char *backup_file;

	signal(SIGINT, handle_sigint);
	signal(SIGTERM, handle_sigint);

	OpenSSL_add_all_digests();

	if(argc == 4){
		if(!strcmp(argv[1], "-c")){
			create_new = true;
		}else if(!strcmp(argv[1], "-D")){
			delete_user = true;
		}
		password_file = argv[2];
		username = argv[3];
	}else if(argc == 3){
		if(!strcmp(argv[1], "-U")){
			do_update_file = true;
			password_file = argv[2];
		}else{
			password_file = argv[1];
			username = argv[2];
		}
	}else{
		print_usage();
		return 1;
	}

	if(create_new){
		rc = get_password(password, 1024);
		if(rc) return rc;
		fptr = fopen(password_file, "wt");
		if(!fptr){
			fprintf(stderr, "Error: Unable to open file %s for writing. %s.\n", password_file, strerror(errno));
			return 1;
		}
		rc = output_new_password(fptr, username, password);
		fclose(fptr);
		return rc;
	}else{
		fptr = fopen(password_file, "r+t");
		if(!fptr){
			fprintf(stderr, "Error: Unable to open password file %s. %s.\n", password_file, strerror(errno));
			return 1;
		}

		backup_file = malloc(strlen(password_file)+5);
		snprintf(backup_file, strlen(password_file)+5, "%s.tmp", password_file);

		if(create_backup(backup_file, fptr)){
			fclose(fptr);
			free(backup_file);
			return 1;
		}

		ftmp = tmpfile();
		if(!ftmp){
			fprintf(stderr, "Error: Unable to open temporary file. %s.\n", strerror(errno));
			fclose(fptr);
			free(backup_file);
			return 1;
		}
		if(delete_user){
			rc = delete_pwuser(fptr, ftmp, username);
		}else if(do_update_file){
			rc = update_file(fptr, ftmp);
		}else{
			rc = get_password(password, 1024);
			if(rc){
				fclose(fptr);
				fclose(ftmp);
				unlink(backup_file);
				free(backup_file);
				return rc;
			}
			/* Update password for individual user */
			rc = update_pwuser(fptr, ftmp, username, password);
		}
		if(rc){
			fclose(fptr);
			fclose(ftmp);
			unlink(backup_file);
			free(backup_file);
			return rc;
		}

		if(copy_contents(ftmp, fptr)){
			fclose(fptr);
			fclose(ftmp);
			fprintf(stderr, "Error occurred updating password file.\n");
			fprintf(stderr, "Password file may be corrupt, check the backup file: %s.\n", backup_file);
			free(backup_file);
			return 1;
		}
		fclose(fptr);
		fclose(ftmp);

		/* Everything was ok so backup no longer needed. May contain old
		 * passwords so shouldn't be kept around. */
		unlink(backup_file);
		free(backup_file);
	}

	return 0;
}
示例#29
0
// returns 0 if everything's OK
// return -1 if error
int  AmAudioFile::open(const string& filename, OpenMode mode, bool is_tmp)
{
    close();

    AmAudioFileFormat* f_fmt = fileName2Fmt(filename);
    if(!f_fmt){
	ERROR("while trying to the format of '%s'\n",filename.c_str());
	return -1;
    }
    fmt.reset(f_fmt);

    open_mode = mode;
    this->close_on_exit = true;

    if(!is_tmp){
	fp = fopen(filename.c_str(),mode == AmAudioFile::Read ? "r" : "w+");
	if(!fp){
	    if(mode == AmAudioFile::Read)
		ERROR("file not found: %s\n",filename.c_str());
	    else
		ERROR("could not create/overwrite file: %s\n",filename.c_str());
	    return -1;
	}
    } else {
	
	fp = tmpfile();
	if(!fp){
	    ERROR("could not create temporary file: %s\n",strerror(errno));
	}
    }

    amci_file_desc_t fd;
    int ret = -1;

    if(open_mode == AmAudioFile::Write){

 	if (f_fmt->channels<0 || f_fmt->rate<0) {
	    if (f_fmt->channels<0)
		ERROR("channel count must be set for output file.\n");
	    if (f_fmt->rate<0)
		ERROR("sampling rate must be set for output file.\n");
	    close();
	    return -1;
 	}
    }

    fd.subtype = f_fmt->getSubtypeId();
    fd.sample = f_fmt->sample;
    fd.channels = f_fmt->channels;
    fd.rate = f_fmt->rate;

    if( iofmt->open && !(ret = (*iofmt->open)(fp,&fd,mode, f_fmt->getHCodecNoInit())) ) {
	if (mode == AmAudioFile::Read) {
	    f_fmt->setSubtypeId(fd.subtype);
	    f_fmt->sample = fd.sample;
	    f_fmt->channels = fd.channels;
	    f_fmt->rate = fd.rate;
	}
	begin = ftell(fp);
    }
    else {
	if(!iofmt->open)
	    ERROR("no open function\n");
	else
	    ERROR("open returned %d\n",ret);
	close();
	return ret;
    }

//     if(open_mode == AmAudioFile::Write){

// 	DBG("After open:\n");
// 	DBG("fmt::subtype = %i\n",f_fmt->getSubtypeId());
// 	DBG("fmt::sample = %i\n",f_fmt->sample);
// 	DBG("fmt::channels = %i\n",f_fmt->channels);
// 	DBG("fmt::rate = %i\n",f_fmt->rate);
//     }

    return ret;
}
示例#30
0
static int io_tmpfile (lua_State *L) {
  int *pf = newfile(L);
  *pf = tmpfile();
  return (*pf == FS_OPEN_OK - 1) ? pushresult(L, 0, NULL) : 1;
}