Exemple #1
0
int main( int argc, char *argv[]) {
    int c = 0;
    int ret_val = 0;
    int port = 0;
    char network[128];
    char *file = NULL;
    char *iface = NULL;
    char *mcast_addr = NULL;
    int bfd = 0;
    network[0] = '\0';

#ifdef UDPTEST
    int sockfd = 0;
#else
    pgm_error_t* pgm_err = NULL;
    pgm_sock_t *pgm_sock;
    pthread_t nak_thread;
#endif

    while((c = getopt(argc, argv, ":hm:i:p:f:")) != -1) {
        switch (c) {
        case 'm':
            mcast_addr = optarg;
            break;
        case 'i':
            iface = optarg;
            break;
        case 'p':
            port = atoi(optarg);
            break;
        case 'h':
        case '?':
            print_usage();
            break;
        default:
            print_usage();
            break;
        }
    }

    if(optind != argc-1) {
        PRINT_ERR("Please provide the path to a file you want to send!");
        ret_val = -1;
        goto ret_error;
    } else {
        file = argv[optind];
    }

    if (iface) {
        char *ifaddr = pftp_inet_iftoa(iface);
        if (strlen(ifaddr) > 0) {
            strncat(network, ifaddr, 128);
            strncat(network, ";", 128);
        }
    }

    if (mcast_addr) {
        strncat(network, mcast_addr, 128);
    } else {
        strncat(network, PFTP_DEFAULT_MCAST_ADDR, 128);
    }

#ifdef UDPTEST
    struct sockaddr_in servaddr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr(PFTP_DEFAULT_MCAST_ADDR);
    servaddr.sin_port = port ? htons(port) : htons(PFTP_UDP_PORT);
#else

    if (0 != pftp_create(1, network, port, &pgm_sock)) {
        ret_val = -1;
        goto ret_error;
    }

    int pgm_status;

    /* Start NAK receiver thread */
    m_run_receiver = 1;
    pthread_create(&nak_thread, NULL, nak_routine, (void*)pgm_sock);
#endif

    char buf[PGMBUF_SIZE];
    buf[0] = '\0';

    struct stat fstat;
    if (-1 == stat(file, &fstat)) {
        PRINT_ERR("Couldn't stat file: %s", strerror(errno));
        ret_val = -1;
        goto ret_error;
    }

    char *fname = strrchr(file, '/');
    if (!fname) {
        fname = file;
    } else {
        fname = fname+1;
    }

    memset(buf, 0, PGMBUF_SIZE);
    snprintf(buf, PGMBUF_SIZE, CMD_SEND_FILE" %ld %s", fstat.st_size, fname);
    PRINT_DBG("Sending file with command: %s", buf);

    size_t bytes_written;
    int bytes_read;

#ifdef UDPTEST
    bytes_written = sendto(sockfd, buf, strlen(buf)+1, 0, (struct sockaddr*)&servaddr, sizeof(servaddr));
    if (bytes_written != strlen(buf)+1) {
        PRINT_ERR("Couldn't send file transfer command! %s", strerror(errno));
        ret_val = -1;
        goto ret_error;
    }
#else
    pgm_status = pgm_status = pgm_send(pgm_sock, buf, strlen(buf)+1, &bytes_written);
    if (pgm_status != PGM_IO_STATUS_NORMAL) {
        PRINT_ERR("Couldn't send file transfer command!");
        ret_val = -1;
        goto ret_error;
    }
#endif

    bfd = open(file, O_RDONLY);
    if (bfd < 0) {
        PRINT_ERR("Couldn't open file for reading! %s", strerror(errno));
        ret_val = -1;
        goto ret_error;
    }

    int fds = 0;
    fd_set writefds;
    fd_set readfds;

    bytes_read = read(bfd, buf, PGMBUF_SIZE);
    while (bytes_read > 0) {

#ifdef UDPTEST

        bytes_written = sendto(sockfd, buf, bytes_read, 0, (struct sockaddr*)&servaddr, sizeof(servaddr));

#else
        struct timeval tv;
        pgm_status = pgm_send(pgm_sock, buf, bytes_read, &bytes_written);

        //PRINT_DBG("pgm_status: %d", pgm_status);

        switch (pgm_status) {

        case PGM_IO_STATUS_NORMAL :
        {
#endif
            if (bytes_written != bytes_read) {
                PRINT_ERR("Error sending file!");
                ret_val = -1;
                goto ret_error;
            }
            bytes_read = read(bfd, buf, PGMBUF_SIZE);

#ifdef UDPTEST
            struct timespec ts = {0, 35000};
            nanosleep(&ts, NULL);
#else
        } break;
        case PGM_IO_STATUS_TIMER_PENDING:
        {
            socklen_t optlen = sizeof(tv);
            pgm_getsockopt (pgm_sock, IPPROTO_PGM, PGM_TIME_REMAIN, &tv, &optlen);
            if (0 == (tv.tv_sec * 1000) + ((tv.tv_usec + 500) / 1000))
                break;
            goto block;
        }
        case PGM_IO_STATUS_RATE_LIMITED :
        {
            socklen_t optlen = sizeof(tv);
            pgm_getsockopt (pgm_sock, IPPROTO_PGM, PGM_RATE_REMAIN, &tv, &optlen);
            if (0 == (tv.tv_sec * 1000) + ((tv.tv_usec + 500) / 1000))
                break;
            /* No accidental fallthrough! */
        }
        case PGM_IO_STATUS_CONGESTION :
        case PGM_IO_STATUS_WOULD_BLOCK :
block:
        {
            FD_ZERO(&writefds);
            pgm_select_info(pgm_sock, NULL, &writefds, &fds);
            fds = select(fds, NULL, &writefds, NULL, pgm_status == PGM_IO_STATUS_WOULD_BLOCK ? NULL : &tv);
        } break;
        default:
            PRINT_ERR("Send error!");
            ret_val = -1;
            goto ret_error;
            break;
        }
#endif
    }

#ifndef UDPTEST
    pthread_mutex_lock(&m_pftp_mutex);
    m_run_receiver = 0;
    pthread_mutex_unlock(&m_pftp_mutex);
    pthread_join(nak_thread, NULL);
    pthread_mutex_destroy(&m_pftp_mutex);
#endif

    goto ret_good;

ret_error:
    PRINT_DBG("Exit error");
    goto ret;
ret_good:
    PRINT_DBG("Exit good");
ret:
    if (bfd > 0)
        close(bfd);
#ifdef UDPTEST
    if (sockfd > 0)
        close(sockfd);
#else
    if (pgm_sock) {
        pftp_stop(pgm_sock);
    }
#endif
    return ret_val;
}
Exemple #2
0
Inform& Inform::operator<<(int i) {
  char tmpbuf[128];
  sprintf(tmpbuf, "%d", i);
  strncat(buf, tmpbuf, MAX_MSG_SIZE - strlen(buf));
  return *this;
}
Exemple #3
0
Inform& Inform::operator<<(double d) {
  char tmpbuf[128];
  sprintf(tmpbuf, "%f", d);
  strncat(buf, tmpbuf, MAX_MSG_SIZE - strlen(buf));
  return *this;
}
const char *
get_optional_features(void)
{
    static char features[1024];
    unsigned int numfeatures = 0;

    snprintf(features, sizeof(features), "Optional features available: ");

#if defined(HAVE_CPU_AFFINITY)
    if (numfeatures > 0) {
	strncat(features, ", ", 
		sizeof(features) - strlen(features) - 1);
    }
    strncat(features, "CPU affinity setting", 
	sizeof(features) - strlen(features) - 1);
    numfeatures++;
#endif /* HAVE_CPU_AFFINITY */
    
#if defined(HAVE_FLOWLABEL)
    if (numfeatures > 0) {
	strncat(features, ", ", 
		sizeof(features) - strlen(features) - 1);
    }
    strncat(features, "IPv6 flow label", 
	sizeof(features) - strlen(features) - 1);
    numfeatures++;
#endif /* HAVE_FLOWLABEL */
    
#if defined(HAVE_SCTP)
    if (numfeatures > 0) {
	strncat(features, ", ", 
		sizeof(features) - strlen(features) - 1);
    }
    strncat(features, "SCTP", 
	sizeof(features) - strlen(features) - 1);
    numfeatures++;
#endif /* HAVE_SCTP */
    
#if defined(HAVE_TCP_CONGESTION)
    if (numfeatures > 0) {
	strncat(features, ", ", 
		sizeof(features) - strlen(features) - 1);
    }
    strncat(features, "TCP congestion algorithm setting", 
	sizeof(features) - strlen(features) - 1);
    numfeatures++;
#endif /* HAVE_TCP_CONGESTION */
    
#if defined(HAVE_SENDFILE)
    if (numfeatures > 0) {
	strncat(features, ", ",
		sizeof(features) - strlen(features) - 1);
    }
    strncat(features, "sendfile / zerocopy",
	sizeof(features) - strlen(features) - 1);
    numfeatures++;
#endif /* HAVE_SENDFILE */

    if (numfeatures == 0) {
	strncat(features, "None", 
		sizeof(features) - strlen(features) - 1);
    }

    return features;
}
Exemple #5
0
static void
show_fstat_error (void)
{	static const char *filename = "fstat.dat" ;
	static char data [256] ;

	STATBUF 	statbuf ;
	int fd, mode, flags ;

	if (sizeof (statbuf.st_size) != sizeof (INT64))
	{	printf ("\n\nLine %d: Error, sizeof (statbuf.st_size) != 8.\n\n", __LINE__) ;
		return ;
	} ;

	puts ("\n64 bit fstat() test.\n--------------------") ;

	printf ("0) Create a file, write %d bytes and close it.\n", SIGNED_SIZEOF (data)) ;
	mode = O_WRONLY | O_CREAT | O_TRUNC | O_BINARY ;
	flags = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH ;
	if ((fd = open (filename, mode, flags)) < 0)
	{	printf ("\n\nLine %d: open() failed : %s\n\n", __LINE__, strerror (errno)) ;
		return ;
	} ;
	assert (write (fd, data, sizeof (data)) > 0) ;
	close (fd) ;

	printf ("1) Re-open file in read/write mode and write another %d bytes at the end.\n", SIGNED_SIZEOF (data)) ;
	mode = O_RDWR | O_BINARY ;
	flags = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH ;
	if ((fd = open (filename, mode, flags)) < 0)
	{	printf ("\n\nLine %d: open() failed : %s\n\n", __LINE__, strerror (errno)) ;
		return ;
	} ;
	LSEEK (fd, 0, SEEK_END) ;
	assert (write (fd, data, sizeof (data)) > 0) ;

	printf ("2) Now use system (\"%s %s\") to show the file length.\n\n", dir_cmd, filename) ;

	/* Would use snprintf, but thats not really available on windows. */
	memset (data, 0, sizeof (data)) ;
	strncpy (data, dir_cmd, sizeof (data) - 1) ;
	strncat (data, " ", sizeof (data) - 1 - strlen (data)) ;
	strncat (data, filename, sizeof (data) - 1 - strlen (data)) ;

	assert (system (data) >= 0) ;
	puts ("") ;

	printf ("3) Now use fstat() to get the file length.\n") ;
	if (FSTAT (fd, &statbuf) != 0)
	{	printf ("\n\nLine %d: fstat() returned error : %s\n", __LINE__, strerror (errno)) ;
		return ;
	} ;

	printf ("4) According to fstat(), the file length is %ld, ", (long) statbuf.st_size) ;

	close (fd) ;

	if (statbuf.st_size != 2 * sizeof (data))
		printf ("but thats just plain ***WRONG***.\n\n") ;
	else
	{	printf ("which is correct.\n\n") ;
		unlink (filename) ;
	} ;

} /* show_fstat_error */
Exemple #6
0
int
main(int argc, char **argv) {
    int status;
    rodsEnv myEnv;
    rErrMsg_t errMsg;
    rcComm_t *conn;
    rodsArguments_t myRodsArgs;
    char *optStr;
    rodsPathInp_t rodsPathInp;
    int i, nArgs;
    modAccessControlInp_t modAccessControl;
    char userName[NAME_LEN];
    char zoneName[NAME_LEN];
    int doingInherit;
    char rescAccessLevel[LONG_NAME_LEN];
    char adminModeAccessLevel[LONG_NAME_LEN];

    optStr = "RrhvVM";
   
    status = parseCmdLineOpt (argc, argv, optStr, 0, &myRodsArgs);
    if (status) {
       printf("Use -h for help\n");
       exit(1);
    }
    if (myRodsArgs.help==True) {
       usage();
       exit(0);
    }

    if (status < 0) {
        rodsLogError (LOG_ERROR, status, "main: parseCmdLineOpt error. ");
	printf("Use -h for help\n");
        exit (2);
    }

    nArgs = argc - myRodsArgs.optind;

    if (nArgs < 2) {usage(); exit(3);}

    status = getRodsEnv (&myEnv);

    if (status < 0) {
        rodsLogError(LOG_ERROR, status, "main: getRodsEnv error. ");
        exit (3);
    }

    optind=myRodsArgs.optind + 2;
    doingInherit=0;
    if (strcmp(argv[myRodsArgs.optind], ACCESS_INHERIT) == 0 ||
	strcmp(argv[myRodsArgs.optind], ACCESS_NO_INHERIT) == 0 ) {
       doingInherit=1;
       optind=myRodsArgs.optind + 1;
    }

    status = parseCmdLinePath (argc, argv, optind, &myEnv,
      UNKNOWN_OBJ_T, NO_INPUT_T, 0, &rodsPathInp);

    if (status < 0) {
        rodsLogError (LOG_ERROR, status, "main: parseCmdLinePath error. ");
	usage ();
        exit (4);
    }

    conn = rcConnect (myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName,
      myEnv.rodsZone, 0, &errMsg);

    if (conn == NULL) {
        exit (5);
    }
   
    status = clientLogin(conn);
    if (status != 0) {
        rcDisconnect(conn);
        exit (6);
    }

    modAccessControl.recursiveFlag = myRodsArgs.recursive;
    modAccessControl.accessLevel = argv[myRodsArgs.optind];

    if (doingInherit) {
       modAccessControl.userName = "";
       modAccessControl.zone = "";
    }
    else {
       status = parseUserName(argv[myRodsArgs.optind+1], userName, zoneName);
       if (status != 0) {
	  printf("Invalid iRODS user name format: %s\n",
		 argv[myRodsArgs.optind+1]);
	  exit(7);
       }
    }
    modAccessControl.userName = userName;
    modAccessControl.zone = zoneName;
    for (i = 0; i < rodsPathInp.numSrc && status==0; i++) {
       if (rodsPathInp.numSrc > 1 && myRodsArgs.verbose!=0) {
	  printf("path %s\n",rodsPathInp.srcPath[i].outPath);
       }
       modAccessControl.path = rodsPathInp.srcPath[i].outPath;

       if (myRodsArgs.resource) {
	  strncpy(rescAccessLevel, MOD_RESC_PREFIX, LONG_NAME_LEN);
	  strncat(rescAccessLevel, argv[myRodsArgs.optind], LONG_NAME_LEN);
	  modAccessControl.accessLevel = rescAccessLevel; /* indicate resource*/
	  modAccessControl.path = argv[optind]; /* just use the plain name */
       }
       if (myRodsArgs.admin && i==0) {    /* admin mode, add indicator */
	  strncpy(adminModeAccessLevel, MOD_ADMIN_MODE_PREFIX, LONG_NAME_LEN);
	  strncat(adminModeAccessLevel, modAccessControl.accessLevel,
		  LONG_NAME_LEN);
	  modAccessControl.accessLevel = adminModeAccessLevel;
       }
       status = rcModAccessControl(conn, &modAccessControl);
       if (status < 0) {
	  rodsLogError(LOG_ERROR, status, "rcModAccessControl failure %s",
		       errMsg.msg);
	  if (conn->rError) {
	     rError_t *Err;
	     rErrMsg_t *ErrMsg;
	     int i, len;
	     Err = conn->rError;
	     len = Err->len;
	     for (i=0;i<len;i++) {
		ErrMsg = Err->errMsg[i];
		rodsLog(LOG_ERROR, "Level %d: %s",i, ErrMsg->msg);
	     }
	  }
       }
    }

    printErrorStack(conn->rError);

    rcDisconnect(conn);

    if (status < 0) {
	exit (8);
    } else {
        exit(0);
    }

}
Exemple #7
0
void EncogStrCatStr(char *base, char *str, size_t len )
{
    strncat(base,str,len-1);
}
Exemple #8
0
/*
 * strargerr
 *
 * returns string containing detailed error message of
 * error occured in last call of _set_args()
 *
 */
