Esempio n. 1
0
void run(void* jt)
{
 I r,n,len;A a;SOCKBUF* pb;static C setname[nsz+1]="";
 while(1)
 {
  pb=getdata();
  if(!pb) errorm("run getdata failed");
  len = pb->len;
  switch(pb->cmd)
  {
	case JCMDDO:
		if(pb->type==1) /* input and event data */
		{
			seteventdata();
			len=strlen(pb->d);
		}
		if(len<sizeof(input)-1)
		{
			memcpy(input, pb->d, len);
			input[len]=0;
			r=JDo(jt,input);
		}
		else
			r=EVLENGTH;
		putdata(JCMDDOZ,r,0,0,0,0);
		break;
	case JCMDSETN:
		n=len<nsz?len:nsz;
		memcpy(setname, pb->d, n);
		setname[n]=0;
		break;			
	case JCMDSET:
		r=JSetA(jt,strlen(setname),setname,len,pb->d);
		putdata(JCMDSETZ,r,0,0,0,0);
		break;
	case JCMDGET:
		a=JGetA(jt,len,pb->d);
		if(a==0)
			putdata(JCMDGETZ,EVVALUE,0,0,0,0);
		else
			putdata(JCMDGETZ,0,AN(a),CAV(a),0,0);
		break;
	default:
		errorm("unknown command");
  }
 }
}
// HTTP worker thread code
static void *HTTPThreadProc(void *status_ptr)
{    

    if (status_ptr == NULL) {
        errorm("Thread started with NULL parameter");
        return NULL;
    }//if

	ThreadInitCode();

    int lifetime = (int)GetConfigUInt(CFG_THREAD_LIFETIME);

    logf("Thread started");

    int *status = (int *)status_ptr;
    int tid = *status;
    struct ClientConnData ccdata;

    logf("Thread %i started", tid);

    while (c_control == C_RUN ) {    // wait for wake up

        *status = STATUS_WAITING;

        pthread_mutex_lock(&req_mutex);
        while (req_data == NULL) {

        	if (c_control != C_RUN) {
        		*status = STATUS_DEAD;
        		pthread_mutex_unlock(&req_mutex);
                logf("Thread %i exited", tid);
        		return NULL;
        	}//if

            pthread_cond_wait(&req_cond, &req_mutex);
        }//while

        memcpy(&ccdata, req_data, sizeof(struct ClientConnData));
        logf("thread %i accepted request", tid);

        //case ACTION_ACCEPT:
        req_data = NULL;
        *status = STATUS_BUSY;
        pthread_mutex_unlock(&req_mutex);
        HTTPMain(&ccdata);
        logf("thread %i completed task.", tid);
        
        if (lifetime > 0) {
           if ((--lifetime) <= 0) {
                *status = STATUS_DEAD;
                logf("Thread %i expired", tid);
                return NULL;
            }//if
        }//if

    }//while
    return NULL;
}
Esempio n. 3
0
char* _stdcall JinputS(J jt, char* prompt)
{
	I n,len;SOCKBUF* pb;
	
	putdata(JCMDIN,0,strlen(prompt),prompt,0,0);
	if(!(pb=getdata())) errorm("jinputs getdata failed");
	if(pb->cmd!=JCMDINZ) errorm("jinputs not inz");
	if(pb->type==1)
	{
		seteventdata();
		len=strlen(pb->d); /* input followed by event data */
	}
	else
		len = pb->len;
	n=min(len,sizeof(input)-1);
	memcpy(input, &pb->d, n);
	input[n]=0;
	return input;
}
Esempio n. 4
0
void CloseTCPSocket()
{
    if (ssd != INVALID_SOCKET) {
        log("Closing HTTP server socket...");
        close(ssd);
        ssd = INVALID_SOCKET;
    } else {
        errorm("Cannot close HTTP server socket (invalid descriptor).");
    }
}
Esempio n. 5
0
int b_assign(int val, int min, int max, int *arg) 
{
  int ok = ((val >= min) && (val <= max));
  if (ok) {
      *arg = val;
  }//if
  else {
    errorm("Invalid argument value");
  }
  return ok;
}
Esempio n. 6
0
/**
 * test_rsvol - test UBI volume re-size.
 *
 * @type  volume type (%UBI_DYNAMIC_VOLUME or %UBI_STATIC_VOLUME)
 *
 * Thus function returns %0 in case of success and %-1 in case of failure.
 */
