예제 #1
0
void PStreamFile::open()
{
    pAssert(m_file == P_NULL);

    if (m_writable)
    {
        m_file = pfopen(m_filePath.c_str(), P_FILE_WRITEONLY_BINARY);
    }
    else
    {
        m_file = pfopen(m_filePath.c_str(), P_FILE_READONLY_BINARY);
    }
}
예제 #2
0
ESR_ReturnCode SR_EventLog_AudioOpen(SR_EventLog* self, const LCHAR* audio_type, size_t sample_rate, size_t sample_size)
{
  SR_EventLogImpl *impl = (SR_EventLogImpl*) self;
  LCHAR *p;

  LSTRCPY(impl->waveformFilename, impl->logFilename);
  p = LSTRSTR(impl->waveformFilename, L(".log"));
  if (p == NULL)
  {
    PLogError(L("ESR_OPEN_ERROR: %s"), impl->waveformFilename);
    return ESR_OPEN_ERROR;
  }
  *p = 0; /* trunc the name */

  psprintf(impl->waveformFilename, L("%s-%04lu.wav"), impl->waveformFilename, (unsigned long) ++impl->waveformCounter);

  impl->waveformFile = pfopen ( impl->waveformFilename, L("wb+") );

  if (impl->waveformFile == NULL)
  {
    PLogError(L("ESR_OPEN_ERROR: %s"), impl->waveformFilename);
    return ESR_OPEN_ERROR;
  }
  impl->waveform_num_bytes = 0;
  impl->waveform_bytes_per_sample = sample_size;
  impl->waveform_sample_rate = sample_rate;
  return writeRiffHeader(self);
}
예제 #3
0
pcap_t *
pcap_open_live(const char *device, int snaplen, int promisc, int to_ms,
    char *ebuf)
{
	pcap_t *p;
	short enmode;
	int backlog = -1;	/* request the most */
	struct enfilter Filter;
	struct endevp devparams;

	p = (pcap_t *)malloc(sizeof(*p));
	if (p == NULL) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE,
		    "pcap_open_live: %s", pcap_strerror(errno));
		return (0);
	}
	memset(p, 0, sizeof(*p));

	/*
	 * XXX - we assume here that "pfopen()" does not, in fact, modify
	 * its argument, even though it takes a "char *" rather than a
	 * "const char *" as its first argument.  That appears to be
	 * the case, at least on Digital UNIX 4.0.
	 */
	p->fd = pfopen(device, O_RDONLY);
	if (p->fd < 0) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "pf open: %s: %s\n\
your system may not be properly configured; see the packetfilter(4) man page\n",
			device, pcap_strerror(errno));
		goto bad;
	}
예제 #4
0
pbool PIni::load(const pchar *filename)
{
    //
    // Look for the file in the specified path
    //
    const pchar* pathList[] =
    {
        ".",
        pPathGetApplicationDirectory(),
        pPathGetExternalStoragePath(),
    };

    for (size_t i = 0; i < sizeof(pathList) / sizeof(pathList[0]); ++i)
    {
        if (pathList[i] != P_NULL)
        {
            PString cfgPath = PString(pathList[i]) + PString(pPathGetDelimiter()) + PString(filename);
            PFile *fp = pfopen(cfgPath.c_str(), "rb");
            if (fp != P_NULL)
            {
                if (ini_parse_file((FILE *)(fp), iniHandler_internal, this) < 0)
                {
                    PLOG_ERROR("Failed to parse %s", cfgPath.c_str());
                    pfclose(fp);
                    return false;
                }
                pfclose(fp);

                return true;
            }
        }
    }

    //
    // Look for the ini file in asset
    //
    PAsset asset = pAssetOpen(filename);
    if (pAssetIsValid(&asset))
    {
        PIniBufferObject iniBufferObject;
        iniBufferObject.m_buffer = (const pchar*)pAssetGetBuffer(&asset);
        iniBufferObject.m_bufferSize = pAssetGetSize(&asset);
        iniBufferObject.m_position = 0;
        
        if (ini_parse_buffer(&iniBufferObject, iniHandler_internal, this) < 0)
        {
            PLOG_ERROR("Failed to parse %s", filename);
            pAssetClose(&asset);
            return false;
        }

        pAssetClose(&asset);
        
        return true;
    }

    PLOG_ERROR("Failed to find %s", filename);
    
    return false;
}
예제 #5
0
pcap_t *
pcap_open_live(const char *device, int snaplen, int promisc, int to_ms,
    char *ebuf)
{
	pcap_t *p;
	short enmode;
	int backlog = -1;	/* request the most */
	struct enfilter Filter;
	struct endevp devparams;

	p = (pcap_t *)malloc(sizeof(*p));
	if (p == NULL) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE,
		    "pcap_open_live: %s", pcap_strerror(errno));
		return (0);
	}
	memset(p, 0, sizeof(*p));
	/*
	 * Initially try a read/write open (to allow the inject
	 * method to work).  If that fails due to permission
	 * issues, fall back to read-only.  This allows a
	 * non-root user to be granted specific access to pcap
	 * capabilities via file permissions.
	 *
	 * XXX - we should have an API that has a flag that
	 * controls whether to open read-only or read-write,
	 * so that denial of permission to send (or inability
	 * to send, if sending packets isn't supported on
	 * the device in question) can be indicated at open
	 * time.
	 *
	 * XXX - we assume here that "pfopen()" does not, in fact, modify
	 * its argument, even though it takes a "char *" rather than a
	 * "const char *" as its first argument.  That appears to be
	 * the case, at least on Digital UNIX 4.0.
	 */
	p->fd = pfopen(device, O_RDWR);
	if (p->fd == -1 && errno == EACCES)
		p->fd = pfopen(device, O_RDONLY);
	if (p->fd < 0) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "pf open: %s: %s\n\
your system may not be properly configured; see the packetfilter(4) man page\n",
			device, pcap_strerror(errno));
		goto bad;
	}