STRPTR strargerr(void)
{
    STRPTR str = "unknown error";

    switch (arg_error_num)
    {

    case ASE_NO_MEM:
        str = "out of memory";
        break;

    case ASE_OCCURED_TWICE:
        str = "argument occured twice";
        break;

    case ASE_UNKNOWN_KEYWORD:
        str = "unknown keyword";
        break;

    case ASE_INVALID_NUM:
        str = "invalid numeric argument";
        break;

    case ASE_INVALID_ENUM:
        str = "invalid enumerator value";
        break;

    case ASE_REQUIRED_MISS:
        str = "required argument missing";
        break;

    case ASE_EMPTY_TEMPLATE:
        str = "empty template";
        break;

    case ASE_OUT_OF_RANGE:
        str = "numeric argument out of range";
        break;
    case ASE_NO_VAL_AFTER_KW:
        str = "value after keyword missing";
        break;

    case ASE_HANDLE_FUNC:       /* error in handle function */
        str = arg_error_hfs;
        break;

    }                           /* switch */

    strcpy(argerrstr, str);
    if (arg_error_arg)
    {

        strncat(argerrstr, ": ", SIZE_ARGERRSTR - strlen(str) - 1);
        strncat(argerrstr, arg_error_arg, SIZE_ARGERRSTR - strlen(str) - 3);

    }

    if (arg_error_num)
        return argerrstr;
    else
        return NULL;
}
Exemple #9
0
ngx_http_whitelist_rule_t *
ngx_http_wlr_find(ngx_conf_t *cf, ngx_http_dummy_loc_conf_t *dlc,
		  ngx_http_rule_t *curr, int zone, int uri_idx,
		  int name_idx, char **fullname) {
  uint i;
  
  /* Create unique string for rule, and try to find it in existing rules.*/
  /*name AND uri*/
  
  if (uri_idx != -1 && name_idx != -1) {
#ifdef whitelist_heavy_debug
    ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, 
		       "whitelist has uri + name");
#endif
    /* allocate one extra byte in case curr->br->target_name is set. */
    *fullname = ngx_pcalloc(cf->pool, custloc_array(curr->br->custom_locations->elts)[name_idx].target.len +
			    custloc_array(curr->br->custom_locations->elts)[uri_idx].target.len + 3);
    /* if WL targets variable name instead of content, prefix hash with '#' */
    if (curr->br->target_name)
      strncat(*fullname, (const char *) "#", 1);
    strncat(*fullname, (const char *) custloc_array(curr->br->custom_locations->elts)[uri_idx].target.data, 
	    custloc_array(curr->br->custom_locations->elts)[uri_idx].target.len);
    strncat(*fullname, (const char *) "#", 1);
    strncat(*fullname, (const char *) custloc_array(curr->br->custom_locations->elts)[name_idx].target.data, 
	    custloc_array(curr->br->custom_locations->elts)[name_idx].target.len);
  }
  /* only uri */
  else if (uri_idx != -1 && name_idx == -1) {
#ifdef whitelist_heavy_debug
    ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, 
		       "whitelist has uri");
#endif
    //XXX set flag only_uri
    *fullname = ngx_pcalloc(cf->pool, custloc_array(curr->br->custom_locations->elts)[uri_idx].target.len + 1);
    strncat(*fullname, (const char *) custloc_array(curr->br->custom_locations->elts)[uri_idx].target.data, 
	    custloc_array(curr->br->custom_locations->elts)[uri_idx].target.len);
  }
  /* only name */
  else if (name_idx != -1) {
#ifdef whitelist_heavy_debug
    ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, 
		       "whitelist has name");
#endif
    *fullname = ngx_pcalloc(cf->pool, custloc_array(curr->br->custom_locations->elts)[name_idx].target.len + 2);
    if (curr->br->target_name)
      strncat(*fullname, (const char *) "#", 1);
    strncat(*fullname, (const char *) custloc_array(curr->br->custom_locations->elts)[name_idx].target.data, 
	    custloc_array(curr->br->custom_locations->elts)[name_idx].target.len);
  }
  /* problem houston */
  else
    return (NULL);
  
  for (i = 0; i < dlc->tmp_wlr->nelts; i++)
    if (!strcmp((const char *)*fullname, (const char *)((ngx_http_whitelist_rule_t *) dlc->tmp_wlr->elts)[i].name->data) && 
	((ngx_http_whitelist_rule_t *) dlc->tmp_wlr->elts)[i].zone == (uint) zone)
      {
#ifdef whitelist_heavy_debug
	ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, 
			   "found existing 'same' WL : %V", ((ngx_http_whitelist_rule_t *) dlc->tmp_wlr->elts)[i].name);
#endif
	return (&((ngx_http_whitelist_rule_t *)dlc->tmp_wlr->elts)[i]);
      }
  return (NULL);
}
CHAR*       FrmStrncat( CHAR* s, const CHAR* ct, UINT32 n )   { return strncat( s, ct, n ); }
Exemple #11
0
int prepare(HMODULE hLibrary, const char *lpCmdLine) {
    char tmp[MAX_ARGS] = {0};
    debug = strstr(lpCmdLine, "--l4j-debug") != NULL;
    setWow64Flag();

	// Open executable
	char exePath[_MAX_PATH] = {0};
	int pathLen = getExePath(exePath);
	if (pathLen == -1) {
		return FALSE;
	}
	hLibrary = LoadLibrary(exePath + pathLen + 1);
	if (hLibrary == NULL) {
		return FALSE;
	}

	// Set default error message, title and optional support web site url.
	loadString(hLibrary, SUPPORT_URL, errUrl);
	loadString(hLibrary, ERR_TITLE, errTitle);
	if (!loadString(hLibrary, STARTUP_ERR, errMsg)) {
		return FALSE;			
	}

	// Single instance
	loadString(hLibrary, MUTEX_NAME, mutexName);
	if (*mutexName) {
		SECURITY_ATTRIBUTES security;
		security.nLength = sizeof(SECURITY_ATTRIBUTES);
		security.bInheritHandle = TRUE;
		security.lpSecurityDescriptor = NULL;
		CreateMutexA(&security, FALSE, mutexName);
		if (GetLastError() == ERROR_ALREADY_EXISTS) {
			return ERROR_ALREADY_EXISTS;
		}
	}
	
	// Working dir
	char tmp_path[_MAX_PATH] = {0};
	GetCurrentDirectory(_MAX_PATH, oldPwd);
	if (loadString(hLibrary, CHDIR, tmp_path)) {
		strncpy(workingDir, exePath, pathLen);
		strcat(workingDir, "\\");
		strcat(workingDir, tmp_path);
		_chdir(workingDir);
	}

	// Use bundled jre or find java
	if (loadString(hLibrary, JRE_PATH, tmp_path)) {
		char jrePath[MAX_ARGS] = {0};
		expandVars(jrePath, tmp_path, exePath, pathLen);
		if (jrePath[0] == '\\' || jrePath[1] == ':') {
			// Absolute
			strcpy(cmd, jrePath);
		} else {
			// Relative
			strncpy(cmd, exePath, pathLen);
			strcat(cmd, "\\");
			strcat(cmd, jrePath);
		}
    }
	if (!isJrePathOk(cmd)) {
		if (!loadString(hLibrary, JAVA_MIN_VER, javaMinVer)) {
			loadString(hLibrary, BUNDLED_JRE_ERR, errMsg);
			return FALSE;
		}
		loadString(hLibrary, JAVA_MAX_VER, javaMaxVer);
		if (!findJavaHome(cmd, loadInt(hLibrary, JDK_PREFERENCE))) {
			loadString(hLibrary, JRE_VERSION_ERR, errMsg);
			strcat(errMsg, " ");
			strcat(errMsg, javaMinVer);
			if (*javaMaxVer) {
				strcat(errMsg, " - ");
				strcat(errMsg, javaMaxVer);
			}
			loadString(hLibrary, DOWNLOAD_URL, errUrl);
			return FALSE;
		}
		if (!isJrePathOk(cmd)) {
			loadString(hLibrary, LAUNCHER_ERR, errMsg);
			return FALSE;
		}
	}

    // Append a path to the Path environment variable
	char jreBinPath[_MAX_PATH];
	strcpy(jreBinPath, cmd);
	strcat(jreBinPath, "\\bin");
	if (!appendToPathVar(jreBinPath)) {
		return FALSE;
	}

	// Set environment variables
	char envVars[MAX_VAR_SIZE] = {0};
	loadString(hLibrary, ENV_VARIABLES, envVars);
	char *var = strtok(envVars, "\t");
	while (var != NULL) {
		char *varValue = strchr(var, '=');
		*varValue++ = 0;
		*tmp = 0;
		expandVars(tmp, varValue, exePath, pathLen);
		SetEnvironmentVariable(var, tmp);
		var = strtok(NULL, "\t"); 
	}
	*tmp = 0;

	// Process priority
	priority = loadInt(hLibrary, PRIORITY_CLASS);

	// Custom process name
	const BOOL setProcName = loadBool(hLibrary, SET_PROC_NAME)
			&& strstr(lpCmdLine, "--l4j-default-proc") == NULL;
	const BOOL wrapper = loadBool(hLibrary, WRAPPER);

	appendLauncher(setProcName, exePath, pathLen, cmd);

	// Heap sizes
	appendHeapSizes(hLibrary, args);
	
    // JVM options
	if (loadString(hLibrary, JVM_OPTIONS, tmp)) {
		strcat(tmp, " ");
	} else {
        *tmp = 0;
    }
	/*
	 * Load additional JVM options from .l4j.ini file
	 * Options are separated by spaces or CRLF
	 * # starts an inline comment
	 */
	strncpy(tmp_path, exePath, strlen(exePath) - 3);
	strcat(tmp_path, "l4j.ini");
	long hFile;
	if ((hFile = _open(tmp_path, _O_RDONLY)) != -1) {
		const int jvmOptLen = strlen(tmp);
		char* src = tmp + jvmOptLen;
		char* dst = src;
		const int len = _read(hFile, src, MAX_ARGS - jvmOptLen - BIG_STR);
		BOOL copy = TRUE;
		int i;
		for (i = 0; i < len; i++, src++) {
			if (*src == '#') {
				copy = FALSE;
			} else if (*src == 13 || *src == 10) {
				copy = TRUE;
				if (dst > tmp && *(dst - 1) != ' ') {
					*dst++ = ' ';
				}
			} else if (copy) {
				*dst++ = *src;
			}
		}
		*dst = 0;
		if (len > 0 && *(dst - 1) != ' ') {
			strcat(tmp, " ");
		}
		_close(hFile);
	}

    // Expand environment %variables%
	expandVars(args, tmp, exePath, pathLen);

	// MainClass + Classpath or Jar
	char mainClass[STR] = {0};
	char jar[_MAX_PATH] = {0};
	loadString(hLibrary, JAR, jar);
	if (loadString(hLibrary, MAIN_CLASS, mainClass)) {
		if (!loadString(hLibrary, CLASSPATH, tmp)) {
			return FALSE;
		}
		char exp[MAX_ARGS] = {0};
		expandVars(exp, tmp, exePath, pathLen);
		strcat(args, "-classpath \"");
		if (wrapper) {
			appendAppClasspath(args, exePath, exp);
		} else if (*jar) {
			appendAppClasspath(args, jar, exp);
		}

		// Deal with wildcards or >> strcat(args, exp); <<
		char* cp = strtok(exp, ";");
		while(cp != NULL) {
			if (strpbrk(cp, "*?") != NULL) {
				int len = strrchr(cp, '\\') - cp + 1;
				strncpy(tmp_path, cp, len);
				char* filename = tmp_path + len;
				*filename = 0;
				struct _finddata_t c_file;
				long hFile;
				if ((hFile = _findfirst(cp, &c_file)) != -1L) {
					do {
						strcpy(filename, c_file.name);
						strcat(args, tmp_path);
						strcat(args, ";");
					} while (_findnext(hFile, &c_file) == 0);
				}
				_findclose(hFile);
			} else {
				strcat(args, cp);
				strcat(args, ";");
			}
			cp = strtok(NULL, ";");
		} 
		*(args + strlen(args) - 1) = 0;

		strcat(args, "\" ");
		strcat(args, mainClass);
	} else if (wrapper) {
       	strcat(args, "-jar \"");
		strcat(args, exePath);
   		strcat(args, "\"");
    } else {
       	strcat(args, "-jar \"");
        strncat(args, exePath, pathLen);
        strcat(args, "\\");
        strcat(args, jar);
       	strcat(args, "\"");
    }

	// Constant command line args
	if (loadString(hLibrary, CMD_LINE, tmp)) {
		strcat(args, " ");
		strcat(args, tmp);
	}

	// Command line args
	if (*lpCmdLine) {
		strcpy(tmp, lpCmdLine);
		char* dst;
		while ((dst = strstr(tmp, "--l4j-")) != NULL) {
			char* src = strchr(dst, ' ');
			if (src == NULL || *(src + 1) == 0) {
				*dst = 0;
			} else {
				strcpy(dst, src + 1);
			}
		}
		if (*tmp) {
			strcat(args, " ");
			strcat(args, tmp);
		}
	}

    if (debug) {
		strncpy(tmp, exePath, pathLen);
		*(tmp + pathLen) = 0;
		strcat(tmp, "\\launch4j.log");
		FILE *hFile = fopen(tmp, "a");
		if (hFile == NULL) {
			return FALSE;
		}
		fprintf(hFile, "Working dir:\t%s\n", workingDir);
		fprintf(hFile, "Launcher:\t%s\n", cmd);
        _itoa(strlen(args), tmp, 10);     // 10 -- radix
		fprintf(hFile, "Args length:\t%s/32768 chars\n", tmp);
		fprintf(hFile, "Launcher args:\t%s\n\n\n", args);
		fclose(hFile);
    }
	return TRUE;
}
Exemple #12
0
static void print_iface_info(uct_worker_h worker, uct_md_h md,
                             uct_tl_resource_desc_t *resource)
{
    uct_iface_config_t *iface_config;
    uct_iface_attr_t iface_attr;
    ucs_status_t status;
    uct_iface_h iface;
    char buf[200] = {0};
    uct_iface_params_t iface_params = {
        .field_mask            = UCT_IFACE_PARAM_FIELD_OPEN_MODE   |
                                 UCT_IFACE_PARAM_FIELD_DEVICE      |
                                 UCT_IFACE_PARAM_FIELD_STATS_ROOT  |
                                 UCT_IFACE_PARAM_FIELD_RX_HEADROOM |
                                 UCT_IFACE_PARAM_FIELD_CPU_MASK,
        .open_mode             = UCT_IFACE_OPEN_MODE_DEVICE,
        .mode.device.tl_name   = resource->tl_name,
        .mode.device.dev_name  = resource->dev_name,
        .stats_root            = ucs_stats_get_root(),
        .rx_headroom           = 0
    };

    UCS_CPU_ZERO(&iface_params.cpu_mask);
    status = uct_md_iface_config_read(md, resource->tl_name, NULL, NULL, &iface_config);
    if (status != UCS_OK) {
        return;
    }

    printf("#   Device: %s\n", resource->dev_name);

    status = uct_iface_open(md, worker, &iface_params, iface_config, &iface);
    uct_config_release(iface_config);

    if (status != UCS_OK) {
        printf("#   < failed to open interface >\n");
        return;
    }

    printf("#\n");
    printf("#      capabilities:\n");
    status = uct_iface_query(iface, &iface_attr);
    if (status != UCS_OK) {
        printf("#   < failed to query interface >\n");
    } else {
        printf("#            bandwidth: %-.2f MB/sec\n", iface_attr.bandwidth / UCS_MBYTE);
        printf("#              latency: %-.0f nsec", iface_attr.latency.overhead * 1e9);
        if (iface_attr.latency.growth > 0) {
            printf(" + %.0f * N\n", iface_attr.latency.growth * 1e9);
        } else {
            printf("\n");
        }
        printf("#             overhead: %-.0f nsec\n", iface_attr.overhead * 1e9);

        PRINT_CAP(PUT_SHORT, iface_attr.cap.flags, iface_attr.cap.put.max_short);
        PRINT_CAP(PUT_BCOPY, iface_attr.cap.flags, iface_attr.cap.put.max_bcopy);
        PRINT_ZCAP(PUT_ZCOPY, iface_attr.cap.flags, iface_attr.cap.put.min_zcopy,
                   iface_attr.cap.put.max_zcopy, iface_attr.cap.put.max_iov);

        if (iface_attr.cap.flags & UCT_IFACE_FLAG_PUT_ZCOPY) {
            printf("#  put_opt_zcopy_align: %s\n",
                   size_limit_to_str(0, iface_attr.cap.put.opt_zcopy_align));
            printf("#        put_align_mtu: %s\n",
                   size_limit_to_str(0, iface_attr.cap.put.align_mtu));
        }

        PRINT_CAP(GET_SHORT, iface_attr.cap.flags, iface_attr.cap.get.max_short);
        PRINT_CAP(GET_BCOPY, iface_attr.cap.flags, iface_attr.cap.get.max_bcopy);
        PRINT_ZCAP(GET_ZCOPY, iface_attr.cap.flags, iface_attr.cap.get.min_zcopy,
                   iface_attr.cap.get.max_zcopy, iface_attr.cap.get.max_iov);
        if (iface_attr.cap.flags & UCT_IFACE_FLAG_GET_ZCOPY) {
            printf("#  get_opt_zcopy_align: %s\n",
                   size_limit_to_str(0, iface_attr.cap.get.opt_zcopy_align));
            printf("#        get_align_mtu: %s\n",
                   size_limit_to_str(0, iface_attr.cap.get.align_mtu));
        }

        PRINT_CAP(AM_SHORT,  iface_attr.cap.flags, iface_attr.cap.am.max_short);
        PRINT_CAP(AM_BCOPY,  iface_attr.cap.flags, iface_attr.cap.am.max_bcopy);
        PRINT_ZCAP(AM_ZCOPY,  iface_attr.cap.flags, iface_attr.cap.am.min_zcopy,
                   iface_attr.cap.am.max_zcopy, iface_attr.cap.am.max_iov);
        if (iface_attr.cap.flags & UCT_IFACE_FLAG_AM_ZCOPY) {
            printf("#   am_opt_zcopy_align: %s\n",
                   size_limit_to_str(0, iface_attr.cap.am.opt_zcopy_align));
            printf("#         am_align_mtu: %s\n",
                   size_limit_to_str(0, iface_attr.cap.am.align_mtu));
            printf("#            am header: %s\n",
                   size_limit_to_str(0, iface_attr.cap.am.max_hdr));
        }

        PRINT_CAP(TAG_EAGER_SHORT, iface_attr.cap.flags,
                  iface_attr.cap.tag.eager.max_short);
        PRINT_CAP(TAG_EAGER_BCOPY, iface_attr.cap.flags,
                  iface_attr.cap.tag.eager.max_bcopy);
        PRINT_ZCAP(TAG_EAGER_ZCOPY, iface_attr.cap.flags, 0,
                   iface_attr.cap.tag.eager.max_zcopy,
                   iface_attr.cap.tag.eager.max_iov);

        if (iface_attr.cap.flags & UCT_IFACE_FLAG_TAG_RNDV_ZCOPY) {
            PRINT_ZCAP_NO_CHECK(TAG_RNDV_ZCOPY, 0,
                                iface_attr.cap.tag.rndv.max_zcopy,
                                iface_attr.cap.tag.rndv.max_iov);
            printf("#  rndv private header: %s\n",
                   size_limit_to_str(0, iface_attr.cap.tag.rndv.max_hdr));
        }

        if (iface_attr.cap.flags & (UCT_IFACE_FLAG_TAG_EAGER_SHORT |
                                    UCT_IFACE_FLAG_TAG_EAGER_BCOPY |
                                    UCT_IFACE_FLAG_TAG_EAGER_ZCOPY |
                                    UCT_IFACE_FLAG_TAG_RNDV_ZCOPY)) {
            PRINT_ZCAP_NO_CHECK(TAG_RECV, iface_attr.cap.tag.recv.min_recv,
                                iface_attr.cap.tag.recv.max_zcopy,
                                iface_attr.cap.tag.recv.max_iov);
            printf("#  tag_max_outstanding: %s\n",
                   size_limit_to_str(0, iface_attr.cap.tag.recv.max_outstanding));
        }

        if (iface_attr.cap.atomic32.op_flags  ||
            iface_attr.cap.atomic64.op_flags  ||
            iface_attr.cap.atomic32.fop_flags ||
            iface_attr.cap.atomic64.fop_flags) {
            if (iface_attr.cap.flags & UCT_IFACE_FLAG_ATOMIC_DEVICE) {
                printf("#               domain: device\n");
            } else if (iface_attr.cap.flags & UCT_IFACE_FLAG_ATOMIC_CPU) {
                printf("#               domain: cpu\n");
            }

            PRINT_ATOMIC_POST(ADD, iface_attr.cap);
            PRINT_ATOMIC_POST(AND, iface_attr.cap);
            PRINT_ATOMIC_POST(OR,  iface_attr.cap);
            PRINT_ATOMIC_POST(XOR, iface_attr.cap);

            PRINT_ATOMIC_FETCH(ADD,   iface_attr.cap, "f");
            PRINT_ATOMIC_FETCH(AND,   iface_attr.cap, "f");
            PRINT_ATOMIC_FETCH(OR,    iface_attr.cap, "f");
            PRINT_ATOMIC_FETCH(XOR,   iface_attr.cap, "f");
            PRINT_ATOMIC_FETCH(SWAP , iface_attr.cap, "");
            PRINT_ATOMIC_FETCH(CSWAP, iface_attr.cap, "");
        }

        buf[0] = '\0';
        if (iface_attr.cap.flags & (UCT_IFACE_FLAG_CONNECT_TO_EP |
                                    UCT_IFACE_FLAG_CONNECT_TO_IFACE)) {
            if (iface_attr.cap.flags & UCT_IFACE_FLAG_CONNECT_TO_EP) {
                strncat(buf, " to ep,", sizeof(buf) - 1);
            }
            if (iface_attr.cap.flags & UCT_IFACE_FLAG_CONNECT_TO_IFACE) {
                strncat(buf, " to iface,", sizeof(buf) - 1);
            }
            buf[strlen(buf) - 1] = '\0';
        } else {
            strncat(buf, " none", sizeof(buf) - 1);
        }
        printf("#           connection:%s\n", buf);

        printf("#             priority: %d\n", iface_attr.priority);

        printf("#       device address: %zu bytes\n", iface_attr.device_addr_len);
        if (iface_attr.cap.flags & UCT_IFACE_FLAG_CONNECT_TO_IFACE) {
            printf("#        iface address: %zu bytes\n", iface_attr.iface_addr_len);
        }
        if (iface_attr.cap.flags & UCT_IFACE_FLAG_CONNECT_TO_EP) {
            printf("#           ep address: %zu bytes\n", iface_attr.ep_addr_len);
        }

        buf[0] = '\0';
        if (iface_attr.cap.flags & (UCT_IFACE_FLAG_ERRHANDLE_SHORT_BUF   |
                                    UCT_IFACE_FLAG_ERRHANDLE_BCOPY_BUF   |
                                    UCT_IFACE_FLAG_ERRHANDLE_ZCOPY_BUF   |
                                    UCT_IFACE_FLAG_ERRHANDLE_AM_ID       |
                                    UCT_IFACE_FLAG_ERRHANDLE_REMOTE_MEM  |
                                    UCT_IFACE_FLAG_ERRHANDLE_PEER_FAILURE)) {

            if (iface_attr.cap.flags & (UCT_IFACE_FLAG_ERRHANDLE_SHORT_BUF |
                                        UCT_IFACE_FLAG_ERRHANDLE_BCOPY_BUF |
                                        UCT_IFACE_FLAG_ERRHANDLE_ZCOPY_BUF)) {
                strncat(buf, " buffer (", sizeof(buf) - 1);
                if (iface_attr.cap.flags & UCT_IFACE_FLAG_ERRHANDLE_SHORT_BUF) {
                    strncat(buf, "short,", sizeof(buf) - 1);
                }
                if (iface_attr.cap.flags & UCT_IFACE_FLAG_ERRHANDLE_BCOPY_BUF) {
                    strncat(buf, "bcopy,", sizeof(buf) - 1);
                }
                if (iface_attr.cap.flags & UCT_IFACE_FLAG_ERRHANDLE_ZCOPY_BUF) {
                    strncat(buf, "zcopy,", sizeof(buf) - 1);
                }
                buf[strlen(buf) - 1] = '\0';
                strncat(buf, "),", sizeof(buf) - 1);
            }
            if (iface_attr.cap.flags & UCT_IFACE_FLAG_ERRHANDLE_AM_ID) {
                strncat(buf, " active-message id,", sizeof(buf) - 1);
            }
            if (iface_attr.cap.flags & UCT_IFACE_FLAG_ERRHANDLE_REMOTE_MEM) {
                strncat(buf, " remote access,", sizeof(buf) - 1);
            }
            if (iface_attr.cap.flags & UCT_IFACE_FLAG_ERRHANDLE_PEER_FAILURE) {
                strncat(buf, " peer failure,", sizeof(buf) - 1);
            }
            buf[strlen(buf) - 1] = '\0';
        } else {
            strncat(buf, " none", sizeof(buf) - 1);
        }
        printf("#       error handling:%s\n", buf);
    }

    uct_iface_close(iface);
    printf("#\n");
}