static int test_rsvol(int type)
{
	const char *name = PROGRAM_NAME "test_rsvol:()";
	int alignments[] = ALIGNMENTS(dev_info.leb_size);
	char vol_node[strlen(UBI_VOLUME_PATTERN) + 100];
	struct ubi_mkvol_request req;
	int i;

	for (i = 0; i < sizeof(alignments)/sizeof(int); i++) {
		int leb_size;
		struct ubi_vol_info vol_info;

		req.vol_id = UBI_VOL_NUM_AUTO;
		req.vol_type = type;
		req.name = name;

		req.alignment = alignments[i];
		req.alignment -= req.alignment % dev_info.min_io_size;
		if (req.alignment == 0)
			req.alignment = dev_info.min_io_size;

		leb_size = dev_info.leb_size - dev_info.leb_size % req.alignment;
		req.bytes =  MIN_AVAIL_EBS * leb_size;

		if (ubi_mkvol(libubi, node, &req)) {
			failed("ubi_mkvol");
			return -1;
		}

		sprintf(vol_node, UBI_VOLUME_PATTERN, dev_info.dev_num,
			req.vol_id);

		if (ubi_get_vol_info(libubi, vol_node, &vol_info)) {
			failed("ubi_get_vol_info");
			goto remove;
		}

		if (test_rsvol1(&vol_info)) {
			errorm("alignment = %d", req.alignment);
			goto remove;
		}

		if (ubi_rmvol(libubi, node, req.vol_id)) {
			failed("ubi_rmvol");
			return -1;
		}
	}

	return 0;

remove:
	ubi_rmvol(libubi, node, req.vol_id);
	return -1;
}
int UDPThreadInit(void)
{
    log("UDP thread initialization");

    if (CreateThread(&udp_thread, UDPServer, NULL) == FALSE) {
        errorm("Failed to create UDP thread");
        return FALSE;
    }//if
    log("Created UDP thread");
    return TRUE;
}
// Creates new threads if neccessary.
int AllocNewThreads(int tcount)
{       
    int i;

    for (i = 0; i < t_num; i++) {
        if (t_status[i] == STATUS_WAITING) {
            logf("thread %i should be ready",i);
            return -1;
        }//if
    }//for

    int a_num = t_num + tcount;
    if (GetConfigUInt(CFG_THREAD_MAX) < (unsigned int)a_num) { 
        return -2;// max. number of threads reached
    }//if

    pthread_mutex_lock(&req_mutex);

    // reallocate array of thread objects
    pthread_t *a_id = t_id;
    int *a_status = t_status;
    t_id = (pthread_t *)emalloc(a_num * sizeof(pthread_t));
    t_status = (int *)emalloc(a_num * sizeof(int));
    memcpy(t_id, a_id, t_num * sizeof(pthread_t));
    memcpy(t_status, a_status, t_num * sizeof(int));
    free(a_id);
    free(a_status);

    int created = 0;
    for (i = t_num; i < a_num; i++) {
        t_status[i] = i;
        if (CreateThread(&t_id[i], HTTPThreadProc, (void *)&t_status[i]) == FALSE) {
            t_status[i] = STATUS_ERROR;
            errorm("Failed to create new thread");
        }//if
        else { 
            logf("Created thread %i", i);
            created++; 
        }//else
    }//for
    t_num = a_num;

    pthread_mutex_unlock(&req_mutex);

    return created;
}
Esempio n. 9
0
/**
 * mkvol_alignment - create volumes with different alignments.
 *
 * Thus function returns %0 in case of success and %-1 in case of failure.
 */