예제 #6
0
PAsset P_APIENTRY pAssetOpen(const pchar *fileName)
{
    // The asset resources are in the same folder of
    // executable/working directory.
    const pchar *path = fileName;

    PAsset ret;
    ret.pHandle = pfopen(path, "rb"); 
    ret.pData = P_NULL;
    return ret;
}
예제 #7
0
static int
pcap_activate_pf(pcap_t *p)
{
	struct pcap_pf *pf = p->priv;
	short enmode;
	int backlog = -1;	/* request the most */
	struct enfilter Filter;
	struct endevp devparams;

	/*
	 * Initially try a read/write open (to allow the inject
	 * method to work).  If that fails due to permission
	 * issues, fall back to read-only.  This allows a
	 * non-root user to be granted specific access to pcap
	 * capabilities via file permissions.
	 *
	 * XXX - we should have an API that has a flag that
	 * controls whether to open read-only or read-write,
	 * so that denial of permission to send (or inability
	 * to send, if sending packets isn't supported on
	 * the device in question) can be indicated at open
	 * time.
	 *
	 * XXX - we assume here that "pfopen()" does not, in fact, modify
	 * its argument, even though it takes a "char *" rather than a
	 * "const char *" as its first argument.  That appears to be
	 * the case, at least on Digital UNIX 4.0.
	 *
	 * XXX - is there an error that means "no such device"?  Is
	 * there one that means "that device doesn't support pf"?
	 */
	p->fd = pfopen(p->opt.device, O_RDWR);
	if (p->fd == -1 && errno == EACCES)
		p->fd = pfopen(p->opt.device, O_RDONLY);
	if (p->fd < 0) {
		pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "pf open: %s: %s\n\
your system may not be properly configured; see the packetfilter(4) man page\n",
			p->opt.device, pcap_strerror(errno));
		goto bad;
	}