static ucs_status_t print_tl_info(uct_md_h md, const char *tl_name,
                                  uct_tl_resource_desc_t *resources,
                                  unsigned num_resources,
                                  int print_opts,
                                  ucs_config_print_flags_t print_flags)
{
    ucs_async_context_t async;
    uct_worker_h worker;
    ucs_status_t status;
    unsigned i;

    status = ucs_async_context_init(&async, UCS_ASYNC_THREAD_LOCK_TYPE);
    if (status != UCS_OK) {
        return status;
    }

    /* coverity[alloc_arg] */
    status = uct_worker_create(&async, UCS_THREAD_MODE_SINGLE, &worker);
    if (status != UCS_OK) {
        goto out;
    }

    printf("#\n");
    printf("#   Transport: %s\n", tl_name);
    printf("#\n");

    if (num_resources == 0) {
        printf("# (No supported devices found)\n");
    }
    for (i = 0; i < num_resources; ++i) {
        ucs_assert(!strcmp(tl_name, resources[i].tl_name));
        print_iface_info(worker, md, &resources[i]);
    }

    uct_worker_destroy(worker);
out:
    ucs_async_context_cleanup(&async);
    return status;
}
Exemple #13
0
static void urlinfo_set_url (urlinfo *u, const char *url)
{
    u->url[0] = '\0';
    strncat(u->url, url, URLLEN - 1);
}
Exemple #14
0
int
uname(struct utsname *ub)
{
        SYSTEM_INFO   sysinfo;
        OSVERSIONINFO osinfo;

        GetSystemInfo(&sysinfo);
        osinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
        GetVersionEx(&osinfo);

        strcpy(ub->sysname, "Windows");
        strcpy(ub->nodename, "Unknown"); /* could use gethostbyname */

        /* ub->release and ub->machine*/
        if (osinfo.dwPlatformId == VER_PLATFORM_WIN32_NT) {
                sprintf(ub->release, "NT %d.%d", osinfo.dwMajorVersion, osinfo.dwMinorVersion);
                switch (sysinfo.wProcessorArchitecture) {
                case PROCESSOR_ARCHITECTURE_INTEL:
                        sprintf(ub->machine, "i%d86", sysinfo.wProcessorLevel);
                        break;
                case PROCESSOR_ARCHITECTURE_MIPS :
                        (void)strncpy(ub->machine, "mips", SYS_NMLN);
                        break;
                case PROCESSOR_ARCHITECTURE_ALPHA:
                        sprintf(ub->machine, "alpha-%d", sysinfo.wProcessorLevel);
                        break;
                case PROCESSOR_ARCHITECTURE_PPC:
                        (void)strncpy(ub->machine, "ppc", SYS_NMLN);
                        break;
                default:
                        (void)strncpy(ub->machine, "unknown", SYS_NMLN);
                        break;
                }
        } else if (osinfo.dwPlatformId == VER_PLATFORM_WIN32s) {
                strcpy(ub->release, "3.1");
                strcpy(ub->machine, "i386");
        } else if (osinfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
                if (osinfo.dwMinorVersion == 0) {
                        strcpy(ub->release, "95");
                } else {
                        strcpy(ub->release, "98");
                }
                switch(sysinfo.dwProcessorType) {
                case PROCESSOR_INTEL_386:
                        strcpy(ub->machine, "i386");
                        break;
                case PROCESSOR_INTEL_486:
                        strcpy(ub->machine, "i486");
                        break;
                case PROCESSOR_INTEL_PENTIUM:
                        strcpy(ub->machine, "i586");
                        break;
                }
        } else {
                sprintf(ub->release, "Unknown %d.%d", osinfo.dwMajorVersion, osinfo.dwMinorVersion);
                sprintf(ub->machine, "Unknown");
        }

        /* Append service pack info onto end of release */
        if (osinfo.szCSDVersion != NULL) {
                DWORD avail = SYS_NMLN - strlen(ub->release);
                strncat(ub->release, osinfo.szCSDVersion, avail);
        }

        /* ub->version */
        sprintf(ub->version, "%lu", osinfo.dwBuildNumber);

        return TRUE;
}
Exemple #15
0
void fputtr_internal(FILE *fp, segy *tp, cwp_Bool fixed_length)
{
	/* search linked list for possible alternative */
	if(fp != lastfp)  searchlist(fp);

	if (infoptr == ((struct outsegyinfo *) NULL)) {
		/* initialize new segy output stream */

		/* allocate new segy output information table */
		*oldinfoptr = (struct outsegyinfo *)
			malloc(sizeof(struct outsegyinfo));
		infoptr = *oldinfoptr;
		infoptr->nextinfo = (struct outsegyinfo *) NULL;
		/* save FILE * ptr */
		infoptr->outfp = fp;
		infoptr->itr = 0;

		switch (infoptr->ftype = filestat(fileno(fp))) {
		case DIRECTORY:
			err("%s: segy output can't be a directory", __FILE__);
		case TTY:
			err("%s: segy output can't be tty", __FILE__);
		default:
			/* the rest are ok */
		break;
		}

		/* Sanity check the segy header */
		infoptr->nsfirst = tp->ns;
		if (infoptr->nsfirst > SU_NFLTS)
			err("%s: unable to handle %d > %d samples per trace",
			    __FILE__, infoptr->nsfirst, SU_NFLTS);
		switch(tp->trid) {
		case CHARPACK:
			infoptr->bytesper = sizeof(char); break;
		case SHORTPACK:
			infoptr->bytesper = 2*sizeof(char); break;
		default:
			infoptr->bytesper = sizeof(float); break;
		}

/*--------------------------------------------------------------------*\
   Write out a line header if it has been set as the default or has 
   requested on the caommandline.  Commandline takes precedence over
   the default in all cases.

   Reginald H. Beardsley			    [email protected]
\*--------------------------------------------------------------------*/
	      
		if (!getparint( "lheader" ,&out_line_hdr )) out_line_hdr=0;

		if( out_line_hdr ){

		   if( in_line_hdr ){
		     (void) efwrite(&(su_text_hdr[0]), 1 ,3200 
				    ,infoptr->outfp);

		   }else{
		     memset( su_text_hdr ,0 ,sizeof(su_text_hdr) );
		     sprintf( hdr_str ,"%-80s" 
			    ,"C 1 CLIENT CWP/SU default text header " );
		     strncat( su_text_hdr ,hdr_str ,80 );
		     for( i=1; i<40; i++ ){
			sprintf( hdr_str ,"%-80s" ,"C" );
			strncat( su_text_hdr ,hdr_str ,80 );
		     }
		     (void) efwrite(&(su_text_hdr[0]), 1 ,3200 
				    ,infoptr->outfp);


		   }

		   memset( &su_binary_hdr ,0 ,sizeof(su_binary_hdr) );
		   su_binary_hdr.format = 5;
		   su_binary_hdr.hns = tp->ns;
		   su_binary_hdr.hdt = tp->dt;
 
 
		  (void) efwrite(&su_binary_hdr,1,
			sizeof(su_binary_hdr), infoptr->outfp);
		}
		
	}

	if (tp->ns != infoptr->nsfirst && fixed_length)
		err("%s: on trace #%ld, number of samples in header (%d) "
		    "differs from number for first trace (%d)", 
		    __FILE__, (infoptr->itr)+1, tp->ns, infoptr->nsfirst);
	

	(void) efwrite(tp, 1,HDRBYTES, infoptr->outfp);
	datawrite(tp, infoptr, fixed_length);
	
	++infoptr->itr;
	lastfp = infoptr->outfp;
}
Exemple #16
0
Fichier : strlib.c Projet : j-fu/gr
char *str_ftoa(char *result, double value, double reference)

/*
 *  str_ftoa - convert real value to floating equivalent
 */