static int mkvol_alignment(void)
{
	struct ubi_mkvol_request req;
	int i, vol_id, ebsz;
	const char *name = PROGRAM_NAME ":mkvol_alignment()";
	int alignments[] = ALIGNMENTS(dev_info.leb_size);

	for (i = 0; i < sizeof(alignments)/sizeof(int); i++) {
		req.vol_id = UBI_VOL_NUM_AUTO;

		/* Alignment should actually be multiple of min. I/O size */
		req.alignment = alignments[i];
		req.alignment -= req.alignment % dev_info.min_io_size;
		if (req.alignment == 0)
			req.alignment = dev_info.min_io_size;

		/* Bear in mind alignment reduces EB size */
		ebsz = dev_info.leb_size - dev_info.leb_size % req.alignment;
		req.bytes = (long long)dev_info.avail_lebs * ebsz;

		req.vol_type = UBI_DYNAMIC_VOLUME;
		req.name = name;

		if (ubi_mkvol(libubi, node, &req)) {
			failed("ubi_mkvol");
			errorm("alignment %d", req.alignment);
			return -1;
		}

		vol_id = req.vol_id;
		if (check_volume(vol_id, &req))
			goto remove;

		if (ubi_rmvol(libubi, node, vol_id)) {
			failed("ubi_rmvol");
			return -1;
		}
	}

	return 0;

remove:
	ubi_rmvol(libubi, node, vol_id);
	return -1;
}
Esempio n. 10
0
int HTTPThreadInit(void)
{
    int i;

    log("HTTP threads initialization");
    pthread_cond_init(&req_cond, NULL);

    t_num = 0; // create worker threads

    t_id = (pthread_t *)emalloc(1 * sizeof(pthread_t));
    t_status = (int *)emalloc(1 * sizeof(int));

    i = GetConfigUInt(CFG_THREAD_INIT);
    logf("init threads %i (%i)", i, AllocNewThreads(i));

    // create http server thread
    if (CreateThread(&http_thread, HTTPServerMain, NULL) == FALSE) {
        errorm("Failed to create HTTP thread");
        return FALSE;
    }//if

    return TRUE;
}
Esempio n. 11
0
//      This is used to either wrap an OpenCL function call, or to explicitly check a variable for an OpenCL error condition.
//      If an error occurs, we throw.
//      Note: std::runtime_error does not take unicode strings as input, so only strings supported
inline cl_int OpenCL_V_Throw ( cl_int res, const std::string& msg, size_t lineno )
{
        switch( res )
        {
                case    CL_SUCCESS:             /**< No error */
                        break;
                default:
                {
                        std::stringstream tmp;
                        tmp << "OPENCL_V_THROWERROR< ";
                        tmp << prettyPrintclFFTStatus( res );
                        tmp << " > (";
                        tmp << lineno;
                        tmp << "): ";
                        tmp << msg;
                        std::string errorm (tmp.str());
                        std::cout << errorm<< std::endl;
                        throw   std::runtime_error( errorm );
                }
        }

        return  res;
}
Esempio n. 12
0
void *HTTPServerMain(void *)
{
    struct ClientConnData ccdata;
    SOCKET newsock;
    struct sockaddr_in cs;
    size_t css = sizeof(cs);

	ThreadInitCode();

    while (c_control == C_RUN) {
        newsock = accept(ssd, (struct sockaddr *)&cs, (socklen_t *)&css);

		if (c_control != C_RUN) { break; } //immediate exit - don't print error

        if (newsock != -1) {

            ccdata.action = ACTION_ACCEPT;
            ccdata.sd = newsock;
            ccdata.port = ntohs(cs.sin_port);
            ccdata.address.inaddr = cs.sin_addr;
            //memcpy(&(ccdata.address), &(cs.sin_addr), sizeof(ccdata.address));

            logf("Accepted connection from %s:%u, socket %u",
                inet_ntoa(ccdata.address.inaddr), 
                ccdata.port, 
                ccdata.sd);

            WakeUpWorkerThread(&ccdata);

        } else {
           errorm("Accept() failed: %s", str_error());
        }//else

    }//while
	return NULL;
}
Esempio n. 13
0
int main(int argc, char *argv[])
{
    int done = FALSE;
    opterr = 0;

    //fprintf(stderr, "ctrack started.");
    c_control = C_RUN;

    srand((int)time(NULL));

	ErrorInit();    
    ConfigInit(); // initializes verbose; must be called before any output

   	ReadConfig(TRUE); // default loc.
    TorrentDBCreate();

    unsigned int p;
    while (!done) {
        switch (getopt(argc, argv, "+vqVhrdt:u:p:c:"))  { // + means "don't shuffle args"
            case '?': // invalid option
                PrintSyntax(1);
            case 'h': // help option
                PrintSyntax(0);
            case 'V':
            	printf("ctrack " VERSION "\n");
            	return 0;
                break;
            case 'v':
                SetConfigBool(CFG_VERBOSE, TRUE);
                log("Verbose mode");
                break;
            case 'q':
                SetConfigBool(CFG_VERBOSE, FALSE);
                log("Quiet mode");
                break;
            case 't':
                if (b_assign(atoi(optarg),1,65535,(int *)&p))
                    SetConfigUInt(CFG_HTTP_PORT, p);
                break;
            case 'u':
                if (b_assign(atoi(optarg),1,65535,(int *)&p))
                    SetConfigUInt(CFG_UDP_PORT, p);
                break;
            case 'p':
                if (b_assign(atoi(optarg),1,65535,(int *)&p))
                    SetConfigUInt(CFG_SERVER_PORT, p);
                break;
            case 'd':
                SetConfigBool(CFG_DAEMON, TRUE);
                break;
            case 'c': //config file
	            SetConfigString(CFG_CONFIG_FILE, optarg);
                ReadConfig(FALSE);
            	break;
            case -1:  //end of options
                done = TRUE;
                break;
            default:
                PrintSyntax(1);
                break;    
        }//switch
    }//while
    int i;
    for (i = optind; i < argc; i++) {
    	PTorrentInfo t;
    	char ibuffer[20];
    	if (strtohash(argv[i], ibuffer)) {
			NewTorrentInfo(&t, ibuffer);
		} else {
			errorm("Invalid hash: %s", argv[i]);
		}
    }//for

    //TODO:parse args
    //TODO:init torrent db

#ifdef DAEMON_SUPPORT
    if (GetConfigBool(CFG_DAEMON) == TRUE) {
    /* Our process ID and Session ID */
    pid_t pid, sid;

    /* Fork off the parent process */
    pid = fork();
    if (pid < 0) { exit(EXIT_FAILURE); }
    /* If we got a good PID, then we can exit the parent process. */
    if (pid > 0) { exit(EXIT_SUCCESS); }
    /* Change the file mode mask */
    umask(0);
        /* Create a new SID for the child process */
    sid = setsid();
    if (sid < 0) {
		errorm("setsid() failed: %s", str_error());
		exit(EXIT_FAILURE);
    }
    /* Change the current working directory */
    if ((chdir("/")) < 0) {
		errorm("chdir() failed: %s", str_error());
        exit(EXIT_FAILURE);
    }
    /* Close out the standard file descriptors */
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

	if (daemon(TRUE, FALSE) != 0) 
        errorf(E_SYSTEM, "daemon() failed: %S", str_error());
    } else {
		extern int asdaemon;
		asdaemon = TRUE;
    }
#endif

    //SetupSignalHandlers
	sigset_t set;
	int sig;

    while (c_control == C_RUN) {
    	sigfillset(&set);
    	pthread_sigmask(SIG_SETMASK, &set, NULL);

        if (GetConfigBool(CFG_HTTP_SERVER)) { // HTTP server
	        if (SetUpListener())
    	        HTTPThreadInit();
	    }

	    if (GetConfigBool(CFG_UDP_SERVER)) { // UDP server
	        UDPThreadInit();
	    }

		//TODO: sigwait
		while (c_control == C_RUN) {
		    sigwait(&set, &sig);
			logf("Caught signal #%d", sig);
			switch (sig) {
				case SIGINT:
	                c_control = C_TERMINATE;
    	            log("Exitting...");
        	        break;
				case SIGHUP:
	                c_control = C_RESTART;
	                log("Restarting...");
                   	ReadConfig(FALSE);
	                break;
				case SIGSEGV:
	                c_control = C_TERMINATE;
    	            log("Exitting...");
			}//switch
		}//while
        ThreadsDestroy();
    	CloseTCPSocket();
    	CloseUDPSocket();

        if (c_control == C_RESTART) { c_control = C_RUN; }
    }//while

  	log("exit ");
    return ((sig==SIGINT) ? EXIT_SUCCESS : EXIT_FAILURE);
}
Esempio n. 14
0
/**
 * mkvol_basic - simple test that checks basic volume creation capability.
 *
 * Thus function returns %0 in case of success and %-1 in case of failure.
 */