예제 #8
0
int main (int argc, char **argv)
{
   PFILE *pf;
   int i;
   char data[1024];

   // Identify ourself and parentage
   printf("Before PFOPEN: Pid=%d, PGrp=%d, PPid=%d\n", getpid(), getpgrp(), getppid());
   fflush(stdout);

   // pfopen
   if ((pf = pfopen("pgrp", "r")) == NULL)
   {
      fprintf(stderr, "Main: pfopen failed: %s\n", strerror(errno));
      exit(1);
   }

   // Read child output
   printf("Child Output:\n");
   fflush(stdout);
   i = 0;
   while (i < 2 && fgets(data, sizeof(data), PF_OUT(pf)) != NULL)
   {
      printf("%s", data);
      i++;
   }
   printf("*** END of child output ***\n");
   fflush(stdout);

   // Terminate child process
   printf("Sending group term signal to child process group\n");
   fflush(stdout);
   pfkill(pf, SIGTERM);
   
   // Close pipe to child process
   printf("Closing connection to child process\n");
   fflush(stdout);
   pfclose(pf);

   printf("SUCCESS\n");
   fflush(stdout);

   exit(0);
}
예제 #9
0
파일: pcap-pf.c 프로젝트: MarginC/kame
pcap_t *
pcap_open_live(char *device, int snaplen, int promisc, int to_ms, char *ebuf)
{
	pcap_t *p;
	short enmode;
	int backlog = -1;	/* request the most */
	struct enfilter Filter;
	struct endevp devparams;

	p = (pcap_t *)malloc(sizeof(*p));
	if (p == NULL) {
		sprintf(ebuf, "pcap_open_live: %s", pcap_strerror(errno));
		return (0);
	}
	bzero((char *)p, sizeof(*p));
	p->fd = pfopen(device, O_RDONLY);
	if (p->fd < 0) {
		sprintf(ebuf, "pf open: %s: %s\n\
your system may not be properly configured; see \"man packetfilter(4)\"\n",
			device, pcap_strerror(errno));
		goto bad;
	}
예제 #10
0
struct libnet_link_int *
libnet_open_link_interface(char *device, char *ebuf)
{
    register struct libnet_link_int *l;
    short enmode;
    int backlog = -1;   /* request the most */
    struct enfilter Filter;
    struct endevp devparams;

    l = (struct libnet_link_int *)malloc(sizeof(*l));
    if (l == NULL)
    {
        sprintf(ebuf, "libnet_open_link_int: %s", ll_strerror(errno));
        return (0);
    }
    memset(l, 0, sizeof(*l));
    l->fd = pfopen(device, O_RDWR);
    if (l->fd < 0)
    {
        sprintf(ebuf, "pf open: %s: %s\n\your system may not be properly configured; see \"man packetfilter(4)\"\n",
            device, ll_strerror(errno));
        goto bad;
    }
예제 #11
0
void pushinclude(char *str)
{
    INCFILE *inf;
    FILE *fi;
    
    if ((fi = pfopen(str, "r")) != NULL) {
        if (F_verbose > 1 && F_verbose != 5 )
            printf("%.*s Including file \"%s\"\n", Inclevel*4, "", str);
        ++Inclevel;
        
        if (F_listfile)
            fprintf(FI_listfile, "------- FILE %s LEVEL %d PASS %d\n", str, Inclevel, pass);
        
        inf = (INCFILE *)zmalloc(sizeof(INCFILE));
        inf->next    = pIncfile;
        inf->name    = strcpy(ckmalloc(strlen(str)+1), str);
        inf->fi = fi;
        inf->lineno = 0;
        pIncfile = inf;
        return;
    }
    printf("Warning: Unable to open '%s'\n", str);
    return;
}
예제 #12
0
ESR_ReturnCode SR_NametagsLoadImpl(SR_Nametags* self, const LCHAR* filename)
{
  SR_NametagsImpl* impl = (SR_NametagsImpl*) self;
  ESR_ReturnCode rc;
  PFile* file = NULL;
  LCHAR line[256];
  LCHAR* result = NULL;
  LCHAR* id;
  LCHAR* value;
  SR_Nametag* newNametag = NULL;
  SR_Nametag* oldNametag;
  HashMap* nametags = impl->value;
  size_t size, len, i;
  LCHAR devicePath[P_PATH_MAX];
  LCHAR number[MAX_UINT_DIGITS+1];
#define NAMETAGID_LENGTH 20
  /* strlen("token\0") == 6 */
#define TOKEN_LENGTH 6 + NAMETAGID_LENGTH
  LCHAR tokenName[TOKEN_LENGTH];

  if (filename == NULL)
  {
    rc = ESR_INVALID_STATE;
    PLogError(ESR_rc2str(rc));
    goto CLEANUP;
  }
  size = P_PATH_MAX;
  CHKLOG(rc, ESR_SessionGetLCHAR(L("cmdline.nametagPath"), devicePath, &size));
  /* check if the filename has the path */
  if (LSTRNCMP(filename, devicePath, LSTRLEN(devicePath)) != 0)
    LSTRCAT(devicePath, filename);
  else
    LSTRCPY(devicePath, filename);
  file = pfopen ( devicePath, L("r"));
/*  CHKLOG(rc, PFileSystemCreatePFile(devicePath, ESR_TRUE, &file));
  CHKLOG(rc, file->open(file, L("r")));*/

  if ( file == NULL )
    goto CLEANUP;

  /* Flush collection */
  CHKLOG(rc, nametags->getSize(nametags, &size));
  for (i = 0; i < size; ++i)
  {
    CHKLOG(rc, nametags->getValueAtIndex(nametags, 0, (void **)&oldNametag));
    CHKLOG(rc, nametags->removeAtIndex(nametags, 0));
    CHKLOG(rc, oldNametag->destroy(oldNametag));
  }
  len = MAX_UINT_DIGITS + 1;
  CHKLOG(rc, lultostr(size, number, &len, 10));
  CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, L("removeCount"), number));

  while (ESR_TRUE)
  {
    result = pfgets ( line, 256, file );
    if (result == NULL)
      break;
    if (LSTRLEN(line) == 255)
    {
      rc = ESR_BUFFER_OVERFLOW;
      PLogError(ESR_rc2str(rc));
      goto CLEANUP;
    }
    lstrtrim(line);

    /* Get the Nametag ID */
    id = line;

    /* Find next whitespace */
    for (value = id + 1; *value != L('\0') && !LISSPACE(*value); ++value);
    if (*value == L('\0'))
    {
      rc = ESR_INVALID_STATE;
      PLogError(L("%s: Cannot find end of Nametag id"), ESR_rc2str(rc));
      goto CLEANUP;
    }
    /* Delimit end of nametag ID */
    *value = L('\0');

    /* Find next non-whitespace */
    for (++value; *value != L('\0') && LISSPACE(*value); ++value);
    if (*value == L('\0'))
    {
      rc = ESR_INVALID_STATE;
      PLogError(L("%s: Cannot find Nametag value"), ESR_rc2str(rc));
      goto CLEANUP;
    }

    /* We now have both the Nametag ID and value */
	len = (LSTRLEN(value)+1) * sizeof(LCHAR) ;
    CHKLOG(rc, SR_NametagCreateFromValue(id, (const char*)value, len, &newNametag));
    /* Add Nametag to collection */
    CHKLOG(rc, impl->value->put(impl->value, id, newNametag));

    if (LSTRLEN(id) > NAMETAGID_LENGTH)
    {
      rc = ESR_BUFFER_OVERFLOW;
      PLogError(ESR_rc2str(rc));
      goto CLEANUP;
    }
    psprintf(tokenName, L("nametag[%s]"), id);
    CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, tokenName, value));
    newNametag = NULL;
  }
  CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, L("filename"), filename));
  CHKLOG(rc, nametags->getSize(nametags, &size));
  len = MAX_UINT_DIGITS + 1;
  CHKLOG(rc, lultostr(size, number, &len, 10));
  CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, L("addCount"), number));
  CHKLOG(rc, SR_EventLogEvent_BASIC(impl->eventLog, impl->logLevel, L("SR_NametagsLoad")));
  pfclose (file);
  return ESR_SUCCESS;