{
  static char *digit = "0123456789";
  char format[STR_MAX];

  double abs_val;
  char str[STR_MAX], *fcp, *cp;
  int count, exponent, factor, mantissa;
  int fdigits, digits, scientific_notation;

  if (value != 0)
    {
      abs_val = fabs(value);

      exponent = (int) (log10(abs_val) + pow(10.0, -NDIGITS));
      if (exponent < 0)
	exponent--;

      factor = (NDIGITS - 1) - exponent;
      mantissa = (int) (abs_val * pow(10.0, factor) + 0.5);

      strcpy(result, "");

      count = 0;
      fdigits = digits = 0;

      do
	{
	  count++;

	  strcpy(str, result);
	  result[0] = digit[mantissa % 10];
	  result[1] = '\0';
	  strcat(result, str);

	  if (count == factor)
	    {
	      strcpy(str, result);
	      strcpy(result, ".");
	      strcat(result, str);
	    }

	  mantissa = mantissa / 10;
	}
      while (count != NDIGITS);

      scientific_notation = (exponent <= 1 - NDIGITS) || (exponent >= NDIGITS);

      if (scientific_notation || exponent < 0)
	{
	  if (!scientific_notation)
	    {
	      strcpy(str, "");
	      str_pad(str, '0', -exponent - 1);
	      strcat(str, result);
	      strcpy(result, str);
	    }

	  strcpy(str, "0.");
	  strcat(str, result);
	  strcpy(result, str);
	}

      if (value < 0)
	{
	  strcpy(str, "-");
	  strcat(str, result);
	  strcpy(result, str);
	}

      if (strchr(result, '.') != 0)
	{
	  str_remove(result, '0');
	  str_remove(result, '.');
	}

      if (scientific_notation)
	{
	  strcat(result, "E");
	  sprintf(str, "%d", exponent + 1);
	  strcat(result, str);
	}
      else
	{
	  sprintf(format, "%lg", reference);

	  if (strchr(format, 'E') == 0)

	    if ((fcp = strchr(format, '.')) != 0)
	      {
		fdigits = strlen(format) - (int) (fcp - format) - 1;

		if ((cp = strchr(result, '.')) != 0)
		  {
		    digits = strlen(result) - (int) (cp - result) - 1;

		    if (fdigits > digits)
		      strncat(result, "000000000", fdigits - digits);
		  }
		else
		  {
		    strcat(result, ".");
		    strncat(result, "000000000", fdigits);
		  }
	      }
	}
    }
  else
    strcpy(result, "0");

  return result;
}
Exemple #17
0
static int writeANSI(QRcode *qrcode, const char *outfile)
{
	FILE *fp;
	unsigned char *row, *p;
	int x, y;
	int realwidth;
	int last;

	char *white, *black, *buffer;
	int white_s, black_s, buffer_s;

	if( image_type == ANSI256_TYPE ){
		/* codes for 256 color compatible terminals */
		white = "\033[48;5;231m";
		white_s = 11;
		black = "\033[48;5;16m";
		black_s = 10;
	} else {
		white = "\033[47m";
		white_s = 5;
		black = "\033[40m";
		black_s = 5;
	}

	size = 1;

	fp = openFile(outfile);

	realwidth = (qrcode->width + margin * 2) * size;
	buffer_s = ( realwidth * white_s ) * 2;
	buffer = (char *)malloc( buffer_s );
	if(buffer == NULL) {
		fprintf(stderr, "Failed to allocate memory.\n");
		exit(EXIT_FAILURE);
	}

	/* top margin */
	writeANSI_margin(fp, realwidth, buffer, buffer_s, white, white_s);

	/* data */
	p = qrcode->data;
	for(y=0; y<qrcode->width; y++) {
		row = (p+(y*qrcode->width));

		bzero( buffer, buffer_s );
		strncpy( buffer, white, white_s );
		for(x=0; x<margin; x++ ){
			strncat( buffer, "  ", 2 );
		}
		last = 0;

		for(x=0; x<qrcode->width; x++) {
			if(*(row+x)&0x1) {
				if( last != 1 ){
					strncat( buffer, black, black_s );
					last = 1;
				}
			} else {
				if( last != 0 ){
					strncat( buffer, white, white_s );
					last = 0;
				}
			}
			strncat( buffer, "  ", 2 );
		}

		if( last != 0 ){
			strncat( buffer, white, white_s );
		}
		for(x=0; x<margin; x++ ){
			strncat( buffer, "  ", 2 );
		}
		strncat( buffer, "\033[0m\n", 5 );
		fputs( buffer, fp );
	}

	/* bottom margin */
	writeANSI_margin(fp, realwidth, buffer, buffer_s, white, white_s);

	fclose(fp);
	free(buffer);

	return 0;
}
Exemple #18
0
static VALUE get_value(const char* buffer, int* position, int type) {
    VALUE value;
    switch (type) {
    case 1:
        {
            double d;
            memcpy(&d, buffer + *position, 8);
            value = rb_float_new(d);
            *position += 8;
            break;
        }
    case 2:
    case 13:
        {
            int value_length;
            *position += 4;
            value_length = strlen(buffer + *position);
            value = STR_NEW(buffer + *position, value_length);
            *position += value_length + 1;
            break;
        }
    case 3:
        {
            int size;
            memcpy(&size, buffer + *position, 4);
            if (strcmp(buffer + *position + 5, "$ref") == 0) { // DBRef
                int offset = *position + 14;
                VALUE argv[2];
                int collection_length = strlen(buffer + offset);
                char id_type;

                argv[0] = STR_NEW(buffer + offset, collection_length);
                offset += collection_length + 1;
                id_type = buffer[offset];
                offset += 5;
                argv[1] = get_value(buffer, &offset, (int)id_type);
                value = rb_class_new_instance(2, argv, DBRef);
            } else {
                value = elements_to_hash(buffer + *position + 4, size - 5, 0);
            }
            *position += size;
            break;
        }
    case 4:
        {
            int size, end;
            memcpy(&size, buffer + *position, 4);
            end = *position + size - 1;
            *position += 4;

            value = rb_ary_new();
            while (*position < end) {
                int type = (int)buffer[(*position)++];
                int key_size = strlen(buffer + *position);
                VALUE to_append;

                *position += key_size + 1; // just skip the key, they're in order.
                to_append = get_value(buffer, position, type);
                rb_ary_push(value, to_append);
            }
            (*position)++;
            break;
        }
    case 5:
        {
            int length, subtype;
            VALUE data, st;
            VALUE argv[2];
            memcpy(&length, buffer + *position, 4);
            subtype = (unsigned char)buffer[*position + 4];
            if (subtype == 2) {
                data = rb_str_new(buffer + *position + 9, length - 4);
            } else {
                data = rb_str_new(buffer + *position + 5, length);
            }
            st = INT2FIX(subtype);
            argv[0] = data;
            argv[1] = st;
            value = rb_class_new_instance(2, argv, Binary);
            *position += length + 5;
            break;
        }
    case 6:
        {
            value = Qnil;
            break;
        }
    case 7:
        {
            VALUE str = rb_str_new(buffer + *position, 12);
            VALUE oid = rb_funcall(str, rb_intern("unpack"), 1, rb_str_new2("C*"));
            value = rb_class_new_instance(1, &oid, ObjectID);
            *position += 12;
            break;
        }
    case 8:
        {
            value = buffer[(*position)++] ? Qtrue : Qfalse;
            break;
        }
    case 9:
        {
            long long millis;
            VALUE seconds, microseconds;
            memcpy(&millis, buffer + *position, 8);
            seconds = INT2NUM(millis / 1000);
            microseconds = INT2NUM((millis % 1000) * 1000);

            value = rb_funcall(Time, rb_intern("at"), 2, seconds, microseconds);
            value = rb_funcall(value, rb_intern("utc"), 0);
            *position += 8;
            break;
        }
    case 10:
        {
            value = Qnil;
            break;
        }
    case 11:
        {
            int pattern_length = strlen(buffer + *position);
            VALUE pattern = STR_NEW(buffer + *position, pattern_length);
            int flags_length, flags = 0, i = 0;
            char extra[10];
            VALUE argv[3];
            *position += pattern_length + 1;

            flags_length = strlen(buffer + *position);
            extra[0] = 0;
            for (i = 0; i < flags_length; i++) {
                char flag = buffer[*position + i];
                if (flag == 'i') {
                    flags |= IGNORECASE;
                }
                else if (flag == 'm') {
                    flags |= MULTILINE;
                }
                else if (flag == 'x') {
                    flags |= EXTENDED;
                }
                else if (strlen(extra) < 9) {
                    strncat(extra, &flag, 1);
                }
            }
            argv[0] = pattern;
            argv[1] = INT2FIX(flags);
            argv[2] = rb_str_new2(extra);
            value = rb_class_new_instance(3, argv, RegexpOfHolding);
            *position += flags_length + 1;
            break;
        }
    case 12:
        {
            int collection_length;
            VALUE collection, str, oid, id, argv[2];
            *position += 4;
            collection_length = strlen(buffer + *position);
            collection = STR_NEW(buffer + *position, collection_length);
            *position += collection_length + 1;

            str = rb_str_new(buffer + *position, 12);
            oid = rb_funcall(str, rb_intern("unpack"), 1, rb_str_new2("C*"));
            id = rb_class_new_instance(1, &oid, ObjectID);
            *position += 12;

            argv[0] = collection;
            argv[1] = id;
            value = rb_class_new_instance(2, argv, DBRef);
            break;
        }
    case 14:
        {
            int value_length;
            memcpy(&value_length, buffer + *position, 4);
            value = ID2SYM(rb_intern(buffer + *position + 4));
            *position += value_length + 4;
            break;
        }
    case 15:
        {
            int code_length, scope_size;
            VALUE code, scope, argv[2];
            *position += 8;
            code_length = strlen(buffer + *position);
            code = STR_NEW(buffer + *position, code_length);
            *position += code_length + 1;

            memcpy(&scope_size, buffer + *position, 4);
            scope = elements_to_hash(buffer + *position + 4, scope_size - 5, 0);
            *position += scope_size;

            argv[0] = code;
            argv[1] = scope;
            value = rb_class_new_instance(2, argv, Code);
            break;
        }
    case 16:
        {
            int i;
            memcpy(&i, buffer + *position, 4);
            value = LL2NUM(i);
            *position += 4;
            break;
        }
    case 17:
        {
            int i;
            int j;
            memcpy(&i, buffer + *position, 4);
            memcpy(&j, buffer + *position + 4, 4);
            value = rb_ary_new3(2, LL2NUM(i), LL2NUM(j));
            *position += 8;
            break;
        }
    case 18:
        {
            long long ll;
            memcpy(&ll, buffer + *position, 8);
            value = LL2NUM(ll);
            *position += 8;
            break;
        }
    default:
        {
            rb_raise(rb_eTypeError, "no c decoder for this type yet (%d)", type);
            break;
        }
    }
    return value;
}
Exemple #19
0
/*****************************************************************************
 * Function - SendAlarmSms
 * DESCRIPTION: Create an send an alarm sms
 *
 *****************************************************************************/