static int mkvol_basic(void)
{
	struct ubi_mkvol_request req;
	struct ubi_vol_info vol_info;
	int vol_id, ret;
	const char *name = PROGRAM_NAME ":mkvol_basic()";

	/* Create dynamic volume of maximum size */
	req.vol_id = UBI_VOL_NUM_AUTO;
	req.alignment = 1;
	req.bytes = dev_info.avail_bytes;
	req.vol_type = UBI_DYNAMIC_VOLUME;
	req.name = name;

	if (ubi_mkvol(libubi, node, &req)) {
		failed("ubi_mkvol");
		return -1;
	}

	vol_id = req.vol_id;
	if (check_volume(vol_id, &req))
		goto remove;

	if (ubi_rmvol(libubi, node, vol_id)) {
		failed("ubi_rmvol");
		return -1;
	}

	/* Create static volume of maximum size */
	req.vol_id = UBI_VOL_NUM_AUTO;
	req.alignment = 1;
	req.bytes = dev_info.avail_bytes;
	req.vol_type = UBI_STATIC_VOLUME;
	req.name = name;

	if (ubi_mkvol(libubi, node, &req)) {
		failed("ubi_mkvol");
		return -1;
	}

	vol_id = req.vol_id;
	if (check_volume(vol_id, &req))
		goto remove;

	if (ubi_rmvol(libubi, node, vol_id)) {
		failed("ubi_rmvol");
		return -1;
	}

	/* Make sure volume does not exist */
	ret = ubi_get_vol_info1(libubi, dev_info.dev_num, vol_id, &vol_info);
	if (ret == 0) {
		errorm("removed volume %d exists", vol_id);
		goto remove;
	}

	return 0;

remove:
	ubi_rmvol(libubi, node, vol_id);
	return -1;
}
Esempio n. 15
0
/*
 * Helper function for test_rsvol().
 */