CLEANUP:
  if (file != NULL)
    pfclose (file);
  if (newNametag != NULL)
    newNametag->destroy(newNametag);
  return rc;
}
예제 #13
0
ESR_ReturnCode SR_NametagsSaveImpl(SR_Nametags* self, const LCHAR* filename)
{
  SR_NametagsImpl* impl = (SR_NametagsImpl*) self;
  ESR_ReturnCode rc;
  PFile* file = NULL;
  size_t size, i;
  HashMap* nametags = impl->value;
  SR_NametagImpl* nametag;
  LCHAR* id;
  size_t len;
  LCHAR devicePath[P_PATH_MAX];
#define NAMETAG_LENGTH 200
  LCHAR nametagBuffer[NAMETAG_LENGTH];
  LCHAR number[MAX_UINT_DIGITS+1];
#define NAMETAGID_LENGTH 20
  /* "token\0" == 6 */
#define TOKEN_LENGTH 6 + NAMETAGID_LENGTH
  LCHAR tokenName[TOKEN_LENGTH];
  size_t num_written;

  if (filename == NULL)
  {
    rc = ESR_INVALID_STATE;
    PLogError(ESR_rc2str(rc));
    goto CLEANUP;
  }
  size = P_PATH_MAX;
  CHKLOG(rc, ESR_SessionGetLCHAR(L("cmdline.nametagPath"), devicePath, &size));

  if (LSTRNCMP(filename, devicePath, LSTRLEN(devicePath)) != 0)
    LSTRCAT(devicePath, filename);
  else
    LSTRCPY(devicePath, filename);

  file = pfopen ( devicePath, L("w"));
/*  CHKLOG(rc, PFileSystemCreatePFile(devicePath, ESR_TRUE, &file));
  CHKLOG(rc, file->open(file, L("w")));*/
  CHKLOG(rc, nametags->getSize(nametags, &size));

  if ( file == NULL )
    goto CLEANUP;

  for (i = 0; i < size; ++i)
  {
    CHKLOG(rc, nametags->getValueAtIndex(nametags, i, (void **)&nametag));

    CHKLOG(rc, nametag->Interface.getID(&nametag->Interface, &id));

    if (LSTRLEN(id) + 1 + LSTRLEN(nametag->value) + 2 >= NAMETAG_LENGTH)
    {
      rc = ESR_BUFFER_OVERFLOW;
      PLogError(ESR_rc2str(rc));
      goto CLEANUP;
    }
    psprintf(nametagBuffer, L("%s %s\n"), id, nametag->value);
    len = LSTRLEN(nametagBuffer);
/*    CHKLOG(rc, file->write(file, nametagBuffer, sizeof(LCHAR), &len));*/
    num_written = pfwrite ( nametagBuffer, sizeof ( LCHAR ), len, file );

    if ( num_written != len )
        goto CLEANUP;

    if (LSTRLEN(id) > NAMETAGID_LENGTH)
    {
      rc = ESR_BUFFER_OVERFLOW;
      PLogError(ESR_rc2str(rc));
      goto CLEANUP;
    }
    psprintf(tokenName, L("nametag[%s]"), id);
    CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, tokenName, nametag->value));
  }
  CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, L("filename"), filename));
  len = MAX_UINT_DIGITS + 1;
  CHKLOG(rc, lultostr(size, (LCHAR*) &number, &len, 10));
  CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, L("saveCount"), number));
  CHKLOG(rc, SR_EventLogEvent_BASIC(impl->eventLog, impl->logLevel, L("SR_NametagsSave")));
  pfclose (file);
  return ESR_SUCCESS;