void SmsAlarm::SendAlarmSms(AlarmEvent* pAlarmEvent, SMS_REQUEST_TYPE reqType)
{
  #ifdef STR_MAX
    #error"AlarmSms"
  #else
    #define STR_MAX 900
  #endif
  char s1[STR_MAX]; //En sms må ikke være mere end 210tegn(tegn=1-4bytes), udfør evt tjek i nedenstående der sikrer mod overindeksering
  int str_id;
  int max_len;
  TimeFormatDataPoint* pDpTimePreference = TimeFormatDataPoint::GetInstance();
  mpc::display::ActualAlarmString alarm_String;

  SmsOut* my_sms = new SmsOut();  //Create a sms object, SmsCtrl will take care of deleting the object

  /* Create the message */
  s1[0]=0;
  if(pAlarmEvent->GetAlarmType() == ALARM_STATE_WARNING)
    strncat(s1, Languages::GetInstance()->GetString( SID_WARNING ),STR_MAX);  //Warning
  else if (pAlarmEvent->GetAlarmType() == ALARM_STATE_ALARM)
    strncat(s1, Languages::GetInstance()->GetString( SID_FS_ALARM ),STR_MAX); //Alarm
  max_len = STR_MAX - strlen(s1);
  if( max_len>0 )
    strncat(s1, "\n", max_len);                                          // CR LF
  max_len = STR_MAX - strlen(s1);
  str_id = GetUnitString(pAlarmEvent->GetErroneousUnit(), pAlarmEvent->GetErroneousUnitNumber());//Alarm source
  if( max_len>0 )
    strncat(s1, Languages::GetInstance()->GetString( str_id ), max_len); //Unit type and number
  max_len = STR_MAX - strlen(s1);
  if( max_len>0 )
    strncat(s1, "\n", max_len);                                          // CR LF
  max_len = STR_MAX - strlen(s1);
  if( max_len>0 )
    strncat(s1, AlarmText::GetInstance()->GetString(pAlarmEvent->GetAlarmId(), pAlarmEvent->GetErroneousUnitNumber()), max_len); //Alarm text
  max_len = STR_MAX - strlen(s1);
  if( max_len>0 )
    strncat(s1, "\n", max_len);                                          // CR LF
  max_len = STR_MAX - strlen(s1);
  if( max_len>0 )
    strncat(s1, Languages::GetInstance()->GetString( SID_ARRIVAL_TIME ), max_len);  //Occurred at
  max_len = STR_MAX - strlen(s1);
  if( max_len>0 )
    strncat(s1, "\n", max_len);                                          // CR LF
  max_len = STR_MAX - strlen(s1);
  mpTimeText->SetTime(*pAlarmEvent->GetArrivalTime());
  if( max_len>0 )
    strncat(s1, mpTimeText->GetText(), max_len);                         //Time
  max_len = STR_MAX - strlen(s1);
  if( max_len>0 )
    strncat(s1, "\n", max_len);                                           // CR LF
  max_len = STR_MAX - strlen(s1);
  if( max_len>0 )
    strncat(s1, Languages::GetInstance()->GetString( SID_DEPARTURE_TIME ), max_len);//Disappeared at
  strcat(s1, "\n");                                                     // CR LF
  max_len = STR_MAX - strlen(s1);
  mpTimeText->SetTime(*pAlarmEvent->GetDepartureTime());
  if( max_len>0 )
    strncat(s1, mpTimeText->GetText(), max_len);                                    //Time

  /* Copy messge to sms object */
  my_sms->SetSmsMessage( s1 );

  switch (reqType)
  {
  case SMS_PRI_SEC:
    my_sms->SetSendTo(mpSmsRecipient->GetValue());          //Primary, or both primary and secondary number
    SmsCtrl::GetInstance()->SendSms( my_sms );              //Send sms to SmsCtrl
    break;
  case SMS_DIRECT:
    SmsCtrl::GetInstance()->SendDirectAlarmSms(my_sms);
    break;
  }
}
Exemple #20
0
bool GCodes::ActOnGcode(GCodeBuffer *gb)
{
  int code;
  float value;
  int iValue;
  char* str;
  bool result = true;
  bool error = false;
  bool resend = false;
  bool seen;
  char reply[STRING_LENGTH];

  reply[0] = 0;

  if(gb->Seen('G'))
  {
    code = gb->GetIValue();
    switch(code)
    {
    case 0: // There are no rapid moves...
    case 1: // Ordinary move
      result = SetUpMove(gb);
      break;
      
    case 4: // Dwell
      result = DoDwell(gb);
      break;
      
    case 10: // Set offsets
      result = SetOffsets(gb);
      break;
    
    case 20: // Inches (which century are we living in, here?)
      distanceScale = INCH_TO_MM;
      break;
    
    case 21: // mm
      distanceScale = 1.0;
      break;
    
    case 28: // Home
      if(NoHome())
      {
    	homeAxisMoveCount = 0;
        homeX = gb->Seen(gCodeLetters[X_AXIS]);
        homeY = gb->Seen(gCodeLetters[Y_AXIS]);
        homeZ = gb->Seen(gCodeLetters[Z_AXIS]);
        if(NoHome())
        {
          homeX = true;
          homeY = true;
          homeZ = true;
        }
      }
      result = DoHome();
      break;

    case 30: // Z probe/manually set at a position and set that as point P
    	result = SetSingleZProbeAtAPosition(gb);
    	break;

    case 31: // Return the probe value, or set probe variables
    	result = SetPrintZProbe(gb, reply);
    	break;

    case 32: // Probe Z at multiple positions and generate the bed transform
    	result = DoMultipleZProbe();
    	break;

    case 90: // Absolute coordinates
      drivesRelative = false;
      axesRelative = false;
      break;
      
    case 91: // Relative coordinates
      drivesRelative = true; // Non-axis movements (i.e. extruders)
      axesRelative = true;   // Axis movements (i.e. X, Y and Z)
      break;
      
    case 92: // Set position
      result = SetPositions(gb);
      break;
      
    default:
    	error = true;
    	snprintf(reply, STRING_LENGTH, "invalid G Code: %s", gb->Buffer());
    }
    if(result)
    	HandleReply(error, gb == serialGCode, reply, 'G', code, resend);
    return result;
  }
  
  if(gb->Seen('M'))
  {
    code = gb->GetIValue();
    switch(code)
    {
    case 0: // Stop
    case 1: // Sleep
      if(fileBeingPrinted != NULL)
      {
    	  fileToPrint = fileBeingPrinted;
    	  fileBeingPrinted = NULL;
      }
      if(!DisableDrives())
    	  return false;
      if(!StandbyHeaters())
    	  return false; // Should never happen
      break;
    
    case 18: // Motors off
      result = DisableDrives();
      break;
      
    case 20:  // Deprecated...
      if(platform->Emulating() == me || platform->Emulating() == reprapFirmware)
    	  snprintf(reply, STRING_LENGTH, "GCode files:\n%s", platform->GetMassStorage()->FileList(platform->GetGCodeDir(), gb == serialGCode));
      else
    	  snprintf(reply, STRING_LENGTH, "%s", platform->GetMassStorage()->FileList(platform->GetGCodeDir(), gb == serialGCode));
      break;

    case 21: // Initialise SD - ignore
    	break;

    case 23: // Set file to print
      QueueFileToPrint(gb->GetUnprecedentedString());
      if(platform->Emulating() == marlin)
    	  snprintf(reply, STRING_LENGTH, "%s", "File opened\nFile selected\n");
      break;
      
    case 24: // Print/resume-printing the selected file
      if(fileBeingPrinted != NULL)
    	  break;
      fileBeingPrinted = fileToPrint;
      fileToPrint = NULL;
      break;
      
    case 25: // Pause the print
    	fileToPrint = fileBeingPrinted;
    	fileBeingPrinted = NULL;
    	break;

    case 27: // Report print status - Depricated
    	if(this->PrintingAFile())
    		strncpy(reply, "SD printing.", STRING_LENGTH);
    	else
    		strncpy(reply, "Not SD printing.", STRING_LENGTH);
    	break;

    case 28: // Write to file
    	str = gb->GetUnprecedentedString();
    	OpenFileToWrite(platform->GetGCodeDir(), str, gb);
    	snprintf(reply, STRING_LENGTH, "Writing to file: %s", str);
    	break;

    case 29: // End of file being written; should be intercepted before getting here
    	platform->Message(HOST_MESSAGE, "GCode end-of-file being interpreted.\n");
    	break;

    case 82:
    	for(int8_t extruder = AXES; extruder < DRIVES; extruder++)
    		lastPos[extruder - AXES] = 0.0;
    	drivesRelative = false;
    	break;

    case 83:
    	for(int8_t extruder = AXES; extruder < DRIVES; extruder++)
    		lastPos[extruder - AXES] = 0.0;
    	drivesRelative = true;

    	break;

    case 84: // Motors off - deprecated, use M18
        result = DisableDrives();
        break;

    case 85: // Set inactive time
    	break;

    case 92: // Set/report steps/mm for some axes
    	seen = false;
    	for(int8_t drive = 0; drive < DRIVES; drive++)
    		if(gb->Seen(gCodeLetters[drive]))
    		{
    			platform->SetDriveStepsPerUnit(drive, gb->GetFValue());
    			seen = true;
    		}
    	reprap.GetMove()->SetStepHypotenuse();
    	if(!seen)
    		snprintf(reply, STRING_LENGTH, "Steps/mm: X: %d, Y: %d, Z: %d, E: %d",
    				(int)platform->DriveStepsPerUnit(X_AXIS), (int)platform->DriveStepsPerUnit(Y_AXIS),
    				(int)platform->DriveStepsPerUnit(Z_AXIS), (int)platform->DriveStepsPerUnit(AXES)); // FIXME - needs to do multiple extruders
        break;


    case 98:
    	if(gb->Seen('P'))
    		result = DoFileCannedCycles(gb->GetString());
    	break;

    case 99:
    	result = FileCannedCyclesReturn();
    	break;

    case 104: // Depricated
    	if(gb->Seen('S'))
    	{
    		reprap.GetHeat()->SetActiveTemperature(1, gb->GetFValue()); // 0 is the bed
    		reprap.GetHeat()->Activate(1);
    	}
    	break;

    case 105: // Deprecated...
    	strncpy(reply, "T:", STRING_LENGTH);
    	for(int8_t heater = HEATERS - 1; heater > 0; heater--)
    	{
    		strncat(reply, ftoa(0, reprap.GetHeat()->GetTemperature(heater), 1), STRING_LENGTH);
    		strncat(reply, " ", STRING_LENGTH);
    	}
    	strncat(reply, "B:", STRING_LENGTH);
    	strncat(reply, ftoa(0, reprap.GetHeat()->GetTemperature(0), 1), STRING_LENGTH);
    	break;
   
    case 106: // Fan on or off
    	if(gb->Seen('S'))
    		platform->CoolingFan(gb->GetFValue());
      break;
    
    case 107: // Fan off - depricated
    	platform->CoolingFan(0.0);
      break;
      
    case 110: // Set line numbers - line numbers are dealt with in the GCodeBuffer class, so ignore
    	break;

    case 111: // Debug level
    	if(gb->Seen('S'))
    		reprap.SetDebug(gb->GetIValue());
    	break;

    case 112: // Emergency stop - acted upon in Webserver
    	break;

    case 114: // Deprecated
    	str = GetCurrentCoordinates();
    	if(str != 0)
    	{
    		strncpy(reply, str, STRING_LENGTH);
    	} else
    		result = false;
    	break;

    case 115: // Print firmware version
    	snprintf(reply, STRING_LENGTH, "FIRMWARE_NAME:%s FIRMWARE_VERSION:%s ELECTRONICS:%s DATE:%s", NAME, VERSION, ELECTRONICS, DATE);
    	break;

    case 109: // Depricated
    	if(gb->Seen('S'))
    	{
    		reprap.GetHeat()->SetActiveTemperature(1, gb->GetFValue()); // 0 is the bed
    		reprap.GetHeat()->Activate(1);
    	}
    case 116: // Wait for everything, especially set temperatures
    	if(!AllMovesAreFinishedAndMoveBufferIsLoaded())
    		return false;
    	result = reprap.GetHeat()->AllHeatersAtSetTemperatures();
    	break;

    case 120:
    	result = Push();
    	break;

    case 121:
      result = Pop();
      break;
    
    case 122:
      reprap.Diagnostics();
      break;
      
    case 126: // Valve open
      platform->Message(HOST_MESSAGE, "M126 - valves not yet implemented\n");
      break;
      
    case 127: // Valve closed
      platform->Message(HOST_MESSAGE, "M127 - valves not yet implemented\n");
      break;
      
    case 135: // Set PID sample interval
    	break;

    case 140: // Set bed temperature
      if(gb->Seen('S'))
      {
        reprap.GetHeat()->SetActiveTemperature(0, gb->GetFValue());
        reprap.GetHeat()->Activate(0);
      }
      break;
    
    case 141: // Chamber temperature
      platform->Message(HOST_MESSAGE, "M141 - heated chamber not yet implemented\n");
      break;

    case 201: // Set axis accelerations
    	for(int8_t drive = 0; drive < DRIVES; drive++)
    	{
    		if(gb->Seen(gCodeLetters[drive]))
    		{
    			value = gb->GetFValue();
    		}else{
    			value = -1;
    		}
    		platform->SetAcceleration(drive, value);
    	}
    	break;

    case 203: // Set maximum feedrates
    	for(int8_t drive = 0; drive < DRIVES; drive++)
    	{
    		if(gb->Seen(gCodeLetters[drive]))
    		{
    			value = gb->GetFValue()*distanceScale*0.016666667; // G Code feedrates are in mm/minute; we need mm/sec;
    			platform->SetMaxFeedrate(drive, value);
    		}
    	}
    	break;

    case 205:  //M205 advanced settings:  minimum travel speed S=while printing T=travel only,  B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk
    	break;

    case 206:  // Offset axes
    	result = OffsetAxes(gb);
    	break;

    case 208: // Set maximum axis lengths
    	for(int8_t axis = 0; axis < AXES; axis++)
    	{
    		if(gb->Seen(gCodeLetters[axis]))
    		{
    			value = gb->GetFValue()*distanceScale;
    			platform->SetAxisLength(axis, value);
    		}
    	}
    	break;

    case 210: // Set homing feedrates
    	for(int8_t axis = 0; axis < AXES; axis++)
    	{
    		if(gb->Seen(gCodeLetters[axis]))
    		{
    			value = gb->GetFValue()*distanceScale*0.016666667;
    			platform->SetHomeFeedRate(axis, value);
    		}
    	}
    	break;

    case 301: // Set PID values
    	break;

    case 302: // Allow cold extrudes
    	break;

    case 304: // Set thermistor parameters
    	break;

    case 503: // list variable settings
    	result = SendConfigToLine();
    	break;

    case 550: // Set machine name
        	if(gb->Seen('P'))
        		reprap.GetWebserver()->SetName(gb->GetString());
        	break;

    case 551: // Set password
    	if(gb->Seen('P'))
    		reprap.GetWebserver()->SetPassword(gb->GetString());
    	break;

    case 552: // Set/Get IP address
    	if(gb->Seen('P'))
    		SetEthernetAddress(gb, code);
    	else
    	{
    		byte *ip = platform->IPAddress();
    		snprintf(reply, STRING_LENGTH, "IP address: %d.%d.%d.%d\n ", ip[0], ip[1], ip[2], ip[3]);
    	}
    	break;

    case 553: // Set/Get netmask
    	if(gb->Seen('P'))
    		SetEthernetAddress(gb, code);
    	else
    	{
    		byte *nm = platform->NetMask();
    		snprintf(reply, STRING_LENGTH, "Net mask: %d.%d.%d.%d\n ", nm[0], nm[1], nm[2], nm[3]);
    	}
    	break;

    case 554: // Set/Get gateway
    	if(gb->Seen('P'))
    		SetEthernetAddress(gb, code);
    	else
    	{
    		byte *gw = platform->GateWay();
    		snprintf(reply, STRING_LENGTH, "Gateway: %d.%d.%d.%d\n ", gw[0], gw[1], gw[2], gw[3]);
    	}
    	break;

    case 555: // Set firmware type to emulate
    	if(gb->Seen('P'))
    		platform->SetEmulating((Compatibility)gb->GetIValue());
    	break;

    case 556: // Axis compensation
    	if(gb->Seen('S'))
    	{
    		value = gb->GetFValue();
    		for(int8_t axis = 0; axis < AXES; axis++)
    			if(gb->Seen(gCodeLetters[axis]))
    				reprap.GetMove()->SetAxisCompensation(axis, gb->GetFValue()/value);
    	}
    	break;

    case 557: // Set Z probe point coordinates
    	if(gb->Seen('P'))
    	{
    		iValue = gb->GetIValue();
    		if(gb->Seen(gCodeLetters[X_AXIS]))
    			reprap.GetMove()->SetXBedProbePoint(iValue, gb->GetFValue());
    		if(gb->Seen(gCodeLetters[Y_AXIS]))
    		    reprap.GetMove()->SetYBedProbePoint(iValue, gb->GetFValue());
    	}
    	break;

    case 558: // Set Z probe type
    	if(gb->Seen('P'))
    		platform->SetZProbeType(gb->GetIValue());
    	break;

    case 559: // Upload config.g
    	if(gb->Seen('P'))
    		str = gb->GetString();
    	else
    		str = platform->GetConfigFile();
        OpenFileToWrite(platform->GetSysDir(), str, gb);
        snprintf(reply, STRING_LENGTH, "Writing to file: %s", str);
    	break;

    case 560: // Upload reprap.htm
         str = INDEX_PAGE;
         OpenFileToWrite(platform->GetWebDir(), str, gb);
         snprintf(reply, STRING_LENGTH, "Writing to file: %s", str);
     	break;

    case 561:
    	reprap.GetMove()->SetIdentityTransform();
    	break;

    case 562: // Reset temperature fault - use with great caution
    	if(gb->Seen('P'))
    	{
    	    iValue = gb->GetIValue();
    	    reprap.GetHeat()->ResetFault(iValue);
    	}
    	break;

    case 876: // TEMPORARY - this will go away...
    	if(gb->Seen('P'))
    	{
    		iValue = gb->GetIValue();
    		if(iValue != 1)
    			platform->SetHeatOn(0);
    		else
    			platform->SetHeatOn(1);
    	}
    	break;

    case 900:
    	result = DoFileCannedCycles("homex.g");
    	break;

    case 901:
    	result = DoFileCannedCycles("homey.g");
    	break;



    case 906: // Set Motor currents
    	for(uint8_t i = 0; i < DRIVES; i++)
    	{
    		if(gb->Seen(gCodeLetters[i]))
    		{
    			value = gb->GetFValue(); // mA
    			platform->SetMotorCurrent(i, value);
    		}
    	}
    	break;

    case 998:
    	if(gb->Seen('P'))
    	{
    	    snprintf(reply, STRING_LENGTH, "%s", gb->GetIValue());
    	    resend = true;
    	}
    	break;
     
    default:
      error = true;
      snprintf(reply, STRING_LENGTH, "invalid M Code: %s", gb->Buffer());
    }
    if(result)
    	HandleReply(error, gb == serialGCode, reply, 'M', code, resend);
    return result;
  }
  
  if(gb->Seen('T'))
  {
    code = gb->GetIValue();
    if(code == selectedHead)
    {
    	if(result)
    		HandleReply(error, gb == serialGCode, reply, 'T', code, resend);
    	return result;
    }

    error = true;
    for(int8_t i = AXES; i < DRIVES; i++)
    {
    	if(selectedHead == i - AXES)
    		reprap.GetHeat()->Standby(selectedHead + 1); // + 1 because 0 is the Bed
    }
    for(int8_t i = AXES; i < DRIVES; i++)
    {    
      if(code == i - AXES)
      {
        selectedHead = code;
        reprap.GetHeat()->Activate(selectedHead + 1); // 0 is the Bed
        error = false;
      }
    }

    if(error)
      snprintf(reply, STRING_LENGTH, "Invalid T Code: %s", gb->Buffer());

    if(result)
    	HandleReply(error, gb == serialGCode, reply, 'T', code, resend);
    return result;
  }
  
  // An empty buffer jumps to here and gets discarded

  if(result)
  	HandleReply(error, gb == serialGCode, reply, 'X', code, resend);

  return result;
}
Exemple #21
0
int cnprocCreateProcess( int *pPId, CnpkPipeFds *pFds, int format, int fdOut )
{


	int command_pipe[2];
	int response_pipe[2];
	int data_pipe[2];
	int pid;


	if( pipe(command_pipe) == -1 ){
		DebugPrint( "Pipe Create Error1 \n");
		goto pipe_error;
	}
	if( pipe(response_pipe) == -1 ){
		DebugPrint( "Pipe Create Error2 \n");
		goto pipe_error;
	}
	if( pipe(data_pipe) == -1 ){
		DebugPrint( "Pipe Create Error3 \n");
		goto pipe_error;
	}

	if( (pid=fork()) == -1 ){
		DebugPrint( "Fork Error: \n");
		goto fork_error;
	}
	else if( pid == 0 ){
		char cmdpipe_opt[32];
		char respipe_opt[32];
		char datpipe_opt[32];
		char format_opt[32];
		char output_opt[32];
		char *module_arg[7];
		char *module_buf = NULL;
		int ret;

		close( command_pipe[1] );
		close( response_pipe[0] );
		close( data_pipe[1] );

		snprintf( format_opt, 31, FORMAT_STR, format );
		snprintf( output_opt, 31, OUTPUT_STR, fdOut );
		snprintf( cmdpipe_opt,31, CMD_PIPE_STR, command_pipe[0] );
		snprintf( respipe_opt,31, RES_PIPE_STR, response_pipe[1] );
		snprintf( datpipe_opt,31, DAT_PIPE_STR, data_pipe[0] );

		module_buf = malloc(strlen(MODULE_PATH)+strlen(MODULE_NAME)+2);
		if( module_buf == NULL ){
			goto malloc_error;
		}

		memset(module_buf, 0, sizeof(module_buf));
		strncpy(module_buf, MODULE_PATH, strlen(MODULE_PATH)+1);
		strcat(module_buf, "/");
		strncat(module_buf, MODULE_NAME, strlen(MODULE_NAME)+1);

		module_arg[0] = module_buf;
		module_arg[1] = format_opt;
		module_arg[2] = output_opt;
		module_arg[3] = cmdpipe_opt;
		module_arg[4] = respipe_opt;
		module_arg[5] = datpipe_opt;
		module_arg[6] = NULL;

		ret = execv(module_buf, module_arg);
		if( ret == -1 ){
			DebugPrint( "exec Error \n");
			exit(-1);

		}
	}
	else{
		close( command_pipe[0] );
		close( response_pipe[1] );
		close( data_pipe[0] );
	}

	*pPId = pid;
	pFds->cmd_fd = command_pipe[1];
	pFds->res_fd = response_pipe[0];
	pFds->dat_fd = data_pipe[1];

	return 0;

 malloc_error:
 fork_error:
 pipe_error:
	return -1;

}
Exemple #22
0
BOOL TEST_LOAD_DATABASE(FILE *ptr_file)
{
   BOOL number_flag = TRUE;  
   char buf[DATABASE_LINE_SIZE];
   char *database_temp;
   int  bytecounter = 0;
   BOOL found = FALSE;

   strcpy(databaseblock, "");
   while (!full_buffer)
   //while (fgets(buf, 1000, ptr_file) != NULL)
   {
      if(bytecounter + DATABASE_LINE_SIZE > DATABASE_BLOCK_SIZE)
      {
         full_buffer = TRUE;
		 bytecounter = 0;
      }
      else
      {
         //printf("%s", buf);
		 if(fgets(buf, DATABASE_LINE_SIZE, ptr_file) == NULL){
			 printf("07: Cant read file\n");
			 return FALSE;
		 }
         linecounter++;
         if (found)
         {
           if (strncmp(buf, endMakerdata, EndMarkersize) == 0)
           {
             //printf("[Binh]%s", buf);
             found = FALSE;
           }
           else
           {
              /* get the first token */
              database_temp = strtok(buf, delimiter);
              number_flag = TRUE;
              /* walk through other tokens */
              strcpy(database_line, "");
              while (database_temp != NULL){

                 if (number_flag == FALSE){
                    //printf("%s", database_temp);
                    strcat(database_line, database_temp);
                 }
                 else
                 {
                    number_flag = FALSE;
                 }
                 database_temp = strtok(NULL, delimiter);
              }
              //printf(database_line);
              CovertQuery2Bit(database_line, strlen(database_line),
                              database_convert_byte, strlen(database_line) / 3 + 1);
              //printHexString(database_convert_byte);
			  strncat(databaseblock,database_convert_byte,strlen(database_line));
              bytecounter += strlen(database_line);
           }
        }
        else if (strncmp(buf, startMakerdata, StartMarkersize) == 0){
          //printf("[Binh] %s", buf);
          found = TRUE;
        }
      }
   }
   printHexString(databaseblock);
   full_buffer = FALSE; //reset for next reading
   printf("#line: %d", linecounter);
   return TRUE;
}
Exemple #23
0
static window_event_result browser_handler(UI_DIALOG *const dlg, const d_event &event, ui_file_browser *const b)
{
	window_event_result rval = window_event_result::ignored;

	if (event.type == EVENT_UI_DIALOG_DRAW)
	{
		ui_dputs_at( dlg, 10, 5, b->message );

		ui_dprintf_at( dlg, 20, 32,"N&ame" );
		ui_dprintf_at( dlg, 20, 86,"&Files" );
		ui_dprintf_at( dlg, 210, 86,"&Dirs" );
		
		ui_dputs_at(dlg, 20, 60, b->spaces.data());
		ui_dputs_at( dlg, 20, 60, b->view_dir );
		
		return window_event_result::handled;
	}

	if (GADGET_PRESSED(b->button2.get()))
	{
		b->filename_list.reset();
		b->directory_list.reset();
		return window_event_result::close;
	}
	
	if (GADGET_PRESSED(b->help_button.get()))
	{
		ui_messagebox( -1, -1, 1, "Sorry, no help is available!", "Ok" );
		rval = window_event_result::handled;
	}
	
	if (event.type == EVENT_UI_LISTBOX_MOVED)
	{
		if ((ui_event_get_gadget(event) == b->listbox1.get()) && (b->listbox1->current_item >= 0) && b->filename_list[b->listbox1->current_item])
			ui_inputbox_set_text(b->user_file.get(), b->filename_list[b->listbox1->current_item]);

		if ((ui_event_get_gadget(event) == b->listbox2.get()) && (b->listbox2->current_item >= 0) && b->directory_list[b->listbox2->current_item])
			ui_inputbox_set_text(b->user_file.get(), b->directory_list[b->listbox2->current_item]);

		rval = window_event_result::handled;
	}
	
	if (GADGET_PRESSED(b->button1.get()) || GADGET_PRESSED(b->user_file.get()) || event.type == EVENT_UI_LISTBOX_SELECTED)
	{
		char *p;
		
		if (ui_event_get_gadget(event) == b->listbox2.get())
			strcpy(b->user_file->text.get(), b->directory_list[b->listbox2->current_item]);
		
		strncpy(b->filename, b->view_dir, PATH_MAX);
		
		p = b->user_file->text.get();
		while (!strncmp(p, "..", 2))	// shorten the path manually
		{
			char *sep = strrchr(b->filename, '/');
			if (sep)
				*sep = 0;
			else
				*b->filename = 0;	// look directly in search paths
			
			p += 2;
			if (*p == '/')
				p++;
		}
		
		if (*b->filename && *p)
			strncat(b->filename, "/", PATH_MAX - strlen(b->filename));
		strncat(b->filename, p, PATH_MAX - strlen(b->filename));
		
		if (!PHYSFS_isDirectory(b->filename))
		{
			if (RAIIPHYSFS_File{PHYSFS_openRead(b->filename)})
			{
				// Looks like a valid filename that already exists!
				return window_event_result::close;
			}
			
			// File doesn't exist, but can we create it?
			if (RAIIPHYSFS_File TempFile{PHYSFS_openWrite(b->filename)})
			{
				TempFile.reset();
				// Looks like a valid filename!
				PHYSFS_delete(b->filename);
				return window_event_result::close;
			}
		}
		else
		{
			if (b->filename[strlen(b->filename) - 1] == '/')	// user typed a separator on the end
				b->filename[strlen(b->filename) - 1] = 0;
			
			strcpy(b->view_dir, b->filename);
			b->filename_list = file_getfilelist(b->filespec, b->view_dir);
			if (!b->filename_list)
			{
				b->directory_list.reset();
				return window_event_result::close;
			}
			
			ui_inputbox_set_text(b->user_file.get(), b->filespec);
			b->directory_list = file_getdirlist(b->view_dir);
			if (!b->directory_list)
			{
				b->filename_list.reset();
				return window_event_result::close;
			}
			
			ui_listbox_change(dlg, b->listbox1.get(), b->filename_list.get_count(), b->filename_list.get());
			ui_listbox_change(dlg, b->listbox2.get(), b->directory_list.get_count(), b->directory_list.get());
			
			//i = TICKER;
			//while ( TICKER < i+2 );
			
		}
		
		rval = window_event_result::handled;
	}
	
	return rval;
}
Exemple #24
0
/* initenv ()  initializes the environment */
void initenv (int argc, char **argv, struct mngmsg *m_msp, 
		 struct pstruct *ppst, unsigned char **aa0)
{
   char *cptr, ctmp;
   long l_tmp;
   int  copt, itmp, i;