static int test_rsvol1(struct ubi_vol_info *vol_info)
{
	long long bytes;
	struct ubi_vol_info vol_info1;
	char vol_node[strlen(UBI_VOLUME_PATTERN) + 100];
	unsigned char buf[vol_info->rsvd_bytes];
	int fd, i, ret;

	/* Make the volume smaller and check basic volume I/O */
	bytes = vol_info->rsvd_bytes - vol_info->leb_size;
	if (ubi_rsvol(libubi, node, vol_info->vol_id, bytes - 1)) {
		failed("ubi_rsvol");
		return -1;
	}

	if (ubi_get_vol_info1(libubi, vol_info->dev_num, vol_info->vol_id,
			     &vol_info1)) {
		failed("ubi_get_vol_info");
		return -1;
	}

	if (vol_info1.rsvd_bytes != bytes) {
		errorm("rsvd_bytes %lld, must be %lld",
		       vol_info1.rsvd_bytes, bytes);
		return -1;
	}

	if (vol_info1.rsvd_lebs != vol_info->rsvd_lebs - 1) {
		errorm("rsvd_lebs %d, must be %d",
		       vol_info1.rsvd_lebs, vol_info->rsvd_lebs - 1);
		return -1;
	}

	/* Write data to the volume */
	sprintf(vol_node, UBI_VOLUME_PATTERN, dev_info.dev_num,
			vol_info->vol_id);

	fd = open(vol_node, O_RDWR);
	if (fd == -1) {
		failed("open");
		errorm("cannot open \"%s\"\n", vol_node);
		return -1;
	}

	bytes = vol_info->rsvd_bytes - vol_info->leb_size - 1;
	if (ubi_update_start(libubi, fd, bytes)) {
		failed("ubi_update_start");
		goto close;
	}

	for (i = 0; i < bytes; i++)
		buf[i] = (unsigned char)i;

	ret = write(fd, buf, bytes);
	if (ret != bytes) {
		failed("write");
		goto close;
	}

	close(fd);

	if (ubi_rsvol(libubi, node, vol_info->vol_id, bytes)) {
		failed("ubi_rsvol");
		return -1;
	}

	if (ubi_rsvol(libubi, node, vol_info->vol_id,
		      (long long)vol_info->leb_size * dev_info.avail_lebs)) {
		failed("ubi_rsvol");
		return -1;
	}

	fd = open(vol_node, O_RDWR);
	if (fd == -1) {
		failed("open");
		errorm("cannot open \"%s\"\n", vol_node);
		return -1;
	}

	/* Read data back */
	if (lseek(fd, 0, SEEK_SET) != 0) {
		failed("seek");
		goto close;
	}
	memset(buf, 0, bytes);
	ret = read(fd, buf, bytes);
	if (ret != bytes) {
		failed("read");
		goto close;
	}

	for (i = 0; i < bytes; i++) {
		if (buf[i] != (unsigned char)i) {
			errorm("bad data");
			goto close;
		}
	}

	close(fd);
	return 0;

close:
	close(fd);
	return -1;
}
Esempio n. 16
0
void *UDPServer(void *)
{
    
    unsigned int port;
    void *inbuffer;
    void *outbuffer;

	ThreadInitCode();

/*    if (status_ptr == NULL) { // no parameter is passed
        errorm("UDP thread started with NULL parameter");
        return NULL;
    }//if*/

    port = GetConfigUInt(CFG_UDP_PORT);
    if (port == 0) {
        port = GetConfigUInt(CFG_SERVER_PORT);
    }//if

    if (port == 0) {
        errorm("UDP port not specified");
        return NULL;
    }//if

    logf("Creating server socket (port: %u).", port);

    struct protoent *pp;
    pp = getprotobyname("udp");
    int protonum = 0;
    if (pp != NULL) { protonum = pp->p_proto; }

    udp_sd = socket(AF_INET, SOCK_DGRAM, protonum);
    if (udp_sd == -1) { 
        errorm("socket() failed: %s", str_error());
        return NULL;  
    }//if

    struct sockaddr_in sinInterface;
    sinInterface.sin_family = AF_INET;
    sinInterface.sin_addr.s_addr = INADDR_ANY;
    sinInterface.sin_port = htons(port);
    if (bind(udp_sd, (struct sockaddr *)&sinInterface, sizeof(sinInterface)) == -1) { 
        errorm("bind() failed for udp server: %s", str_error());  
    }//if

    logf("UDP server started...");

    inbuffer = emalloc(UDP_BUFFER_SIZE);
    outbuffer = emalloc(UDP_BUFFER_SIZE);
    
    while (c_control == C_RUN) {
    
        struct sockaddr_in sa;
        socklen_t sl;
        ssize_t inmsgsize;
        ssize_t outmsgsize;
		char *pbuffer;
		sl = sizeof(sa);

        inmsgsize = recvfrom(udp_sd, inbuffer, UDP_BUFFER_SIZE, 0, (struct sockaddr*)&sa, &sl);

		if (c_control != C_RUN) { break; } //immediate exit - don't print error
		
		if (inmsgsize == -1) {
			errorm("recvfrom() failed: %s", str_error());
		} else {
	        pbuffer = hexdump((char*)inbuffer, inmsgsize);
    	    logf("in: \n%s", pbuffer);
			free(pbuffer);

			DBLock();
	        outmsgsize = UDPMain(inbuffer, inmsgsize, outbuffer, &sa);
	        DBUnlock();

	        pbuffer = hexdump((char*)outbuffer, outmsgsize);
	        logf("out: \n%s", pbuffer);
			free(pbuffer);

	        ssize_t sent = sendto(udp_sd, outbuffer, outmsgsize, 0, (struct sockaddr*)&sa, sl);
	        logf("udp in: %i, out: %i (sent: %i)", inmsgsize, outmsgsize, (int)sent);

	        if (sent == -1) { errorm("sendto() failed: %s",str_error()); }
		}//else

    }//while

    return NULL;

}