CLEANUP:
  if (file != NULL)
    pfclose (file);
  return rc;
}
예제 #14
0
ESR_ReturnCode SR_EventLogCreate(SR_EventLog** self)
{
  SR_EventLogImpl *impl, *any_existing_eventlog;
  ESR_ReturnCode rc;
  LCHAR* dataCaptureDir;
#define TIMESTAMP_LENGTH 18
  LCHAR timeStr[TIMESTAMP_LENGTH];
  struct tm *ct, ct_r;
  PTimeStamp timestamp;
#ifdef ANDROID
  struct timeval dir_stamp;
#endif

  if (self == NULL)
  {
    PLogError(L("ESR_INVALID_ARGUMENT"));
    return ESR_INVALID_ARGUMENT;
  }

  any_existing_eventlog = NULL;
  rc = ESR_SessionGetProperty(L("eventlog"), (void **)&any_existing_eventlog, TYPES_SR_EVENTLOG);
  if (rc == ESR_SUCCESS && any_existing_eventlog)
  {
    *self = (SR_EventLog*)any_existing_eventlog;
    PLogError("eventlog was already created");
    return ESR_SUCCESS;
  }

  impl = NEW(SR_EventLogImpl, MTAG);
  if (impl == NULL)
  {
    PLogError(L("ESR_OUT_OF_MEMORY"));
    return ESR_OUT_OF_MEMORY;
  }

  impl->Interface.destroy = &SR_EventLog_Destroy;
  impl->Interface.event = &SR_EventLog_Event;
  impl->Interface.token = &SR_EventLog_Token;
  impl->Interface.tokenInt = &SR_EventLog_TokenInt;
  impl->Interface.tokenPointer = &SR_EventLog_TokenPointer;
  impl->Interface.tokenUint16_t = &SR_EventLog_TokenUint16_t;
  impl->Interface.tokenSize_t = &SR_EventLog_TokenSize_t;
  impl->Interface.tokenBool = &SR_EventLog_TokenBool;
  impl->Interface.tokenFloat = &SR_EventLog_TokenFloat;
  impl->Interface.eventSession = &SR_EventLogEventSessionImpl;
  impl->Interface.audioOpen = &SR_EventLog_AudioOpen;
  impl->Interface.audioClose = &SR_EventLog_AudioClose;
  impl->Interface.audioWrite = &SR_EventLog_AudioWrite;
  impl->Interface.audioGetFilename = &SR_EventLog_AudioGetFilename;
  impl->sessionListenerPair.data = NULL;
  impl->sessionListenerPair.listener = &impl->sessionListener;
  impl->sessionListener.propertyChanged = &propertyChanged;
  impl->waveformCounter = 0;
  impl->logFile = NULL;
  impl->tokenBuf[0] = 0;
  impl->logFile_state = NO_FILE;
  impl->logLevel = 0;
  impl->waveformFile = NULL;
  LSTRCPY(impl->logFilename, L(""));

  CHKLOG(rc, ESR_SessionSetProperty(L("eventlog"), impl, TYPES_SR_EVENTLOG));
  rc = ESR_SessionGetSize_t(L("SREC.Recognizer.osi_log_level"), &impl->logLevel);
  if (rc == ESR_NO_MATCH_ERROR)
  {
    impl->logLevel = 7;
    CHKLOG(rc, ESR_SessionSetSize_t(L("SREC.Recognizer.osi_log_level"), impl->logLevel));
  }
  else if (rc != ESR_SUCCESS)
  {
    PLogError(ESR_rc2str(rc));
    goto CLEANUP;
  }

  if (impl->logLevel > 0)
  {
    CHKLOG(rc, ESR_SessionGetProperty(L("cmdline.DataCaptureDirectory"), (void**) &dataCaptureDir, TYPES_PLCHAR));

    LSTRCPY(impl->logFilename, dataCaptureDir);
#ifdef ANDROID
/*
 * The existing functions did not work on the desired platform, hence this code for the device.
 */
    gettimeofday ( &dir_stamp, NULL );
    sprintf(timeStr, "%lu", (unsigned long) dir_stamp.tv_sec );
#else
    PTimeStampSet(&timestamp);
    ct = localtime_r(&timestamp.secs, &ct_r);
    sprintf(timeStr, "%04d%02d%02d%02d%02d%02d",
            ct->tm_year + 1900, ct->tm_mon + 1, ct->tm_mday, ct->tm_hour,
            ct->tm_min, ct->tm_sec);
#endif
    /* create capture directory if it doesn't already exist */
    rc = pf_make_dir (impl->logFilename);
    if (rc != ESR_SUCCESS && rc != ESR_IDENTIFIER_COLLISION)
    {
      PLogError(ESR_rc2str(rc));
      goto CLEANUP;
    }

    /* create the directory for today's log if it doesn't already exist */
    LSTRCAT(impl->logFilename, L("/"));
    LSTRCAT(impl->logFilename, timeStr);
/*
 * There used to be a while forever loop here with a break, but that caused an infinite loop
 * for the customer. With 1 second resolution, a pre-existing directory probably means a bug.
 * It's not worth trying to handle this.
 */
    rc = pf_make_dir (impl->logFilename);
    if (rc != ESR_SUCCESS)
    {
      PLogError(ESR_rc2str(rc));
      goto CLEANUP;
    }

    /* create the log file */
    LSTRCAT(impl->logFilename, L("/SWIevent-"));
    LSTRCAT(impl->logFilename, timeStr);
    LSTRCAT(impl->logFilename, L(".log"));

    impl->logFile = pfopen ( impl->logFilename, L("w") );
/*    CHKLOG(rc, PFileSystemCreatePFile(impl->logFilename, ESR_TRUE, &impl->logFile));
    CHKLOG(rc, PFileOpen(impl->logFile, L("w")));*/

    if ( impl->logFile != NULL )
        impl->logFile_state = FILE_OK;
    else
        goto CLEANUP;
  }

  *self = (SR_EventLog*) impl;
  return ESR_SUCCESS;
CLEANUP:
  if (impl->logFile)
    pfclose (impl->logFile);
  return rc;
}
예제 #15
0
파일: run.c 프로젝트: Macaulay2/Singular
/* process exec_arg : if it
 * NATIVE:
 *  1) starts with '\\' or '/', it's a root-path and leave it alone
 *  2) starts with 'x:\\' or 'x:/', it's a root-path and leave it alone
 *  3) starts with '.\\' or './', two possible meanings:
 *       1) exec is in the current directory
 *       2) exec in same directory as this program
 *  4) otherwise, search path (and _prepend_ "." to the path!!!)
 *  5) convert all '/' to '\\'
 * CYGWIN
 *  1) starts with '\\' or '/', it's a root-path and leave it alone
 *  2) starts with 'x:\\' or 'x:/', it's a root-path and leave it alone
 *  3) starts with '.\\' or './', two possible meanings:
 *       1) exec is in the current directory
 *       2) exec in same directory as this program
 *  4) otherwise, search path (and _prepend_ "." to the path!!!)
 *  5) convert to cygwin-style path to resolve symlinks within the pathspec
 *  6) check filename: if it's a symlink, resolve it by peeking inside
 *  7) convert to win32-style path+filename since we're using Windows 
 *       createProcess() to launch
 */