   /* options for all search functions */
   /* char   *g_optstr = "b:BC:d:DE:F:HiK:l:Lm:N:O:QqR:T:v:V:w:W:X:Z:"; */

   char g_optstring[MAX_STR];
   char f_optstring[MAX_STR];
   char optstring[MAX_STR];

   build_optstr(g_optstring, sizeof(f_optstring), g_options);
   build_optstr(f_optstring, sizeof(f_optstring), f_options);

/*  these initializations will be used by all functions */

   /* prog_name[] is only used for error messages */
   strncpy(prog_name,argv[0],sizeof(prog_name));
   prog_name[sizeof(prog_name)-1]='\0';

#ifdef PCOMPLIB
#ifdef MPI_SRC
  MPI_Comm_size(MPI_COMM_WORLD,&fa_max_workers);
  if (fa_max_workers <= 1) {
    fprintf(stderr," nnodes = %d; no workers available\n",fa_max_workers);
    exit(1);
  }
  else {
    fa_max_workers -= FIRSTNODE;
    fprintf(stderr," have %d workers\n",fa_max_workers);
  }
#endif
#else
#if defined(IRIX)
   fa_max_workers = sysmp(MP_NPROCS);
#else
#if defined(UNIX) || defined(HAVE_SYSCONF)
   fa_max_workers = sysconf(_SC_NPROCESSORS_CONF);
#endif	/* UNIX || SYSCONF */
#endif  /* !IRIX */
#endif  /* !PCOMPLIB */

   m_msp->ltitle[0] = '\0';

   if ((cptr=getenv("FASTLIBS"))!=NULL) {
     strncpy(m_msp->flstr,cptr,MAX_FN);
     m_msp->flstr[MAX_FN-1] = '\0';
   }
   else m_msp->flstr[0]='\0';

   m_msp->std_output = 1;
   m_msp->hist.hist_a = NULL;
   m_msp->outfile[0] = '\0';
   m_msp->outfd = NULL;
   m_msp->ldb_info.ldnaseq = SEQT_PROT;	/* library is protein */
   m_msp->n1_low = ppst->n1_low = 0;
   m_msp->n1_high = ppst->n1_high = BIGNUM;
   m_msp->ql_start = 1;	/* start with first query sequence */
   m_msp->ql_stop = BIGNUM;	/* end with the last query sequence */
   m_msp->aa1save_buf_b = NULL;
   m_msp->bline_buf_b = NULL;

   m_msp->pamd1 = MAXSQ;
   m_msp->pamd2 = MAXSQ;

   m_msp->ldb_info.term_code = 0;
   ppst->tr_type = 0;
   ppst->debug_lib = 0;
   m_msp->nshow = 20;
   ppst->max_repeat = 50;
   m_msp->nohist = 1;
#if defined(PCOMPLIB)
   m_msp->mshow = 20;
#else
#ifdef SHOW_HIST
   m_msp->nohist = 0;
#endif
   m_msp->mshow = 50;
#endif
   m_msp->do_showbest = 1;
   m_msp->ashow = -1;
   m_msp->ashow_set = 0;
   m_msp->nmlen = DEF_NMLEN;
   m_msp->z_bits = 1;
   m_msp->mshow_set = 0;
   m_msp->mshow_min = 0;
   m_msp->aln.llen = 60;
   m_msp->aln.llcntx = 30;
   m_msp->aln.llcntx_set = 0;
   m_msp->e_low = 0.0;
   m_msp->e_cut_set = 0;
   m_msp->revcomp = 0;
   m_msp->long_info = 0;
   m_msp->ldb_info.maxn = 0;
   m_msp->ldb_info.dupn = SEQDUP;
   m_msp->dfile[0] = '\0';
   m_msp->tname[0] = '\0';
   m_msp->lname[0] = '\0';
   m_msp->link_lname[0] = '\0';
   m_msp->show_code = 0;
   m_msp->aln.showall = 0;
   m_msp->markx = 0;
   m_msp->markx_list = NULL;
   m_msp->align_done = 0;
   m_msp->sq0off = m_msp->sq1off = 1;
   strncpy(m_msp->sqnam,"aa",4);
   strncpy(m_msp->sqtype,"protein",10);
   m_msp->ann_flg = 0;
   m_msp->ann_arr[0] = '\0';
   m_msp->aa0a = NULL;
   
   ppst->LK_set = 0;
   ppst->e_cut = m_msp->e_cut = 10.0;
   ppst->e_cut_r = ppst->e_cut / 10.0;
   ppst->do_rep = 1;
   ppst->zs_win = 0;
   ppst->show_ident = 0;

   ppst->zdb_size = -1;
   ppst->zdb_size_set = 0;
   ppst->dnaseq = SEQT_PROT;	/* default is protein */
   ppst->nt_align = 0;

   ppst->other_info = NULL;

   g_init_opts(m_msp, ppst);

   f_initenv (m_msp, ppst, aa0);

   if (argc == 1) {
     show_help(m_msp->pgm_name, ppst->pgm_id);
   }
   if (strcmp(argv[1],"-help")==0) {
     show_all_help(m_msp->pgm_name, ppst->pgm_id);
   }

   strncpy (optstring, g_optstring, sizeof (optstring));
   strncat (optstring, f_optstring, sizeof (optstring));

   while ((copt = getopt (argc, argv, optstring)) != EOF)
   {
      if (strchr (g_optstring, copt) != NULL)
      {
	switch (copt) {  /* switches for all options */
	case 'C': 
	  sscanf(optarg,"%d",&m_msp->nmlen);
	  if (m_msp->nmlen > MAX_UID-1) m_msp->nmlen = MAX_UID-1;
	  break;
	case 'D': ppst->debug_lib = 1;
	  break;
	case 'e': 
	  strncpy(m_msp->link_lname, optarg, MAX_LSTR);
	  break;
	case 'F':
	  sscanf(optarg,"%lg",&m_msp->e_low);
	  m_msp->e_cut_set = 1;
	  break;
#if defined(PCOMPLIB) || !defined(SHOW_HIST)
	case 'H':
	  m_msp->nohist = 0; break;
#else
	case 'H':
	  m_msp->nohist = 1; break;
#endif
	case 'i':
	  m_msp->revcomp = 1; break;
	case 'I':
	  m_msp->quiet = 0; break;
	case 'l':
	  strncpy(m_msp->flstr,optarg,MAX_FN);
	  m_msp->flstr[MAX_FN-1]='\0';
	  break;
	case 'L':
	  m_msp->long_info = 1;
	  long_info_set = 1;
	  break;
	case 'm':
	  pre_parse_markx(optarg, m_msp);
	  break;
	case 'N':
	  sscanf(optarg,"%d",&m_msp->ldb_info.maxn);
	  break;
	case 'o':
	  sscanf (optarg,"%ld %ld",&m_msp->sq0off,&m_msp->sq1off); break;
	case 'O':
	  strncpy(m_msp->outfile,optarg,MAX_FN);
	  m_msp->outfile[MAX_FN-1]='\0';
	  break;
	case 'q':
	case 'Q':
	  m_msp->quiet = 1;
	  break;
	case 'R':
	  strncpy (m_msp->dfile, optarg, MAX_FN);
	  m_msp->dfile[MAX_FN-1]='\0';
	  break;
	case 'T':
#ifdef PCOMPLIB
	  if (strchr(optarg,'-') != NULL) {
	    sscanf(optarg,"%d-%d",&worker_1,&worker_n);
	    if (worker_1 > worker_n) {
	      worker_1 = worker_n = 0;
	    }
	  }
	  else 
#endif
	    sscanf (optarg, "%d", &fa_max_workers);
	  if (fa_max_workers < 0) fa_max_workers=1;
	  break;
	case 'v':
	  sscanf (optarg,"%d",&ppst->zs_win);
	  break;
	case 'V':
	  strncpy(m_msp->ann_arr+1,optarg,MAX_FN-2);
	  m_msp->ann_arr[0]='\0';
	  m_msp->ann_arr[MAX_FN-2]='\0';
	  m_msp->ann_flg = 1;
	  add_ascii_ann(qascii, m_msp->ann_arr);
	  break;
/*
	case 'V':
	  fprintf(stderr," -V option not currently supported in parallel\n");
	  break;
*/
	case 'w':
	  sscanf (optarg,"%d",&m_msp->aln.llen);
	  if (m_msp->aln.llen < 10) m_msp->aln.llen = 10;
	  if (m_msp->aln.llen > 200) m_msp->aln.llen = 200;
	  if (!m_msp->aln.llcntx_set) m_msp->aln.llcntx = m_msp->aln.llen/2;
	  llen_set = 1;
	  break;
	case 'Z':
	  sscanf(optarg,"%ld",&ppst->zdb_size);
	  ppst->zdb_size_set = 1;
	  break;
	}
      }
      else if (strchr (f_optstring, copt))
	 f_getopt (copt, optarg, m_msp, ppst);
   }
   optind--;

   f_lastenv (m_msp, ppst);