void process_execname(char *exec, const char* execname,const char* execpath )
{
   char* orig_pathlist;
   char* pathlist;
   char exec_tmp[MAX_PATH + FILENAME_MAX + 100];
   char exec_tmp2[MAX_PATH + FILENAME_MAX + 100];
   char buf[MAX_PATH + FILENAME_MAX + 100];
   int i,j;

   int len = 0;
   /* 
    * STARTS WITH / or \ 
    * execpath NOT used
    */
   if ((execname[0] == '\\') || (execname[0] == '/'))
   {
#if defined(__CYGWIN__)
      strcpy(exec_tmp,execname);
#else    
      exec_tmp[0] = ((char) (_getdrive() + ((int) 'A') - 1));
      exec_tmp[1] = ':';
      exec_tmp[2] = '\0';
      strcat(exec_tmp,execname);
#endif
      Trace(("/ -\nexec_tmp\t%s\nexecname\t%s\nexecpath\t%s\n",
             exec_tmp,execname,execpath));
      if (! fileExistsMulti(exec_tmp2,NULL,exec_tmp,exts,NUM_EXTENSIONS) )
      {
          j = 0;
          for (i = 0; i < NUM_EXTENSIONS; i++)
              j += sprintf(buf + j," [%d]: %s\n",i+1,exts[i]);
          error("Couldn't locate %s\nI tried appending the following "
                "extensions: \n%s",exec_tmp,buf);
      }
      Trace((exec_tmp2));
   }
   /* 
    * STARTS WITH x:\ or x:/
    * execpath NOT used
    */
    else if ((strlen(execname) > 3) && // avoid boundary errors
       (execname[1] == ':') &&
       ((execname[2] == '\\') || (execname[2] == '/')))
   {
      strcpy(exec_tmp,execname);       
      Trace(("x: -\nexec_tmp\t%s\nexecname\t%s\nexecpath\t%s\n",
             exec_tmp,execname,execpath));
      if (! fileExistsMulti(exec_tmp2,NULL,exec_tmp,exts,NUM_EXTENSIONS) )
      {
          j = 0;
          for (i = 0; i < NUM_EXTENSIONS; i++)
              j += sprintf(buf + j," [%d]: %s\n",i+1,exts[i]);
          error("Couldn't locate %s\nI tried appending the following "
                "extensions: \n%s",exec_tmp,buf);
      }
      Trace((exec_tmp2));
   }
   /* 
    * STARTS WITH ./ or .\
    */
   else if ((execname[0] == '.') &&
            ((execname[1] == '\\') || (execname[1] == '/')))
   {
      if (((char*) getcwd(exec_tmp,MAX_PATH))==NULL)
         error("can't find current working directory");
      if (! fileExistsMulti(exec_tmp2,exec_tmp,&(execname[2]),
                            exts,NUM_EXTENSIONS) )
          if (! fileExistsMulti(exec_tmp2,execpath,&(execname[2]),
                                exts,NUM_EXTENSIONS) )
          {
              j = 0;
              for (i = 0; i < NUM_EXTENSIONS; i++)
                  j += sprintf(buf + j," [%d]: %s\n",i+1,exts[i]);
              error("Couldn't locate %s\n"
                    "I looked in the following directories:\n [1]: %s\n [2]: %s\n"
                    "I also tried appending the following "
                    "extensions: \n%s",execname,exec_tmp,execpath,buf);
          }
      Trace((exec_tmp2));
   }
   /*
    * OTHERWISE, SEARCH PATH (prepend '.' and run.exe's directory)
    * can't use fileExistsMulti because we want to search entire path
    * for exts[0], then for exts[1], etc.
    */
   else
   {
      orig_pathlist = getenv("PATH");
      if ((pathlist = malloc (strlen(orig_pathlist)
                              + strlen(".") 
                              + strlen(execpath)+ 3)) == NULL)
         error("internal error - out of memory");
      strcpy(pathlist,".");
      strcat(pathlist,SEP_CHARS);
      strcat(pathlist,execpath);
      strcat(pathlist,SEP_CHARS);
      strcat(pathlist,orig_pathlist);

      Trace((pathlist));
      for (i = 0; i < NUM_EXTENSIONS; i++)
      {
          strcpy(exec_tmp,execname);
          strcat(exec_tmp,exts[i]);
          pfopen(exec_tmp2,exec_tmp,pathlist);
          if (fileExists(NULL,NULL,exec_tmp2))
              break;
          exec_tmp2[0] = '\0';
      }
      Trace(("exec_tmp\t%s\npathlist\t%s\n",exec_tmp2,pathlist));

      free(pathlist);
      if (exec_tmp2[0] == '\0')
      {
          j = 0;
          for (i = 0; i < NUM_EXTENSIONS; i++)
              j += sprintf(buf + j," [%d]: %s\n",i+1,exts[i]);
          error("Couldn't find %s anywhere.\n"
                "I even looked in the PATH \n"
                "I also tried appending the following "
                "extensions: \n%s",execname,buf);
      }
   }
/*
 * At this point, we know that exec_tmp2 contains a filename
 * and we know that exec_tmp2 exists.
 */
#if defined(__CYGWIN__)
   {
      struct stat stbuf;
      char sym_link_name[MAX_PATH+1];
      char real_name[MAX_PATH+1];
      char dummy[MAX_PATH+1];

      strcpy(exec_tmp,exec_tmp2);

      CYGWIN_CONV_TO_POSIX_PATH((exec_tmp,sym_link_name));
      Trace((sym_link_name));
      
      if (si_lstat(sym_link_name, &stbuf) == 0)
      {
         if ((stbuf.st_mode & S_IFLNK) == S_IFLNK)
         {
	    if (readlink(sym_link_name, real_name, sizeof(real_name)) == -1)
               error("problem reading symbolic link for %s",exec_tmp);
            else
            {
                // if realname starts with '/' it's a rootpath 
                if (real_name[0] == '/')
                    strcpy(exec_tmp2,real_name);
                else // otherwise, it's relative to the symlink's location
                {
                   CYGWIN_SPLIT_PATH((sym_link_name,exec_tmp2,dummy));
                   if (!endsWith(exec_tmp2,PATH_SEP_CHAR_STR))
                      strcat(exec_tmp2,PATH_SEP_CHAR_STR);
                   strcat(exec_tmp2,real_name);
                }
            }
         }
         else /* NOT a symlink */
            strcpy(exec_tmp2, sym_link_name);
      }
      else
         error("can't locate executable - %s",sym_link_name);
   }
   CYGWIN_CONV_TO_FULL_WIN32_PATH((exec_tmp2,exec));
#else					
   strcpy (exec, exec_tmp2);
#endif  
}
예제 #16
0
int main(int argc, char **argv)
{
  LCHAR phrase[MAX_LINE_LENGTH];
  SR_Vocabulary *vocab = 0;
  LCHAR vocabfile[MAX_LINE_LENGTH];
  LCHAR outfilename[MAX_LINE_LENGTH];
  LCHAR testfilename[MAX_LINE_LENGTH];
  LCHAR parfilename[MAX_LINE_LENGTH];
  LCHAR wordfile[MAX_LINE_LENGTH];
  LCHAR locale[MAX_LINE_LENGTH];
  LCHAR ptemp[MAX_LINE_LENGTH];
  LCHAR* p;
  ESR_ReturnCode rc;
  int i;
  PFile* fin = 0;
  FILE* fout = stdout;
  size_t len;
  ESR_BOOL bSession = ESR_FALSE;

  LCHAR *env_sdk_path;
  LCHAR *env_lang;

  CHKLOG(rc, PMemInit());
/*  CHKLOG(rc, PFileSystemCreate());
    CHKLOG(rc, PANSIFileSystemCreate());
    CHKLOG(rc, PANSIFileSystemAddPath(L("/dev/ansi"), L("/")));*/

    /* Set ANSI file-system as default file-system */
/*  CHKLOG(rc, PANSIFileSystemSetDefault(ESR_TRUE));*/
    /* Set virtual current working directory to native current working directory */
/*  len = P_PATH_MAX;
    CHKLOG(rc, PANSIFileSystemGetcwd(cwd, &len));
    CHKLOG(rc, PFileSystemChdir(cwd));*/

    fout = stdout;
  *vocabfile = 0;
  *wordfile = 0;
  *locale = 0;
  *outfilename = 0;
  *testfilename = 0;
  *parfilename = 0;

  /* get some phrases from the user */
  LPRINTF("\nDictation Test Program for esr (Nuance Communications, 2007)\n");

  if(argc != 1 && argc != 3 && argc != 5 && argc != 7 && argc != 9)
  {
    usage();
        rc = 1;
    goto CLEANUP;
  }

  for(i=1; i<argc; i++)
  {
    if(!LSTRCMP(argv[i], L("-words")))
      LSTRCPY(wordfile, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-vocab")))
      LSTRCPY(vocabfile, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-locale")))
      LSTRCPY(locale, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-out")))
      LSTRCPY(outfilename, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-itest")))
      LSTRCPY(testfilename, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-parfile")) || !LSTRCMP(argv[i], L("-par")) )
      LSTRCPY(parfilename, argv[++i]);
    else {
      usage();
      rc = 1;
      goto CLEANUP;
    }
  }

  if ( *parfilename == L('\0') )
  {
    LPRINTF ( "Warning: No parfile defined in the command line.\n" );
    LPRINTF ( "Looking for the default parfile, $ESRSDK/config/$ESRLANG/baseline.par...\n" );

    env_sdk_path =  LGETENV(L("ESRSDK"));
    if ( env_sdk_path != NULL )
    {
      LSPRINTF ( parfilename, L("%s/config/"), env_sdk_path );
      env_lang = LGETENV(L("ESRLANG"));
      if ( env_lang != NULL )
      {
         LSTRCAT ( parfilename, env_lang );
         LSTRCAT ( parfilename, L("/baseline.par") );
      }
      else
      {
        LPRINTF("Error: An environment variable ESRLANG should be defined.\n");
        goto CLEANUP;
      }
    }
    else
    {
      LPRINTF("Error: An environment variable ESRSDK should be defined.\n");
      goto CLEANUP;
    }
  }

  rc = InitSession( parfilename );
  if ( rc != ESR_SUCCESS )
  {
    LPRINTF("Error: %s\n", ESR_rc2str(rc));
    goto CLEANUP;
  }
  bSession = ESR_TRUE;

  if (*vocabfile == 0)
  {
    len = sizeof(vocabfile);
    rc = ESR_SessionGetLCHAR ( L("cmdline.vocabulary"), vocabfile, &len );
    env_sdk_path =  LGETENV(L("ESRSDK"));
    if ( env_sdk_path != NULL )
      {
	LSPRINTF ( parfilename, L("%s/config/"), env_sdk_path );
	env_lang = LGETENV(L("ESRLANG"));
	if ( env_lang != NULL )
	  {
	    LSTRCAT ( parfilename, env_lang );
	    LSTRCAT ( parfilename, L("/baseline.par") );
	  }
	else
	  {
	    LPRINTF("Error: An environment variable ESRLANG should be defined.\n");
	    goto CLEANUP;
	  }
      }
    else
      {
	LPRINTF("Error: An environment variable ESRSDK should be defined.\n");
	goto CLEANUP;
      }

    strcpy(ptemp, env_sdk_path);
    strcat(ptemp,"/config/");
    strcat(ptemp,env_lang);
    strcat(ptemp,"/");
    strcat(ptemp,vocabfile);
    strcpy(vocabfile,ptemp);
    if ( rc == ESR_SUCCESS )
    {
      len = sizeof(vocabfile);
       rc = ESR_SessionPrefixWithBaseDirectory(vocabfile, &len);
    }
    else
    {
       *vocabfile = 0;
    }
  }

  if (*vocabfile)
    rc = SR_VocabularyLoad(vocabfile, &vocab);
  else if (*locale)
  {
    ESR_Locale localeTag;

    rc = ESR_str2locale(locale, &localeTag);
    if (rc != ESR_SUCCESS)
    {
      LPRINTF("Error: %s\n",ESR_rc2str(rc));
      goto CLEANUP;
    }
    rc = SR_VocabularyCreate(localeTag, &vocab);
  }
  else
    rc = SR_VocabularyCreate(ESR_LOCALE_EN_US, &vocab);

  if (rc != ESR_SUCCESS)
  {
    LPRINTF("Error: %s\n",ESR_rc2str(rc));
    goto CLEANUP;
  }

  if (*outfilename) /* output file */
  {
    if  ((fout = fopen(outfilename,"w")) == NULL)
    {
      LPRINTF("Could not open file: %s\n",outfilename);
      rc = 1;
      goto CLEANUP;
    }
  }

  if (*wordfile) /* file mode */
  {
    if ((fin = pfopen(wordfile,"r")) == NULL)
    {
      LPRINTF("Could not open file: %s\n", wordfile);
      goto CLEANUP;
    }
    while (pfgets(phrase, MAX_LINE_LENGTH, fin)!=NULL)
    {
      lstrtrim(phrase);
      doGetProns(vocab, phrase, MAX_PRONS_LENGTH, fout);
    }

  }
  else if (*testfilename) /* test file mode */
  {
    if ((fin = pfopen(testfilename,"r")) == NULL)
    {
      LPRINTF("Could not open file: %s\n", testfilename);
      rc = 1;
      goto CLEANUP;
    }
    doInputTestPhonemes(vocab, fin, fout);
  }
  else /* interactive mode */
  {
    LPRINTF("'qqq' to quit\n");
    while (ESR_TRUE)
    {
      LPRINTF("> ");
      if(! pfgets(phrase, MAX_LINE_LENGTH, PSTDIN ))
        break;
      // remove trailing whitespace
      for(p=&phrase[0]; *p!=0 && *p!='\n' && *p!='\r'; p++) {}
      *p=0;
      lstrtrim(phrase);
      if(!LSTRCMP("qqq",phrase))
        break;
      else
        doGetProns(vocab, phrase, MAX_PRONS_LENGTH, fout);
     }
  }

CLEANUP:
  if(vocab)
    vocab->destroy(vocab);

  if(bSession)
    ShutdownSession();

  if(fin)
    pfclose(fin);

  if(fout && fout != stdout)
    fclose(fout);

/*  PANSIFileSystemDestroy();
  PFileSystemDestroy();*/
  PMemShutdown();
  return rc;
}