   if (argc - optind < 3) return;
   m_msp->tnamesize = sizeof (m_msp->tname);
   if (argc - optind > 1) {strncpy (m_msp->tname, argv[optind + 1],MAX_FN);}
   if (argc - optind > 2) {strncpy(m_msp->lname, argv[optind + 2],MAX_LSTR);}
   f_getarg (argc, argv, optind, m_msp, ppst);
}
Exemple #25
0
Inform& Inform::operator<<(const char *s) {
  strncat(buf, s, MAX_MSG_SIZE - strlen(buf));
  return *this;
}
Exemple #26
0
int main(int argc, char ** argv)
{
    char * sender;

    char * message;
    unsigned int time_message;
    unsigned int timer;
    unsigned int num;
    char * message_filename;
    char * dir;

    char * ptr;
    char * my_delivered_to;

    DIR * dirp;
    struct dirent * direntp;
    unsigned int message_time;
    char * address;
    unsigned int count;
    char filename[256];
    FILE * f;
    unsigned int message_handling = DEFAULT_MH;
    char buffer[256];
    char *content_boundary;
    char *rpath = DEFAULT_FROM;
    char *TheUser;
    char *TheDomain;

    if(argc > 7 || argc < 5) {
        fprintf(stderr, "\nautorespond: ");
        fprintf(stderr, "usage: time num message dir [ flag arsender ]\n\n");
        fprintf(stderr, "time - amount of time to consider a message (in seconds)\n");
        fprintf(stderr, "num - maximum number of messages to allow within time seconds\n");
        fprintf(stderr, "message - the filename of the message to send\n");
        fprintf(stderr, "dir - the directory to hold the log of messages\n\n");
        fprintf(stderr, "optional parameters:\n\n");
        fprintf(stderr, "flag - handling of original message:\n\n");
        fprintf(stderr, "0 - append nothing\n");
        fprintf(stderr, "1 - append quoted original message without attachments <default>\n\n");
        fprintf(stderr, "arsender - from address in generated message, or:\n\n");
        fprintf(stderr, "+ = blank from envelope !\n");
        fprintf(stderr, "$ = To: address will be used\n\n");
        _exit(111);
    }

    TheUser= getenv("EXT");
    TheDomain= getenv("HOST");

    setvbuf(stderr, NULL, _IONBF, 0);

    if(argc > 7 || argc < 5) {
        fprintf(stderr, "AUTORESPOND: Invalid arguments. (%d)\n",argc);
        _exit(111);
    }

    time_message     = strtoul(argv[1],NULL,10);
    num              = strtoul(argv[2],NULL,10);
    message_filename = argv[3];
    dir              = argv[4];

    if ( argc > 5 )
        message_handling = strtoul(argv[5],NULL,10);
    if ( argc > 6 )
        rpath = argv[6];

    if ( *rpath == '+' )
        rpath = "";
    if ( *rpath == '$' )
    {
        rpath = safe_malloc( strlen(TheUser) + strlen(TheDomain) + 2);
        strncpy( rpath, TheUser, strlen(TheUser) );
        strncat( rpath, "@", 1 );
        strncat( rpath, TheDomain, strlen(TheDomain) );
    }

    timer = time(NULL);

    /*prepare the "delivered-to" string*/
    my_delivered_to = "Delivered-To: Autoresponder\n";

    read_headers( stdin );


    message = read_file(message_filename);
    if(message==NULL) {
        fprintf(stderr, "AUTORESPOND: Failed to open message file.\n");
        _exit(111);
    }

    /*don't autorespond in certain situations*/
    sender = getenv("SENDER");
    if(sender==NULL)
        sender = "";

    /*don't autorespond to a mailer-daemon*/
    if( sender[0]==0 || strncasecmp(sender,"mailer-daemon",13)==0 || strchr(sender,'@')==NULL || strcmp(sender,"#@[]")==0 ) {
        /*exit with success and continue parsing .qmail file*/
        fprintf(stderr,"AUTORESPOND:  Stopping on mail from [%s].\n",sender);
        _exit(0);
    }


    if ( inspect_headers("mailing-list", (char *)NULL ) != (char *)NULL )
    {
        fprintf(stderr,"AUTORESPOND: This looks like it's from a mailing list, I will ignore it.\n");
        _exit(0);			/*report success and exit*/
    }
    if ( inspect_headers("Delivered-To", "Autoresponder" ) != (char *)NULL )
    {
        /*got one of my own messages...*/
        fprintf(stderr,"AUTORESPOND: This message is looping...it has my Delivered-To header.\n");
        _exit(100);			/*hard error*/
    }
    if ( inspect_headers("precedence", "junk" ) != (char *)NULL ||
            inspect_headers("precedence", "bulk" ) != (char *)NULL ||
            inspect_headers("precedence", "list" ) != (char *)NULL )
    {
        fprintf(stderr,"AUTORESPOND: Junk mail received.\n");
        _exit(0); /* don't reply to bulk, junk, or list mail */
    }

    /*check the logs*/
    if(chdir(dir) == -1) {
        fprintf(stderr,"AUTORESPOND: Failed to change into directory.\n");
        _exit(111);
    }

    /*add entry*/
    sprintf(filename,"A%u.%u",getpid(),timer);
    f = fopen(filename,"wb");
    if(f==NULL) {
        fprintf(stderr,"AUTORESPOND: Unable to create file for [%s].",sender);
        _exit(111);
    }
    if(fwrite(sender,1,strlen(sender),f)!=strlen(sender)) {
        fprintf(stderr,"AUTORESPOND: Unable to create file for [%s].",sender);
        fclose(f);
        unlink(filename);
        _exit(111);
    }
    fclose(f);

    /*check if there are too many responses in the logs*/
    dirp = opendir(".");
    count = 0;
    while((direntp = readdir(dirp)) != NULL) {
        if(direntp->d_name[0] != 'A')
            continue;
        ptr = strchr(direntp->d_name,'.');
        if(ptr==NULL)
            continue;
        message_time = strtoul(ptr+1,NULL,10);
        if(message_time < timer-time_message) {
            /*too old..ignore errors on unlink*/
            unlink(direntp->d_name);
        } else {
            address = read_file(direntp->d_name);
            if(address==NULL) {
                /*ignore this?*/
                continue;
            }
            if(strcasecmp(address,sender)==0) {
                count++;
            }
            free(address);
        }
    }
    if(count>num) {
        fprintf(stderr,"AUTORESPOND: too many received from [%s]\n",sender);
        _exit(0); /* don't reply to this message, but allow it to be delivered */
    }

    sprintf(filename,"tmp%u.%u",getpid(),timer);
    f = fopen(filename,"wb");

    fprintf( f, "%sTo: %s\nFrom: %s\nSubject: Re:%s\n%s\n",
             my_delivered_to, sender, rpath, inspect_headers( "Subject", (char *) NULL ), message );

    if ( message_handling == 1 ) {
        fprintf( f, "%s\n\n", "-------- Original Message --------" );
        if ( (content_boundary = get_content_boundary()) == (char *)NULL )
        {
            while ( fgets( buffer, sizeof(buffer), stdin ) != NULL )
            {
                fputs( "> ", f );
                fputs( buffer, f );
            }
        } else
        {
            int content_found = 0;
            while ( fgets( buffer, sizeof(buffer), stdin ) != NULL )
            {
                if ( content_found == 1 )
                {
                    if ( strstr( buffer, content_boundary ) != (char *)NULL )
                        break;
                    fputs( "> ", f );
                    fputs( buffer, f );
                }
                if ( strstr( buffer, content_boundary ) != (char *)NULL )
                {
                    if ( content_found == 1 )
                        break;
                    else
                    {
                        free_headers();
                        read_headers( stdin );
                        if ( inspect_headers("Content-Type", "text/plain" ) != (char *)NULL )
                            content_found = 1;
                        continue;
                    }
                }
            }
        }
    }

    fprintf( f, "\n\n" );

    fclose( f );

    /*send the autoresponse...ignore errors?*/
    send_message(filename,rpath,&sender,1);

    unlink( filename );

    _exit(0);
    return 0;					/*compiler warning squelch*/
}
Exemple #27
0
Inform& Inform::operator<<(unsigned long u) {
  char tmpbuf[128];
  sprintf(tmpbuf, "%ld", u);
  strncat(buf, tmpbuf, MAX_MSG_SIZE - strlen(buf));
  return *this;
}
Exemple #28
0
int main(int argc, char *argv[]) {

    int fd = 0, dfd = 0, stringsize, leido, opt, sourceflag = 0, cpal = 0, file = 0, help = 0, auxcount = 0;

    char source[100];

    char *pal1;

    char *pal2;

    char *pal3;

    char* path;

    char buff[1];

    char auxbuff[150];
    char* pch;


    extern char *optarg;
    extern int optind, opterr, optopt;


    while ((opt = getopt(argc, argv, "s:1:2:3:f:h")) != -1) {
        switch (opt) {
            case 's':
                strcpy(source, optarg);
                sourceflag = 1;
                break;

            case '1':
                pal1 = malloc(sizeof (int)*strlen(optarg));
                strcpy(pal1, optarg);
                cpal++;
                break;

            case '2':
                pal2 = malloc(sizeof (int)*strlen(optarg));
                strcpy(pal2, optarg);
                cpal++;
                break;

            case '3':
                pal3 = malloc(sizeof (int)*strlen(optarg));
                strcpy(pal3, optarg);
                cpal++;
                break;

            case 'f':
                path = malloc(sizeof (int)*strlen(optarg));
                strcpy(path, optarg);
                file = 1;
                break;

            case 'h':
                help = 1;

                write(1, "Uso: censurar -1 [PALABRA] \n\n Censura las palabras indicadas y las reemplaza por caracteres ? \n\n -s [NOMBRE DE ARCHIVO] Seleccionar el nombre del archivo fuente para censurar \n                        (Source), si se omite se lee el stdin. \n -f [NOMBRE DE ARCHIVO] Seleccionar el nombre del archivo destino para la cens\n                        ura, si se omite la salida sera por stdout. \n -2 [PALABRA]           Seleccionar una segunda palabra adicional para censurar. \n -3 [PALABRA]           Seleccionar una tercera palabra adicional para censurar. \n -h                     Ver este archivo de ayuda. \n\n Nota: Para usar el parametro -2 y -3 se necesita haber usado los parametros anteriores.\n\n", 696);
                break;
        }
    }

    if (cpal == 0 && help == 0) { //Si el contador de palabras está en cero significa que no se insertaron palabras
        write(2, "No se insertaron palabras a buscar! \n", 37);
        return -1;
    } else if (help == 1) {
        return 0;
    }


    if (sourceflag == 1) { //Si se marca el Source, se le asigna el file descriptor al archivo sino se deja en 0


        fd = open(source, O_RDONLY);

        if (fd < 0) {

            perror("Source open()");
            return -1;
        }

    } else {
        fd = 0;
    }


    if (file == 1) { // Si se especificó un destino se crea o se abre el archivo.
        dfd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0777);

        if (dfd < 0) {

            perror("Destination open()");
            return -1;
        }
    }



    memset(auxbuff, 0, sizeof auxbuff);

    while (((leido = read(fd, buff, sizeof buff)) > 0)) { //Leo letra a letra el input.

        if (buff[0] == ' ' || buff[0] == ('.') || buff[0] == ',' || buff[0] == ':' || buff[0] == ';') { //Si la letra es un espacio lo contenido en el buffer de palabra es una palabra

            stringsize = strlen(pal1); //Calculo la longitud de la palabra a buscar.

            pch = strstr(auxbuff, pal1); //La comparo con la palabra que leí.

            if (pch != 0 && stringsize == auxcount) { //Si hay coincidencia se reemplaza por los signos ?.
                strncpy(pch, "?????????????????????", stringsize);
            } else if (cpal > 1) { //Si no hubo coincidencia y hay una segunda palabra a buscar se repite el proceso.

                stringsize = strlen(pal2);

                pch = strstr(auxbuff, pal2);

                if (pch != 0 && stringsize == auxcount) {
                    strncpy(pch, "?????????????????????", stringsize);
                } else if (cpal > 2) { //Si aún no hubo coincidencia y hay una tercera palabra se repite nuevamente.

                    stringsize = strlen(pal3);

                    pch = strstr(auxbuff, pal3);

                    if (pch != 0 && stringsize == auxcount) {
                        strncpy(pch, "?????????????????????", stringsize);
                    }

                }
            }

            switch (buff[0]) { //ya que el ultimo caracter fue ignorado y no se introdujo en el buffer. Se lo agregamos a la salida
                case ' ':
                    strncat(auxbuff, " ", 1);
                    break;
                case 46:
                    strncat(auxbuff, ".", 1);
                    break;
                case ',':
                    strncat(auxbuff, ",", 1);
                    break;
                case ':':
                    strncat(auxbuff, ":", 1);
                    break;
                case ';':
                    strncat(auxbuff, ";", 1);
                    break;
                default:
                    strncat(auxbuff, " ", 1);
                    break;
            }




            if (file == 1) { //Si esta en 1 el flag de destino se escribe en destino sino en stdout
                write(dfd, auxbuff, auxcount + 1);
            } else {
                write(1, auxbuff, auxcount + 1);
            }


            memset(auxbuff, 0, sizeof auxbuff); //Se vacia el buffer que contiene la palabra para leer la proxima

            auxcount = 0; //Se reinicia el contador de caracteres del buffer.
        } else {
            strncat(auxbuff, buff, 1); //Si la letra no era un espacio se inserta en el buffer de palabra.

            auxcount++; //Se aumenta el contador de caracteres del buffer.
        }



    }

    //Si abrí archivos los cierro al finalizar.

    if (sourceflag == 1)
        close(fd);

    if (file == 1)
        close(dfd);

    printf("\n");

    return 0;
}
Exemple #29
0
int
CSDPSInit(
    Display *dpy,
    int *numberType,		/* RETURN */
    char **floatingName)	/* RETURN */
{
    register Display *agent;
    register xCAPConnReplyPrefix *p;
    register char *c;
    DPSCAPData my;
    xCAPConnSetupReq setup;
    union {
        xCAPConnSuccess good;
        xCAPConnFailed bad;
    } reply;
    XExtData *extData;
    XExtCodes *codes;
    int indian;
    int rest;
    Window clientWindow;
    char fullDisplayName[MAXHOSTNAMELEN+10];

    if (gCSDPS == NULL)
        DPSCAPStartUp();

    /* To fix dps-nx #68, Motif too slow on HP */
    if ((c = getenv("DPSNXGCMODE")) != 0)
        {
	gNXSyncGCMode = atoi(c);
	if (gNXSyncGCMode < DPSNXSYNCGCMODE_FLUSH
	  || gNXSyncGCMode > DPSNXSYNCGCMODE_DELAYED)
	    gNXSyncGCMode = DPSNXSYNCGCMODE_DEFAULT;
	}

    /* We may have already called this routine via XDPSExtensionPresent,
       so don't do it again! */

    if ((codes = XDPSLGetCodes(dpy))
        && (agent = XDPSLGetShunt(dpy))
        && agent != dpy
	&& codes->major_opcode == DPSXOPCODEBASE)
        return(DPSCAPSUCCESS);

    /* Try to create a window for ClientMessage communication */

    clientWindow = XCreateSimpleWindow(
      dpy,
      DefaultRootWindow(dpy),
      0, 0,
      1, 1,
      0,
      BlackPixel(dpy, DefaultScreen(dpy)),
      WhitePixel(dpy, DefaultScreen(dpy)));
    if (clientWindow == None)
        return(DPSCAPFAILED);

    /* Try to open a connection to an agent */

    if ((extData = DPSCAPOpenAgent(dpy, fullDisplayName)) == NULL)
        {
        XDestroyWindow(dpy, clientWindow);
        return(DPSCAPFAILED);
        }

    /* DPSCAPOpenAgent only partially fills in extData, so finish it */

    codes = XAddExtension(dpy);
    codes->major_opcode = DPSXOPCODEBASE;
    codes->first_event = 0;  /* REQUIRED */
    codes->first_error = FirstExtensionError;
    extData->number = codes->extension;
    extData->free_private = DPSCAPDestroy;
    my = (DPSCAPData) extData->private_data;
    my->codes = codes;
    agent = my->agent;
    /* +++ Is this all we have to do here? */

    /* Send opening handshake */

    indian = 1;
    if (*(char *) &indian)
        setup.byteorder = 'l';
    else
    	setup.byteorder = 'B';
    setup.dpscapVersion = DPSCAPPROTOVERSION;
    setup.flags = DPSCAPNONEFLAG;
    setup.libraryversion = DPSPROTOCOLVERSION;
    setup.authProtoNameLength = 0;
    setup.authProtoDataLength = 0;
    setup.displayStringLength = strlen(fullDisplayName);
    setup.nodeStringLength = 0;
    setup.transportStringLength = 0;
    setup.display = 0;
    setup.screen = 0;
    setup.reserved = 0;
    setup.clientWindow = clientWindow;

#ifndef DPSLNKL
    DPSCAPWrite(agent, (char *)&setup, sizeof(xCAPConnSetupReq), dpscap_nopad,dpscap_insert);
    DPSCAPWrite(agent, fullDisplayName, setup.displayStringLength, dpscap_pad, dpscap_append);
    N_XFlush(agent);
#else /* DPSLNKL */
    if (CSDPSConfirmDisplay(agent, dpy, &setup, &reply, fullDisplayName) == 1)
        {
	p = (xCAPConnReplyPrefix *)&reply.good;
        goto skip_read;
	}
    /* Read normal reply */
#endif /* DPSLNKL */

    /* Read common reply prefix */

    p = (xCAPConnReplyPrefix *)&reply.good;
    N_XRead(agent, (char *)p, (long)sizeof(xCAPConnReplyPrefix));
#ifdef DPSLNKL
skip_read:
#endif
    if (!p->success)
        {
	char mbuf[512];
        /* read the rest */
        c = (char *)&reply.bad.serverVersion;
        N_XRead(agent, c, sz_xCAPConnFailed - sz_xCAPConnReplyPrefix);
	sprintf(mbuf, "DPS NX: connection to \"%s\" refused by agent.", DisplayString(agent));
	DPSWarnProc(NULL, mbuf);
        c = (char *)Xmalloc(reply.bad.reasonLength);
        if (!c) return(DPSCAPFAILED);
        N_XReadPad(agent, c, (long)reply.bad.reasonLength);
	if (!reply.bad.reasonLength)
	    sprintf(mbuf, "DPS NX: (no reason given)\n");
	else
            {
	    strcpy(mbuf, "DPS NX: ");
	    strncat(mbuf, c, reply.bad.reasonLength);
	    mbuf[reply.bad.reasonLength+7] = '\0';
	    }
	DPSWarnProc(NULL, mbuf);
        Xfree(c);
        DPSCAPDestroy(extData);
        Xfree(extData);
        XDestroyWindow(dpy, clientWindow);
        return(DPSCAPFAILED);
        }

    /* read the rest of the fixed length reply */
    c = (char *)&reply.good.serverVersion;
    rest = sizeof(xCAPConnSuccess) - sizeof(xCAPConnReplyPrefix);
    N_XRead(agent, c, rest);

    /* verify */

    if (reply.good.serverVersion < DPSPROTOCOLVERSION)
        {
	/* Fine, we downgrade the client */
	char qbuf[256];
	sprintf(qbuf, "NX: server version %ld older than expected %d, client will downgrade", (long)reply.good.serverVersion, DPSPROTOCOLVERSION);
	DPSWarnProc(NULL, qbuf);
	}
    my->dpscapVersion = reply.good.dpscapVersion;
    if (my->dpscapVersion < DPSCAPPROTOVERSION)
        {
	/* Fine, we downgrade the client */
	char kbuf[256];
	sprintf(kbuf, "NX: agent version %d older than expected %d, client will downgrade", my->dpscapVersion, DPSCAPPROTOVERSION);
	DPSWarnProc(NULL, kbuf);
#ifdef XXX
        /* Saving this code as a reminder about what needs to be
	   cleaned up if we exit here */
        DPSCAPDestroy(extData);
        Xfree(extData);
        XDestroyWindow(clientWindow);
        return(DPSCAPFAILED);
#endif
	}

    if (numberType)
        *numberType = reply.good.preferredNumberFormat;

    /* read additional data */

    c = (char *)Xmalloc(reply.good.floatingNameLength + 1);
    N_XReadPad(agent, c, reply.good.floatingNameLength);
    c[reply.good.floatingNameLength] = 0;
    if (floatingName)
	*floatingName = c;
    else
	Xfree(c);

    /* set library extension data */

    XDPSLSetVersion(agent, reply.good.serverVersion);
    XDPSLSetVersion(dpy, reply.good.serverVersion);
    XDPSLSetShunt(dpy, agent);
    XDPSLSetCodes(dpy, codes);
    if (XDPSLGetSyncMask(dpy) == DPSCAP_SYNCMASK_NONE)
        XDPSLSetSyncMask(dpy, DPSCAP_SYNCMASK_DFLT);
    my->agentWindow = reply.good.agentWindow;
    XDPSLSetGCFlushMode(dpy, XDPSNX_GC_UPDATES_SLOW); /* default */

    /* Hook my extension data on the dpy */

    my->extData = extData;
    XAddToExtensionList(CSDPSHeadOfDpyExt(dpy), extData);
    (void) XESetCloseDisplay(dpy, codes->extension, DPSCAPCloseDisplayProc);
    (void) XESetCopyGC(dpy, codes->extension, DPSCAPCopyGCProc);
    (void) XESetFreeGC(dpy, codes->extension, DPSCAPFreeGCProc);
    (void) XESetFlushGC(dpy, codes->extension, DPSCAPFlushGCProc);
    XDPSLSetClientMessageHandler(dpy);

    /* Chain my data on global list */

    my->next = gCSDPS->head;
    gCSDPS->head = my;

#ifdef MAHALO
    /* Set function that is called after every Xlib protocol proc */
    XDPSLSetAfterProc(dpy);

    /* All CSDPS protocol is auto-flushed */
    (void) XSetAfterFunction(agent, DPSCAPFlushAfterProc);
#endif /* MAHALO */

    /* set agent arguments, if needed */
    /* must follow setting of ShuntMap at least, so safest to
       do here when everything has been setup */
    XDPSLUpdateAgentArgs(dpy);

    return(DPSCAPSUCCESS);
}
Exemple #30
0
void ACConfig(instance_parameter *ins_para,struct list *lpublic,struct list *lwcontrol,struct list *lwlan)
{
	int ret = 0; 
    int flag = 1;
	char *endptr = NULL; 
    char mtu[20] = { 0 };
    char log_stat[20] = { 0 };
    char log_size[20] = { 0 };
	char ap_static_state[5] = { 0 };
	int static_state = 0;
	char ac_exten_infor_switch[10] = { 0 };
	char neidead_inter[10] = { 0 };
	char asd_arp_listen_switch[10] = { 0 };
	char asd_log_level[10] = { 0 };
	char response_sta_probe_request[10] = { 0 };
	char trap_level[5] = { 0 };
	char warm_standby_type[10] = { 0 };
	char warm_standby_addr[20] = { 0 };
	char ip1[4] = { 0 };
	char ip2[4] = { 0 };
	char ip3[4] = { 0 };
	char ip4[4] = { 0 };
	char add_ac_listen_if[50] = { 0 };
	char del_ac_listen_if[50] = { 0 };
	char user_set_vlan[10] = { 0 };
	char country_code[5] = { 0 };
	char temp[100] = { 0 };
	char max_wlan_num[10] = { 0 };
	char max_wtp_num[10] = { 0 };
	char max_radio_num[10] = { 0 };

	/***********************set wid max mtu*****************************/	
    memset(mtu,0,sizeof(mtu));
	cgiFormStringNoNewlines("mtu",mtu,20);   
    if(strcmp(mtu,"")!=0)
  	{
		ret = config_wireless_max_mtu(ins_para->parameter,ins_para->connection,mtu);
		switch(ret)
		{
			case -1:ShowAlert(search(lwcontrol,"mtu_num"));
					flag = 0;
					break;
			case 1: break;
			case -2:ShowAlert(search(lpublic,"oper_fail"));
					flag = 0;
					break;
				
		}
    }


    /***********************set wid log switch*****************************/		
    memset(log_stat,0,sizeof(log_stat));
    cgiFormStringNoNewlines("log",log_stat,20); 
	if(strcmp(log_stat,"")!=0)	
	{
		ret = set_wid_log_switch_cmd(ins_para->parameter,ins_para->connection,log_stat);
		switch(ret)
		{
			case 1:break;
			case -1:ShowAlert(search(lpublic,"oper_fail"));
					flag = 0;
					break;
		}
	}


	/***********************set wid log switch*****************************/		
    memset(log_size,0,sizeof(log_size));
	cgiFormStringNoNewlines("log_size",log_size,20); 
	if(strcmp(log_size,"")!=0)	
 	{
		ret = set_wid_log_size_cmd(ins_para->parameter,ins_para->connection,log_size);
		switch(ret)
		{
			case -1:flag = 0;
				    ShowAlert(search(lwcontrol,"log_num"));
				    break;
			case 1:break;
			case -2:flag = 0;
					ShowAlert(search(lpublic,"oper_fail"));
					break;
		}
 	}

	/***********************set ap statistics switch*****************************/		
    memset(ap_static_state,0,sizeof(ap_static_state));
	cgiFormStringNoNewlines("ap_static_state",ap_static_state,5); 
	if(strcmp(ap_static_state,"")!=0)	
 	{
 		static_state = strtoul(ap_static_state,&endptr,10);
		ret = set_ap_statistics(ins_para->parameter,ins_para->connection,static_state);
		switch(ret)
		{
			case SNMPD_CONNECTION_ERROR:
			case 0:flag = 0;
				   ShowAlert(search(lwcontrol,"con_static_state_fail"));
				    break;
			case 1:break;
			case -1:flag = 0;
					ShowAlert(search(lpublic,"error"));
					break;
		}
 	}


	/***********************set all ap extension information switch*****************************/		
    memset(ac_exten_infor_switch,0,sizeof(ac_exten_infor_switch));
	cgiFormStringNoNewlines("ac_exten_infor_switch",ac_exten_infor_switch,10); 
	if(strcmp(ac_exten_infor_switch,"")!=0)	
 	{
		ret = set_ac_all_ap_extension_information_enable_cmd(ins_para->parameter,ins_para->connection,ac_exten_infor_switch);
		switch(ret)
		{
			case SNMPD_CONNECTION_ERROR:
			case 0:flag = 0;
				   ShowAlert(search(lwcontrol,"con_ac_exten_infor_switch_fail"));
				    break;
			case 1:break;
			case -1:flag = 0;
					ShowAlert(search(lpublic,"input_para_illegal"));
					break;
			case -2:flag = 0;
					ShowAlert(search(lpublic,"error"));
					break;
		}
 	}
	

	/***********************set neighbordead interval cmd func*****************************/		
    memset(neidead_inter,0,sizeof(neidead_inter));
	cgiFormStringNoNewlines("neidead_inter",neidead_inter,10); 
	if(strcmp(neidead_inter,"")!=0)	
 	{
		ret = set_neighbordead_interval_cmd_func(ins_para->parameter,ins_para->connection,neidead_inter);
		switch(ret)
		{
		 	case SNMPD_CONNECTION_ERROR:
			case 0:flag = 0;
				   ShowAlert(search(lwcontrol,"set_neidead_inter_fail"));
				   break;
			case 1:break;
			case -1:flag = 0;
					ShowAlert(search(lwcontrol,"neidead_inter_illegal"));
					break;
			case -2:flag = 0;
					ShowAlert(search(lpublic,"error"));
					break;
		}
 	}

	/***********************set asd sta arp listen cmd*****************************/		
    memset(asd_arp_listen_switch,0,sizeof(asd_arp_listen_switch));
	cgiFormStringNoNewlines("asd_arp_listen_switch",asd_arp_listen_switch,10); 
	if(strcmp(asd_arp_listen_switch,"")!=0)	
 	{
		ret = set_asd_sta_arp_listen_cmd(ins_para->parameter,ins_para->connection,"listen",asd_arp_listen_switch);
		switch(ret)
		{
		 	case SNMPD_CONNECTION_ERROR:
			case 0:flag = 0;
				   ShowAlert(search(lwcontrol,"set_asd_arp_listen_switch_fail"));
				   break;
			case 1:break;
			case -1:flag = 0;
					ShowAlert(search(lpublic,"input_para_illegal"));
					break;
		}
 	}

	/***********************set asd daemonlog level cmd*****************************/
    memset(asd_log_level,0,sizeof(asd_log_level));
    cgiFormStringNoNewlines("asd_log_level",asd_log_level,10); 
	if(strcmp(asd_log_level,"")!=0)	
	{
		ret = set_asd_daemonlog_level_cmd(ins_para->parameter,ins_para->connection,asd_log_level);
		switch(ret)
		{
			case SNMPD_CONNECTION_ERROR:
			case 0:flag = 0;
				   ShowAlert(search(lwcontrol,"set_asd_log_level_fail"));
				   break;
			case 1:break;
			case -1:flag = 0;
					ShowAlert(search(lpublic,"input_para_illegal"));
					break;
			case -2:flag = 0;
					ShowAlert(search(lpublic,"error"));
					break;
		}
	}

	/***********************set wlan not response sta probe request cmd*****************************/
	memset(response_sta_probe_request,0,sizeof(response_sta_probe_request));
	cgiFormStringNoNewlines("response_sta_probe_request",response_sta_probe_request,10);
	if(strcmp(response_sta_probe_request,"") != 0)
	{
		ret=set_wlan_not_response_sta_probe_request_cmd(ins_para->parameter,ins_para->connection,0,response_sta_probe_request);
																				/*返回0表示失败,返回1表示成功*/
																				/*返回-1表示input patameter only with 'enable' or 'disable'*/
																				/*返回-2表示WLAN ID非法,返回-3表示wlan does not exist*/
																				/*返回-4表示wlan is enable, please disable it first*/
																				/*返回-5表示you want to some wlan, and the operation of the wlan was not successful*/
																				/*返回-6表示error*/
																			    /*返回SNMPD_CONNECTION_ERROR表示connection error*/
		switch(ret)
		{
			case SNMPD_CONNECTION_ERROR:
			case -5:
			case 0:ShowAlert(search(lwlan,"set_response_sta_probe_request_fail"));
				   flag=0;
				   break;
			case 1:break;
			case -1:ShowAlert(search(lpublic,"input_para_illegal"));
					flag=0;
					break; 
			case -2:{
				      memset(temp,0,sizeof(temp));
				      strncpy(temp,search(lwlan,"wlan_id_illegal1"),sizeof(temp)-1);
				      memset(max_wlan_num,0,sizeof(max_wlan_num));
				      snprintf(max_wlan_num,sizeof(max_wlan_num)-1,"%d",WLAN_NUM-1);
				      strncat(temp,max_wlan_num,sizeof(temp)-strlen(temp)-1);
				      strncat(temp,search(lwlan,"wlan_id_illegal2"),sizeof(temp)-strlen(temp)-1);
				      ShowAlert(temp);
					  flag=0;
				      break;
				    }
			case -3:ShowAlert(search(lwlan,"wlan_not_exist"));
					flag=0;
					break; 
			case -4:ShowAlert(search(lwlan,"dis_wlan"));
					flag=0;
					break; 
			case -6:ShowAlert(search(lpublic,"error"));
					flag=0;
					break;
		}
	}

	/***********************set wid trap open func*****************************/
	memset(trap_level,0,sizeof(trap_level));
	cgiFormStringNoNewlines("trap_level",trap_level,5);
	if(strcmp(trap_level,"") != 0)
	{
		ret=set_wid_trap_open_func(ins_para->parameter,ins_para->connection,trap_level);
																	/*返回1表示成功,返回0表示失败,返回-1表示error*/
																	/*返回SNMPD_CONNECTION_ERROR表示connection error*/
		switch(ret)
		{
			case SNMPD_CONNECTION_ERROR:
			case 0:ShowAlert(search(lwlan,"set_trap_level_fail"));
				   flag=0;
				   break;
			case 1:break;
			case -1:ShowAlert(search(lpublic,"error"));
					flag=0;
					break;
			case -2:ShowAlert(search(lpublic,"input_para_illegal"));
					flag=0;
					break;
		}
	}


	/***********************set ac master ipaddr cmd*****************************/
	memset(warm_standby_type,0,sizeof(warm_standby_type));
	cgiFormStringNoNewlines("warm_standby_type",warm_standby_type,10);
	memset(warm_standby_addr,0,sizeof(warm_standby_addr));                                 
    memset(ip1,0,sizeof(ip1));
    cgiFormStringNoNewlines("ip1",ip1,4);	
    strncat(warm_standby_addr,ip1,sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1);
    strncat(warm_standby_addr,".",sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1);
    memset(ip2,0,sizeof(ip2));
    cgiFormStringNoNewlines("ip2",ip2,4); 
    strncat(warm_standby_addr,ip2,sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1);	
    strncat(warm_standby_addr,".",sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1);
    memset(ip3,0,sizeof(ip3));
    cgiFormStringNoNewlines("ip3",ip3,4); 
    strncat(warm_standby_addr,ip3,sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1);	
    strncat(warm_standby_addr,".",sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1);
    memset(ip4,0,sizeof(ip4));
    cgiFormStringNoNewlines("ip4",ip4,4);
    strncat(warm_standby_addr,ip4,sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1);
	if((strcmp(warm_standby_type,"") != 0)&&(strcmp(warm_standby_type,"...") != 0))
	{
		ret=set_ac_master_ipaddr_cmd(ins_para->parameter,ins_para->connection,warm_standby_type,warm_standby_addr);
																	/*返回0表示失败,返回1表示成功*/
																	/*返回-1表示invalid input,input should be master or bakup*/
																	/*返回-2表示unknown ip format,返回-3表示more if have this ip*/
																	/*返回-4表示no if has this ip,返回-5表示please disable it first*/
																	/*返回-6表示no interface binding this ip*/
																	/*返回-7表示this ip has not been added or has already been deleted*/
																	/*返回-8表示error*/
																	/*返回SNMPD_CONNECTION_ERROR表示connection error*/
		switch(ret)
		{
			case SNMPD_CONNECTION_ERROR:
			case 0:ShowAlert(search(lwcontrol,"set_warm_standby_addr_fail"));
				   flag=0;
				   break;
			case 1:break;
			case -1:ShowAlert(search(lpublic,"input_para_illegal"));
					flag=0;
					break;
			case -2:ShowAlert(search(lpublic,"unknown_ip_format"));
					flag=0;
					break;
			case -3:ShowAlert(search(lwcontrol,"more_if_have_ip"));
					flag=0;
					break;
			case -4:ShowAlert(search(lwcontrol,"no_if_has_ip"));
					flag=0;
					break;
			case -5:ShowAlert(search(lwcontrol,"disable_it_first"));
					flag=0;
					break;
			case -6:ShowAlert(search(lwcontrol,"no_if_bind_ip"));
					flag=0;
					break;
			case -7:ShowAlert(search(lwcontrol,"this_ip_has_deleted"));
					flag=0;
					break;
			case -8:ShowAlert(search(lpublic,"error"));
					flag=0;
					break;
		}
	}

	/***********************set wirelesscontrol listen l3 interface cmd*****************************/
	memset(add_ac_listen_if,0,sizeof(add_ac_listen_if));
	cgiFormStringNoNewlines("add_ac_listen_if",add_ac_listen_if,50);
	if(strcmp(add_ac_listen_if,"") != 0)
	{
		ret=set_wirelesscontrol_listen_l3_interface_cmd(ins_para->parameter,ins_para->connection,"add",add_ac_listen_if);
																	/*返回0表示失败,返回1表示成功*/
																	/*返回-1表示interface name is too long,should be no more than 15*/
																	/*返回-2表示input patameter only with 'add'or 'del'*/
																	/*返回-3表示 auto ap login switch is enable,you should disable it first*/
																	/*返回-4表示interface error, no index or interface down*/
																	/*返回-5表示this interface has not been added or has already been deleted*/
																	/*返回-6表示interface is down,返回-7表示interface is no flags*/
																	/*返回-8表示tinterface is no index,返回-9表示interface is no local interface, permission denial*/
																	/*返回-10表示interface is other hansi listen*/
																	/*返回SNMPD_CONNECTION_ERROR表示connection error*/
		switch(ret)
		{
			case SNMPD_CONNECTION_ERROR:
			case 0:ShowAlert(search(lwcontrol,"add_ac_listen_if_fail"));
				   flag=0;
				   break;
			case 1:break;
			case -1:ShowAlert(search(lpublic,"interface_too_long"));
					flag=0;
					break;
			case -2:ShowAlert(search(lpublic,"input_para_illegal"));
					flag=0;
					break;
			case -3:ShowAlert(search(lwlan,"disable_auto_ap_switch"));
					flag=0;
					break;
			case -4:{
				 	  memset(temp,0,sizeof(temp));
			          strncpy(temp,search(lpublic,"inter"),sizeof(temp)-1);
				      strncat(temp,add_ac_listen_if,sizeof(temp)-strlen(temp)-1);
				      strncat(temp,search(lpublic,"inter_err_noindex_isdown"),sizeof(temp)-strlen(temp)-1);
			          ShowAlert(temp);
					  flag=0;
					  break;
				    }
			case -5:ShowAlert(search(lwcontrol,"this_ip_has_deleted"));
					flag=0;
					break;
			case -6:ShowAlert(search(lwlan,"inter_is_down"));
					flag=0;
					break;
			case -7:ShowAlert(search(lwlan,"inter_is_no_flag"));
					flag=0;
					break;
			case -8:ShowAlert(search(lwlan,"inter_is_no_index"));
					flag=0;
					break;
			case -9:ShowAlert(search(lpublic,"no_local_interface"));
					flag=0;
					break;
			case -10:ShowAlert(search(lwlan,"interface_bind_in_other_hansi"));
					 flag=0;
					 break;
		}
	}

	
	/***********************set wirelesscontrol listen l3 interface cmd*****************************/
	memset(del_ac_listen_if,0,sizeof(del_ac_listen_if));
	cgiFormStringNoNewlines("del_ac_listen_if",del_ac_listen_if,50);
	if(strcmp(del_ac_listen_if,"") != 0)
	{
		ret=set_wirelesscontrol_listen_l3_interface_cmd(ins_para->parameter,ins_para->connection,"del",del_ac_listen_if);
																	/*返回0表示失败,返回1表示成功*/
																	/*返回-1表示interface name is too long,should be no more than 15*/
																	/*返回-2表示input patameter only with 'add'or 'del'*/
																	/*返回-3表示 auto ap login switch is enable,you should disable it first*/
																	/*返回-4表示interface error, no index or interface down*/
																	/*返回-5表示this interface has not been added or has already been deleted*/
																	/*返回-6表示interface is down,返回-7表示interface is no flags*/
																	/*返回-8表示tinterface is no index,返回-9表示interface is no local interface, permission denial*/
																	/*返回-10表示interface is other hansi listen*/
																	/*返回SNMPD_CONNECTION_ERROR表示connection error*/
		switch(ret)
		{
			case SNMPD_CONNECTION_ERROR:
			case 0:ShowAlert(search(lwcontrol,"add_ac_listen_if_fail"));
				   flag=0;
				   break;
			case 1:break;
			case -1:ShowAlert(search(lpublic,"interface_too_long"));
					flag=0;
					break;
			case -2:ShowAlert(search(lpublic,"input_para_illegal"));
					flag=0;
					break;
			case -3:ShowAlert(search(lwlan,"disable_auto_ap_switch"));
					flag=0;
					break;
			case -4:{
					  memset(temp,0,sizeof(temp));
					  strncpy(temp,search(lpublic,"inter"),sizeof(temp)-1);
					  strncat(temp,add_ac_listen_if,sizeof(temp)-strlen(temp)-1);
					  strncat(temp,search(lpublic,"inter_err_noindex_isdown"),sizeof(temp)-strlen(temp)-1);
					  ShowAlert(temp);
					  flag=0;
					  break;
					}
			case -5:ShowAlert(search(lwcontrol,"this_ip_has_deleted"));
					flag=0;
					break;
			case -6:ShowAlert(search(lwlan,"inter_is_down"));
					flag=0;
					break;
			case -7:ShowAlert(search(lwlan,"inter_is_no_flag"));
					flag=0;
					break;
			case -8:ShowAlert(search(lwlan,"inter_is_no_index"));
					flag=0;
					break;
			case -9:ShowAlert(search(lpublic,"no_local_interface"));
					flag=0;
					break;
			case -10:ShowAlert(search(lwlan,"interface_bind_in_other_hansi"));
					 flag=0;
					 break;
		}
	}

	/***********************set vlan switch cmd*****************************/
	memset(user_set_vlan,0,sizeof(user_set_vlan));
	cgiFormStringNoNewlines("user_set_vlan",user_set_vlan,10);
	if(strcmp(user_set_vlan,"") != 0)
	{
		ret=set_vlan_switch_cmd(ins_para->parameter,ins_para->connection,user_set_vlan);
																			/*返回0表示失败,返回1表示成功*/
																			/*返回-1表示error*/
																			/*返回SNMPD_CONNECTION_ERROR表示connection error*/
		switch(ret)
		{
			case SNMPD_CONNECTION_ERROR:
			case 0:ShowAlert(search(lwcontrol,"con_user_set_vlan_fail"));
				   flag=0;
				   break;
			case 1:break;
			case -1:ShowAlert(search(lpublic,"error"));
					flag=0;
					break;
		}
	}

	/***********************set system country code func*****************************/
	memset(country_code,0,sizeof(country_code));
	cgiFormStringNoNewlines("country_code",country_code,5);
	if(strcmp(country_code,"") != 0)
	{
		ret=set_system_country_code_func(ins_para->parameter,ins_para->connection,0,0,country_code);
																			/*返回0表示失败,返回1表示成功,返回-1表示input country code should be capital letters*/
																			/*返回-2表示input country code error,返回-3表示system country code is already Country_code, no need to change*/
																			/*返回-4表示system country code error,返回-5表示WTP ID非法,返回-6表示Radio ID非法*/
																			/*返回SNMPD_CONNECTION_ERROR表示connection error*/
		switch(ret)
		{
			case SNMPD_CONNECTION_ERROR:
			case 0:ShowAlert(search(lwcontrol,"con_country_code_fail"));
				   flag=0;
				   break;
			case 1:break;
			case -1:
			case -2:ShowAlert(search(lpublic,"input_para_illegal"));
					flag=0;
					break;
			case -3:{
					  memset(temp,0,sizeof(temp));
					  strncpy(temp,search(lwcontrol,"country_code_no_need_change1"),sizeof(temp)-1);
					  strncat(temp,country_code,sizeof(temp)-strlen(temp)-1);
					  strncat(temp,search(lwcontrol,"country_code_no_need_change2"),sizeof(temp)-strlen(temp)-1);
					  ShowAlert(temp);
					  flag=0;
					  break;
					}
			case -4:ShowAlert(search(lpublic,"sys_err"));
					flag=0;
					break;
			case -5:{
					  memset(temp,0,sizeof(temp));
					  strncpy(temp,search(lwlan,"wtp_id_illegal1"),sizeof(temp)-1);
					  memset(max_wtp_num,0,sizeof(max_wtp_num));
					  snprintf(max_wtp_num,sizeof(max_wtp_num)-1,"%d",WTP_NUM-1);
					  strncat(temp,max_wtp_num,sizeof(temp)-strlen(temp)-1);
					  strncat(temp,search(lwlan,"wtp_id_illegal2"),sizeof(temp)-strlen(temp)-1);
					  ShowAlert(temp);
					  flag = 0;
					  break;
				    }
			case -6:{					  
		              memset(temp,0,sizeof(temp));
					  strncpy(temp,search(lwlan,"radio_id_illegal1"),sizeof(temp)-1);
					  memset(max_radio_num,0,sizeof(max_radio_num));
					  snprintf(max_radio_num,sizeof(max_radio_num)-1,"%d",G_RADIO_NUM-1);
					  strncat(temp,max_radio_num,sizeof(temp)-strlen(temp)-1);
					  strncat(temp,search(lwlan,"radio_id_illegal2"),sizeof(temp)-strlen(temp)-1);
				  	  ShowAlert(temp);
					  flag=0;
					  break;
					}
		}
	}

    if(flag == 1)
  	{
		ShowAlert(search(lpublic,"oper_succ"));
  	}
}