Example #1
0
///////////////////////////////////////////////////////////////////////////////
//  MAIN: collect input parameters and run benchmarks
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv) {

	int info_flag = 0;
	int usage_flag = 0;
	int csv_flag = 0;
    int type_flag = 0;
	int c;
	char *sizes_str = NULL;
	char *devices_str = NULL;
    char *vector_str = NULL;
	char *repeat_str = NULL;
	char *iterations_str = NULL;
	
	while (1)
	{
		static struct option long_options[] =
		{
			/* These options set a flag. */
			{"info", no_argument,       &info_flag, 1},
			{"help", no_argument,       &usage_flag, 1},
			{"csv",  no_argument,       &csv_flag, 1},
            {"private", no_argument,       &type_flag, 1},
            {"global", no_argument,       &type_flag, 2},
            {"local", no_argument,       &type_flag, 0},
			/* These options don't set a flag.
			 We distinguish them by their indices. */
			{"sizes",    optional_argument, 0, 'a'},
			{"device",  optional_argument, 0, 'b'},
			{"repeats",  optional_argument, 0, 'c'},
			{"iterations",  optional_argument, 0, 'd'},
			{"vector",  optional_argument, 0, 'e'},
			{0, 0, 0, 0}
		};
		/* getopt_long stores the option index here. */
		int option_index = 0;
		
		c = getopt_long (argc, argv, "a:", long_options, &option_index);
		
		/* Detect the end of the options. */
		if (c == -1)
			break;
		
		switch (c)
		{
			case 0:
				/* If this option set a flag, do nothing else now. */
				break;
			case 'a':
				sizes_str = optarg;
				break;
			case 'b':
				devices_str = optarg;
				break;
			case 'c':
				repeat_str = optarg;
				break;
			case 'd':
				iterations_str = optarg;
				break;
			case 'e':
				vector_str = optarg;
				break;
			case '?':
				/* getopt_long already printed an error message. */
				break;
			default:
				abort ();
		}
	}
	
	
	// retrieve devices
	unsigned int num_devices = 0, num_platforms;

    cl_platform_id* platforms = get_all_platforms(&num_platforms, NULL);
	cl_device_id* devices = get_all_devices(platforms, num_platforms, &num_devices);
    free(platforms);
	if(devices == NULL) {
		printf("Error: Failed to create a device group!\n");
		return 1;
	}
		
	if (info_flag) {
		print_device_list(devices, num_devices);
		return 0;
	}
	
	if (usage_flag) {
		print_usage();
		return 0;
	}
	
	// retrieve devices to be benchmarked
	cl_device_id *used_devices = (cl_device_id*) malloc(sizeof(cl_device_id) * num_devices);
	unsigned int used_num_devices = 0;
	if((devices_str == '\0') || (strcmp(devices_str, "all") == 0)) {
		// nothing specified, run benchmark for all devices
		for(unsigned int i = 0; i < num_devices; i++) used_devices[i] = devices[i];
		used_num_devices = num_devices;
	} else {
		// check the given device-numbers and fill up the device-array
		char* ptr;
		used_num_devices = 0;
		ptr = strtok(devices_str, ",");
		while(ptr != NULL) {
			unsigned int id = 0;
			if(sscanf(ptr, "%i", &id) > 0) {
				if(id >= 0 && id < num_devices) {
					used_devices[used_num_devices] = devices[id];
					used_num_devices++;
				}
			} else {
				printf("invalid device-number given (%d)\n", id);
				return 1;
			}
			ptr = strtok(NULL, ",");
		}
	}
	
	// retrieve memory-sizes to run the benchmark with  -- momentary unused
	unsigned long* sizes = (unsigned long*) malloc(sizeof(unsigned long) * MAX_SIZES * used_num_devices);
	for (unsigned int i = 0; i < MAX_SIZES * used_num_devices; i++) {
		sizes[i] = 0;
	}
	unsigned int num_sizes = 0;
	if(sizes_str == '\0') {
		// nothing specified, test for maximum
		num_sizes = 1;
		for (unsigned int i = 0; i < used_num_devices; i++) {
			sizes[i * MAX_SIZES] = 10 * 1024 * 1024;
		}
	} else {
		// check given numbers and fill up the device-array
		char* ptr;
		ptr = strtok(sizes_str, ",");
		while(ptr != NULL) {
			unsigned long size = 0;
			unsigned long _s;
			char _m;
			if (sscanf(ptr, "%lu%c", &_s, &_m) == 2) {
				switch (_m) {
					case 'K': case 'k':
						size = _s * 1024;
						break;
					case 'M': case 'm':
						size = _s * 1024 * 1024;
						break;
					default:
						printf("invalid size given (%s)\n", ptr);
						return 1;
				}
			} else if (sscanf(ptr, "%lu", &_s) > 0) {
				size = _s;
			} else {
				printf("invalid size given (%s)\n", ptr);
				return 1;
			}
			for (unsigned int i = 0; i < used_num_devices; i++) {
				sizes[num_sizes + i * MAX_SIZES] = size;
			}
			num_sizes ++;
			ptr = strtok(NULL, ",");
		}		
	}
	
	// retrieve amount of repeats for each data-point
	unsigned int repeats = 0;
	if (repeat_str == '\0') {
		repeats = DEFAULT_REPEATS;
	} else {
		if (sscanf(repeat_str, "%d", &repeats) > 0) {
			// nothing more to do
		} else {
			printf("invalid number of repeats given (%s)\n", repeat_str);
			return 1;
		}
	}
	
	// retrieve amount of iterations used for each data-point
	unsigned int iterations = 0;
	if (iterations_str== '\0') {
		iterations = DEFAULT_ITERATIONS;
	} else {
		if (sscanf(iterations_str, "%d", &iterations) > 0) {
			// nothing more to do
		} else {
			printf("invalid number of iterations given (%s)\n", iterations_str);
			return 1;
		}
	}

    int f4 = 0;
    char vec[16];
    if (vector_str== '\0') {
        f4 = 0;
    } else {
        if (sscanf(vector_str, "%d", &f4) < 0 || f4 < 0 || f4 > 4) {
            printf("Request for unsupported vector type! Supported are:\n \
                   \t0 -> float\n \
                   \t1 -> float2\n \
                   \t2 -> float4\n \
                   \t3 -> float8\n \
                   \t4 -> float16\n");
            return 1;
        }
    }
Example #2
0
bool ChatHandler::HandleAddAIAgentCommand(const char* args, WorldSession *m_session)
{
	char* agent = strtok((char*)args, " ");
	if(!agent)
		return false;
	char* procEvent = strtok(NULL, " ");
	if(!procEvent)
		return false;
	char* procChance = strtok(NULL, " ");
	if(!procChance)
		return false;
	char* procCount = strtok(NULL, " ");
	if(!procCount)
		return false;
	char* spellId = strtok(NULL, " ");
	if(!spellId)
		return false;
	char* spellType = strtok(NULL, " ");
	if(!spellType)
		return false;
	char* spelltargetType = strtok(NULL, " ");
	if(!spelltargetType)
		return false;
	char* spellCooldown = strtok(NULL, " ");
	if(!spellCooldown)
		return false;
	char* floatMisc1 = strtok(NULL, " ");
	if(!floatMisc1)
		return false;
	char* Misc2 = strtok(NULL, " ");
	if(!Misc2)
		return false;

	Unit* target = m_session->GetPlayer()->GetMapMgr()->GetCreature(m_session->GetPlayer()->GetSelection());
	if(!target)
	{
		RedSystemMessage(m_session, "You have to select a Creature!");
		return false;
	}

	std::stringstream qry;
	qry << "INSERT INTO ai_agents set entryId = '" << target->GetUInt32Value(OBJECT_FIELD_ENTRY) << "', AI_AGENT = '" << atoi(agent) << "', procEvent = '" << atoi(procEvent)<< "', procChance = '" << atoi(procChance)<< "', procCount = '" << atoi(procCount)<< "', spellId = '" << atoi(spellId)<< "', spellType = '" << atoi(spellType)<< "', spelltargetType = '" << atoi(spelltargetType)<< "', spellCooldown = '" << atoi(spellCooldown)<< "', floatMisc1 = '" << atof(floatMisc1)<< "', Misc2  ='" << atoi(Misc2)<< "'";
	WorldDatabase.Execute( qry.str().c_str( ) );

	AI_Spell * sp = new AI_Spell;
	sp->agent = atoi(agent);
	sp->procChance = atoi(procChance);
	sp->spell = sSpellStore.LookupEntry(atoi(spellId));
	sp->spellType = atoi(spellType);
	sp->spelltargetType = atoi(spelltargetType);
	sp->floatMisc1 = atof(floatMisc1);
	sp->Misc2 = (uint32)atof(Misc2);
	sp->cooldown = atof(spellCooldown);
	sp->minrange = GetMinRange(sSpellRange.LookupEntry(sSpellStore.LookupEntry(atoi(spellId))->rangeIndex));
	sp->maxrange = GetMaxRange(sSpellRange.LookupEntry(sSpellStore.LookupEntry(atoi(spellId))->rangeIndex));
	if(sp->agent == AGENT_CALLFORHELP)
		target->GetAIInterface()->m_canCallForHelp = true;
	else if(sp->agent == AGENT_FLEE)
		target->GetAIInterface()->m_canFlee = true;
	else if(sp->agent == AGENT_RANGED)
		target->GetAIInterface()->m_canRangedAttack = true;
	else
		target->GetAIInterface()->addSpellToList(sp);

	return true;
}
Example #3
0
int parse_flute_conf_file(repair_arguments_t *ra) {
  
  char *buf = NULL;
  FILE *fp;
  struct stat file_stats;
  int nbytes;
  char *tmp = NULL;
  
  if(stat(ra->flute_conf_file, &file_stats) == -1) {
    printf("Error: %s is not valid file name\n", ra->flute_conf_file);
    fflush(stdout);
    return -1;
  }
  
  if(!(buf = (char*)calloc((file_stats.st_size + 1), sizeof(char)))) {
    printf("Could not alloc memory for buffer!\n");
    fflush(stdout);
    return -1;
  }
  
  if((fp = fopen(ra->flute_conf_file, "rb")) == NULL) {
    printf("Error: unable to open file %s\n", ra->flute_conf_file);
    fflush(stdout);
    free(buf);
    return -1;
  }
  
  nbytes = fread(buf, 1, file_stats.st_size, fp); 
  
  if(nbytes <= 0) {
    free(buf);
    fclose(fp);
    return -1;
  }
  fclose(fp);
  
  tmp = strtok (buf, "=");
  
  while(tmp != NULL) {
    if(strcmp(tmp, "BaseDir") == 0) {
      tmp = strtok(NULL, "\n");
      
      memset(ra->base_dir, 0, MAX_PATH_LENGTH);
      strcpy(ra->base_dir, tmp);
      
      if(ra->base_dir[strlen(ra->base_dir)-1] == '\r') {
	ra->base_dir[strlen(ra->base_dir)-1] = '\0';
      }
    }
    else if(strcmp(tmp, "FECRatio") == 0) {
      tmp = strtok(NULL, "\n");
      ra->fec_ratio = (unsigned short)atoi(tmp);
    }
    else if(strcmp(tmp, "FDTFile") == 0) {
      tmp = strtok(NULL, "\n");

      memset(ra->fdt_file, 0, MAX_PATH_LENGTH);
      strcpy(ra->fdt_file, tmp);
      
      if(ra->fdt_file[strlen(ra->fdt_file)-1] == '\r') {
	ra->fdt_file[strlen(ra->fdt_file)-1] = '\0';
      }
    }
    
    tmp = strtok (NULL, "=");
  }
  
  free(buf);
  
  return 0;
}
Example #4
0
int main(void)
{
  int sockfd, numbytes;
  char buf[MAXDATASIZE];
  struct addrinfo hints, *servinfo, *p;
  int rv;
  char s[INET6_ADDRSTRLEN];
//print local IP and port number
    struct sockaddr_in PatientSock;
    int PatientSockLen;
    //char ipstr[INET6_ADDRSTRLEN]="nunki.usc.edu";
    char ipstr[INET6_ADDRSTRLEN]="localhost";
    struct hostent *he;
    struct in_addr **addr_list;
    int i;
    int getsock_check;
    struct sockaddr_in my_addr;
    int addrlen=sizeof(struct sockaddr);
    char destiaddr[20]="127.0.0.1";
//read patient1.txt
  FILE *file_1;
  char patient1[2][20];
//send file
  char head[50]="authenticate ";
//compare receive
  char com[MAXDATASIZE]={'f','a','i','l','u','r','e','\0'};
//send availble
    char avail[15]={'a','v','a','i','l','a','b','l','e','\0'};
//receive table and print;receive patient key board input; send number
    char availtable[200];
    int availtablelen;
    int appointnum[1];// only for now
    char appointcom[10];//to transform int to char
    int j,k;
    char *availabilities[6][3];
    int printnum;//to check whether all availabilities are stored fully
    char selectmes[15];
//whether successfully booked
    char reserved[15];
    int docportnum;
//test side
   
    
//  if (argc != 2) {
 // fprintf(stderr,"usage: client hostname\n");
 // exit(1);
 // }

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_INET;
    //hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
    
// the IP address of server should be hard coded into the program; change before submit!!!!!!!!!!
  if ((rv = getaddrinfo(destiaddr, PORT, &hints, &servinfo)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    return 1;
  }
// loop through all the results and connect to the first we can
  for(p = servinfo; p != NULL; p = p->ai_next) {
    if ((sockfd = socket(p->ai_family, p->ai_socktype,
			 p->ai_protocol)) == -1) {
      perror("client: socket");
      continue;
    }
    if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
      close(sockfd);
      perror("client: connect");
      continue;
    }
    break;
  }
  if (p == NULL) {
    fprintf(stderr, "client: failed to connect\n");
    return 2;
  }
//inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),s, sizeof s);
//printf("client: connecting to %s\n", s);
    
    
//host name should be hardcode in the program; change before submit!!!!!!
   // gethostname(ipstr, sizeof ipstr);
    he=gethostbyname(ipstr);
  //  getsockname(sockfd, (struct sockaddr *)&PatientSock, &PatientSockLen);
//from description checking!!!!!!!!!!
    //Retrieve the locally-­‐bound name of the specified socket and store it in the sockaddr structure
    getsock_check=getsockname(sockfd,(struct sockaddr *)&my_addr, (socklen_t *)&addrlen);
    //Error checking
    if(getsock_check==-1)
    {
        perror("getsockname");
        exit(1);
    }
    printf("Phase 1: Patient 1 has TCP port number %d and IP address ", ntohs(my_addr.sin_port));
//BJ P73
  //printf("Patient 1 has TCP port number %d and IP address ", ntohs(PatientSock.sin_port));
  addr_list = (struct in_addr **)he->h_addr_list;
  for(i = 0; addr_list[i] != NULL; i++) {
    printf("%s ", inet_ntoa(*addr_list[i]));
  }
  printf("\n");

  freeaddrinfo(servinfo); // all done with this structure
    
//read patient1.txt and send
  file_1=fopen("patient1.txt","r");
  fscanf(file_1,"%s",patient1[0]);
  fscanf(file_1,"%s",patient1[1]);
  fclose(file_1);
  strcat(head,patient1[0]);
  strcat(head," ");
  strcat(head,patient1[1]);
  if (send(sockfd, head, 50, 0) == -1)
    perror("send");
  else
    printf("Phase 1: Authentication requst from Patient 1 with username %s and password %s has been sent to the Health Center Server\n",patient1[0],patient1[1]);
//authenticate successful or not

  if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
    perror("recv");
    exit(1);
  }

  buf[numbytes] = '\0';
  printf("Phase 1: Patient 1 authentication result: %s\n",buf);
 
  
   if(strcmp(buf,com)==0)
    {
  //    printf("dead\n");
      close(sockfd);
      exit(1);
    }
   
  printf("Phase 1: End of Phase 1 for Patient1\n");

// Phase 2!!!!!
//send "available"
    if (send(sockfd, avail, 15, 0) == -1)
        perror("send");
//receive table
    if ((availtablelen = recv(sockfd, availtable, 200, 0)) == -1) {
        perror("recv");
        exit(1);
    }
    avail[availtablelen] = '\0';
//store what you receive
    //strtok(availtable," ");
    for(j=0;j<6;j++)
    {
        for(k=0;k<3;k++)
        {
            if (j==0&&k==0) {
                availabilities[j][k]=strtok(availtable," ");
            }
            else
            {
                if((availabilities[j][k]=strtok(NULL," "))==NULL)
                {
                   // printnum=5;
                    continue;
                }
            }
            //fscanf(file_2,"%s", availabilities[i][j]);
            //  availabilities[i][5][0]=1;//right?
        }
    }
    //need to check whether the last line of availabilities[j][k] is null!
    if (availabilities[5][0]==NULL) {
        printnum=5;
        availabilities[5][0]="-1";//to assign this line as useless
    }
    else
    {
        printnum=6;
    }
//print the table;receive patient key board input; send number
    printf("Phase 2: The following appointments are available for Patient1:\n");
    for(j=0;j<printnum;j++)
    {
        for(k=0;k<3;k++)
        {

            printf("%s ", availabilities[j][k]);
        }
        printf("\n");
    }
    //printf("\n");
    printf("Please enter the preferred appointment index and press enter:\n");
    scanf("%d",&appointnum[0]);//is error check needed here?!!!!!!!!!
    //error check
    sprintf(appointcom,"%d",appointnum[0]);
    while((strcmp(availabilities[0][0],appointcom))&&(strcmp(availabilities[1][0],appointcom))&&(strcmp(availabilities[2][0],appointcom))&&(strcmp(availabilities[3][0],appointcom))&&(strcmp(availabilities[4][0],appointcom))&&(strcmp(availabilities[5][0],appointcom))){
        printf("Please enter the preferred appointment index and press enter:\n");
        scanf("%d",&appointnum[0]);
        sprintf(appointcom,"%d",appointnum[0]);
    }
    //send select message
    strcpy(selectmes, "selection ");
    strcat(selectmes,appointcom);
    if (send(sockfd, selectmes, 15, 0) == -1)
        perror("send");
    //receive reply whether the patient book is accepted
    if ((recv(sockfd, reserved, 15, 0)) == -1) {
        perror("recv");
        exit(1);
    }
    char *docname;
    char *docport;
    if(strcmp(reserved,"notavailable")){
        docname=strtok(reserved," ");// the doctor's name could be stored here
        docport=strtok(NULL," ");
        docportnum=atoi(docport);
        printf("Phase 2: The requested appointment is available and reserved to Patient1. The assigned doctor port number is %d\n",docportnum);
    //end of patient tcp progress
        close(sockfd);
    }
    else{
        printf("Phase 2: The requested appointment from Patient 1 is not available.Exiting...\n");
        close(sockfd);
        exit(1);
    }
    
    //from now on start the phase 3 udp!!!!! 11.9
    int sockfd_1;
    struct addrinfo hints_1, *servinfo_1, *p_1;
    int rv_1;
    int numbytes_1;
    //read patient1insurance.txt
    FILE *file_3;
    char patient1insurance[20];
    // receive price
    socklen_t addr_len_1;
    struct sockaddr_storage their_addr_1;
    char price[3];
    
  //  if (argc != 2) {
   //     fprintf(stderr,"usage: talker hostname message\n");
    //    exit(1);
   // }
    memset(&hints_1, 0, sizeof hints_1);
    hints_1.ai_family = AF_UNSPEC;
    hints_1.ai_socktype = SOCK_DGRAM;
    if ((rv_1 = getaddrinfo(destiaddr, docport, &hints_1, &servinfo_1)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv_1));
        return 1;
    }
    // loop through all the results and make a socket
    for(p_1 = servinfo_1; p_1 != NULL; p_1 = p_1->ai_next) {
        if ((sockfd_1 = socket(p_1->ai_family, p_1->ai_socktype,
                             p_1->ai_protocol)) == -1) {
            perror("talker: socket");
            continue;
        }
        break;
    }
    if (p_1 == NULL) {
        fprintf(stderr, "talker: failed to bind socket\n");
        return 2;
    }
    //screen
    
    
    
    // printf("Phase 3: Patient 1 has a dynamic UDP port number and IP address\n");//handle!!!!!!!!
    
    
    //read patient1insurance.txt
    file_3=fopen("patient1insurance.txt","r");
    fscanf(file_3,"%s",patient1insurance);
    // fscanf(file_1,"%s",patient1[1]);
    fclose(file_3);
    
    if ((numbytes_1 = sendto(sockfd_1, patient1insurance, strlen(patient1insurance), 0,p_1->ai_addr, p_1->ai_addrlen)) == -1) {
        perror("talker: sendto");
        exit(1);
    }
    // IP address and port number
    char hostname[20]="localhost";
    struct hostent *ipaddress;
    struct sockaddr_in my_addr_1;
    int addrlen_1=sizeof(struct sockaddr);
    struct in_addr **addr_list_1;
    ipaddress=gethostbyname(hostname);//IP address
    addr_list_1 = (struct in_addr **)ipaddress->h_addr_list;
    getsockname(sockfd_1,(struct sockaddr *)&my_addr_1, (socklen_t *)&addrlen_1);//socket
    printf("Phase 3: Patient 1 has a dynamic UDP port %d and IP address %s\n",ntohs(my_addr_1.sin_port), inet_ntoa(*addr_list_1[0]));
    // get the Ip address of doc
  
    addr_len_1=sizeof(struct sockaddr);
    printf("Phase 3: The cost estimation request from Patient 1 with insurance plan %s has been sent to the doctor with port number %s and IP adress ", patient1insurance, docport);
    // receive price
    if ((numbytes_1 = recvfrom(sockfd_1, price, 3 , 0,
                             (struct sockaddr *)&their_addr_1, &addr_len_1)) == -1) {
        perror("recvfrom");
        exit(1);
    }
    
   // struct sockaddr_in peer_addr;
    int addrlen_2=sizeof(struct sockaddr);
    struct sockaddr_in *peer_addrt=(struct sockaddr_in *)&their_addr_1;
    char peer_IP[INET6_ADDRSTRLEN];
    inet_ntop(AF_INET,&peer_addrt->sin_addr,peer_IP,sizeof peer_IP);
    printf("%s\n",peer_IP);//Print IP address
    
    
    printf("Phase 3: Patient 1 receives %s$ estimation cost from doctor with port number %s and name %s \n",price,docport, docname);
    //  printf("Phase 3: Patient 1 receives %s$ estimation cost from doctor with port number and name %s \n",price, docname);
    //printf("%s\n",price);
    printf("Phase 3: End of Phase 3 for Patient 1\n");
    freeaddrinfo(servinfo_1);
    // printf("talker: sent %d bytes to %s\n", numbytes, argv[1]);
    close(sockfd_1);
    return 0;

    
    
    
    
    //end of patient program
  return 0;
}
Example #5
0
int
doloop(DB_ENV *dbenv)
{
    DB *dbp;
    DBT key, data;
    char buf[BUFSIZE], *rbuf;
    int ret;
    u_int32_t db_flags;

    dbp = NULL;
    memset(&key, 0, sizeof(key));
    memset(&data, 0, sizeof(data));
    ret = 0;

    for (;;) {
	if (dbp == NULL) {
	    if ((ret = db_create(&dbp, dbenv, 0)) != 0)
		return (ret);

	    db_flags = DB_AUTO_COMMIT | DB_CREATE;

	    if ((ret = dbp->open(dbp,
		NULL, DATABASE, NULL, DB_BTREE, db_flags, 0)) != 0) {
		dbenv->err(dbenv, ret, "DB->open");
		goto err;
	    }
	}

	printf("QUOTESERVER> ");
	fflush(stdout);

	if (fgets(buf, sizeof(buf), stdin) == NULL)
	    break;
	if (strtok(&buf[0], " \t\n") == NULL) {
	    switch ((ret = print_stocks(dbp))) {
	    case 0:
		continue;
	    default:
		dbp->err(dbp, ret, "Error traversing data");
		goto err;
	    }
	}
	rbuf = strtok(NULL, " \t\n");
	if (rbuf == NULL || rbuf[0] == '\0') {
	    if (strncmp(buf, "exit", 4) == 0 ||
		strncmp(buf, "quit", 4) == 0)
		break;
	    dbenv->errx(dbenv, "Format: TICKER VALUE");
	    continue;
	}

	key.data = buf;
	key.size = (u_int32_t)strlen(buf);

	data.data = rbuf;
	data.size = (u_int32_t)strlen(rbuf);

	if ((ret = dbp->put(dbp, NULL, &key, &data, 0)) != 0)
	{
	    dbp->err(dbp, ret, "DB->put");
	    if (ret != DB_KEYEXIST)
		goto err;
	}
    }
err: if (dbp != NULL)
	(void)dbp->close(dbp, DB_NOSYNC);

    return (ret);
}
Example #6
0
VOID TRoute::RouteTo (VOID)
{
   DIR *dir;
   int fd;
   USHORT Zone, Net, Node, Point, DoPack, CheckNet;
   CHAR *p, Flag, Lookup[32], DestPath[128], DestAddr[32], FlagStr[32];
   ULONG TotalSize;
   class TAddress Addr;
   class TPacker *Packer;
   class TNodes *Nodes;
   struct dirent *ent;
   struct stat statbuf;

   Cfg->MailAddress.First ();
   Zone = Cfg->MailAddress.Zone;
   Net = Cfg->MailAddress.Net;
   Node = Cfg->MailAddress.Node;

   DoPack = FALSE;
   DestPath[0] = '\0';
   TotalSize = 0L;

   Flag = 'H';
   if ((p = strtok (NULL, " ")) != NULL) {
      if (!stricmp (p, "hold") || !stricmp (p, "crash") || !stricmp (p, "direct") || !stricmp (p, "normal")) {
         if ((Flag = (CHAR)toupper (*p)) == 'N')
            Flag = 'F';
      }
      strcpy (FlagStr, strupr (p));
   }

   if ((p = strtok (NULL, "")) != NULL)
      strcpy (Line, p);

   if ((p = strtok (Line, " ")) != NULL) {
      Addr.Parse (p);
      if ((p = strtok (NULL, "")) != NULL)
         strcpy (Line, p);
      else
         Line[0] = '\0';

      Point = 0;
      if (Addr.Zone != 0)
         Zone = Addr.Zone;
      if (Addr.Net != 0)
         Net = Addr.Net;
      Node = Addr.Node;
      Point = Addr.Point;

      if (Zone == 0 || Cfg->MailAddress.Zone == Zone) {
         if (Point != 0)
            sprintf (DestPath, "%s\\%04x%04x.pnt\\", Outbound, Net, Node);
         else
            sprintf (DestPath, "%s\\", Outbound);
      }
      else {
         if (Point != 0)
            sprintf (DestPath, "%s.%03x\\%04x%04x.pnt\\", Outbound, Zone, Net, Node);
         else
            sprintf (DestPath, "%s.%03x\\", Outbound, Zone);
      }

      sprintf (DestAddr, "%u:%u/%u.%u", Zone, Net, Node, Point);
      MakeArcMailName (DestAddr, Flag);

      if (Point != 0)
         sprintf (Temp, "%s%08x.xpr", DestPath, Point);
      else
         sprintf (Temp, "%s%04x%04x.xpr", DestPath, Net, Node);

      if ((fd = sopen (Temp, O_RDONLY, SH_DENYNO, S_IREAD|S_IWRITE)) != -1) {
         close (fd);
         cprintf ("ROUTE: %s %u:%u/%u.%u Via %s\r\n", FlagStr, Zone, Net, Node, Point, DestAddr);
         do {
            sprintf (Name, "%s%08lx.pkt", DestPath, time (NULL));
         } while (rename (Temp, Name) != 0);

         if (stat (Name, &statbuf) == 0)
            TotalSize += statbuf.st_size;
         cprintf ("Adding %s (%lub) to archive '%s'\r\n", &Name[strlen (Name) - 12], statbuf.st_size, ArcMailName);
         DoPack = TRUE;
      }
   }

   while ((p = strtok (Line, " ")) != NULL) {
      Addr.Parse (p);
      if ((p = strtok (NULL, "")) != NULL)
         strcpy (Line, p);
      else
         Line[0] = '\0';

      if (Addr.Zone != 0)
         Zone = Addr.Zone;
      if (Addr.Net != 0)
         Net = Addr.Net;
      Node = Addr.Node;
      Point = Addr.Point;

      // Controlla se e' stato comando di compattare la posta di
      // tutti i point (send-to 2:332/402.All).
      if (Point == 65535U && Net != 65535U && Node != 65535U) {
         if (Zone == 0 || Cfg->MailAddress.Zone == Zone)
            sprintf (Temp, "%s\\%04x%04x.pnt", Outbound, Net, Node);
         else
            sprintf (Temp, "%s.%03x\\%04x%04x.pnt", Outbound, Zone, Net, Node);
         if ((dir = opendir (Temp)) != NULL) {
            while ((ent = readdir (dir)) != NULL) {
               strlwr (ent->d_name);
               if (strstr (ent->d_name, ".xpr") != NULL) {
                  sscanf (ent->d_name, "%08hx", &Point);

                  if (Zone == 0 || Cfg->MailAddress.Zone == Zone)
                     sprintf (Temp, "%s\\%04x%04x.pnt\\%08lx.xpr", Outbound, Net, Node, Point);
                  else
                     sprintf (Temp, "%s.%03x\\%04x%04x.pnt\\%08lx.xpr", Outbound, Zone, Net, Node, Point);

                  if ((fd = sopen (Temp, O_RDONLY, SH_DENYNO, S_IREAD|S_IWRITE)) != -1) {
                     close (fd);
                     cprintf ("ROUTE: %s %u:%u/%u.%u Via %s\r\n", FlagStr, Zone, Net, Node, Point, DestAddr);
                     do {
                        sprintf (Name, "%s%08lx.pkt", DestPath, time (NULL));
                     } while (rename (Temp, Name) != 0);

                     if (stat (Name, &statbuf) == 0)
                        TotalSize += statbuf.st_size;
                     cprintf ("Adding %s (%lub) to archive '%s'\r\n", &Name[strlen (Name) - 12], statbuf.st_size, ArcMailName);
                     DoPack = TRUE;
                  }
               }
            }
            closedir (dir);
         }
      }
      // Controlla se e' stato comando di compattare la posta di
      // tutta una zona (send-to all 2:All) o di un solo net (send-to 2:332/All).
      else if (Net == 65535U || Node == 65535U) {
         CheckNet = (Net != 65535U) ? TRUE : FALSE;
         sprintf (Lookup, "%04x", Net);
         if (Zone == 0 || Cfg->MailAddress.Zone == Zone)
            sprintf (Temp, "%s", Outbound);
         else
            sprintf (Temp, "%s.%03x", Outbound, Zone);
         if ((dir = opendir (Temp)) != NULL) {
            while ((ent = readdir (dir)) != NULL) {
               strlwr (ent->d_name);
               if (strstr (ent->d_name, ".xpr") != NULL) {
                  DoPack = FALSE;
                  if (CheckNet == FALSE) {
                     sscanf (ent->d_name, "%04hx%04hx", &Net, &Node);
                     DoPack = TRUE;
                  }
                  else if (!strncmp (ent->d_name, Lookup, strlen (Lookup))) {
                     sscanf (ent->d_name, "%04hx%04hx", &Net, &Node);
                     DoPack = TRUE;
                  }

                  if (DoPack == TRUE) {
                     if (Zone == 0 || Cfg->MailAddress.Zone == Zone)
                        sprintf (Temp, "%s\\%04x%04x.xpr", Outbound, Net, Node);
                     else
                        sprintf (Temp, "%s.%03x\\%04x%04x.xpr", Outbound, Zone, Net, Node);

                     if ((fd = sopen (Temp, O_RDONLY, SH_DENYNO, S_IREAD|S_IWRITE)) != -1) {
                        close (fd);
                        cprintf ("ROUTE: %s %u:%u/%u Via %s\r\n", FlagStr, Zone, Net, Node, DestAddr);
                        do {
                           sprintf (Name, "%s%08lx.pkt", DestPath, time (NULL));
                        } while (rename (Temp, Name) != 0);

                        if (stat (Name, &statbuf) == 0)
                           TotalSize += statbuf.st_size;
                        cprintf ("Adding %s (%lub) to archive '%s'\r\n", &Name[strlen (Name) - 12], statbuf.st_size, ArcMailName);
                     }
                  }
               }
            }
            closedir (dir);
         }
      }
      else {
         if (Zone == 0 || Cfg->MailAddress.Zone == Zone) {
            if (Point != 0)
               sprintf (Temp, "%s\\%04x%04x.pnt\\%08x.xpr", Outbound, Net, Node, Point);
            else
               sprintf (Temp, "%s\\%04x%04x.xpr", Outbound, Net, Node);
         }
         else {
            if (Point != 0)
               sprintf (Temp, "%s.%03x\\%04x%04x.pnt\\%08x.xpr", Outbound, Zone, Net, Node, Point);
            else
               sprintf (Temp, "%s.%03x\\%04x%04x.xpr", Outbound, Zone, Net, Node);
         }

         if ((fd = sopen (Temp, O_RDONLY, SH_DENYNO, S_IREAD|S_IWRITE)) != -1) {
            close (fd);
            cprintf ("ROUTE: %s %u:%u/%u Via %s\r\n", FlagStr, Zone, Net, Node, DestAddr);
            do {
               sprintf (Name, "%s%08lx.pkt", DestPath, time (NULL));
            } while (rename (Temp, Name) != 0);

            if (stat (Name, &statbuf) == 0)
               TotalSize += statbuf.st_size;
            cprintf ("Adding %s (%lub) to archive '%s'\r\n", &Name[strlen (Name) - 12], statbuf.st_size, ArcMailName);
            DoPack = TRUE;
         }
      }
   }

   if (DoPack == TRUE) {
      MakeArcMailName (DestAddr, Flag);
      sprintf (Name, "%s*.pkt", DestPath);

      if ((Packer = new TPacker (Cfg->SystemPath)) != NULL) {
         Packer->First ();
         if (Packer->CheckArc (ArcMailName) == FALSE) {
            if ((Nodes = new TNodes (Cfg->NodelistPath)) != NULL) {
               if (Nodes->Read (DestAddr) == TRUE)
                  Packer->Read (Nodes->Packer);
               delete Nodes;
            }
         }
         if (Log != NULL) {
            Log->Write ("#Packing mail for %s (%lu bytes)", DestAddr, TotalSize);
            Log->Write ("#Executing %s", Packer->PackCmd);
         }
         Packer->DoPack (ArcMailName, Name);
         delete Packer;
      }
   }
}
Example #7
0
int readPgm(char *fileName, MyImage *image)
{
	FILE *in_file;
	char ch;
	int type;
	char version[3];
	char line[100];
	char mystring [20];
	char *pch;
	int i;
	long int position;

	in_file = fopen(fileName, "r");
	if (in_file == NULL)
	{
		printf("ERROR: Unable to open file %s\n\n", fileName);
		return -1;
	}
	printf("\nReading image file: %s\n", fileName);
	// Determine image type (only pgm format is allowed)*/
	ch = fgetc(in_file);
	if(ch != 'P')
	{
		printf("ERROR: Not valid pgm file type\n");
		return -1;
	}

	ch = fgetc(in_file);


	/*convert the one digit integer currently represented as a character to

         an integer(48 == '0')*/

	type = ch - 48;

	if(type != 5)
	{
		printf("ERROR: only pgm raw format is allowed\n");
		return -1;
	}
	// Skip comments
//	char line[100];
	while ((ch = fgetc(in_file)) != EOF && isspace(ch));
	position = ftell(in_file);


	// skip comments
	if (ch == '#')
		{
			fgets(line, sizeof(line), in_file);
			while ((ch = fgetc(in_file)) != EOF && isspace(ch));
			position = ftell(in_file);
		}

	fseek(in_file, position-1, SEEK_SET);

	fgets (mystring , 20, in_file);
	pch = (char *)strtok(mystring," ");
	image->width = atoi(pch);
	pch = (char *)strtok(NULL," ");
	image->height = atoi(pch);
	fgets (mystring , 5, in_file);
	image->maxgrey = atoi(mystring);
	image->data = (unsigned char*)malloc(sizeof(unsigned char)*(image->height*image->width));//new unsigned char[row*col];
	image->flag = 1;
	for(i=0;i<(image->height*image->width);i++)
	{	
		ch = fgetc(in_file);
		image->data[i] = (unsigned char)ch;
	}
	fclose(in_file);
	return 0;
}
Example #8
0
int main(int argc , char *argv[])
{
    if(argc < 3)
    {
        perror("Config file and/or Database file path error!\n");
        return EXIT_FAILURE;
    }

    FILE *fp = fopen(argv[1],"r");

    if ( NULL == fp )
    {
        perror("Database Configuration File Read Failure");
        return 1;
    }

    FILE *db = fopen(argv[2],"a");
    if ( NULL == db )
    {
        perror("Database Log File Open Failure");
        return 1;
    }

    fseek(fp, 0, SEEK_END);
    long pos = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    char *device = malloc(pos * sizeof(char));
    fread(device, pos, 1, fp);
    fclose(fp);

    char *gateway, *item;

    gateway = strtok(device, "\n");

    if( NULL != gateway )
        item = strtok(NULL, "");

    // Gateway Info Parsing
    char *token, *ip;
    unsigned short int port;

    token = strtok(gateway, ",");

    ip = token;

    if( NULL != token )
    {
        token = strtok(NULL, ",");
    }

    port = (unsigned short int) atoi(token);

    // Device Info Parsing
    char *d_token, *d_token2, *d_token3, *d_type, *d_ip;
    unsigned short int d_port;
    int d_area;

    d_token = strtok(item, ",");

    d_type = d_token;

    if( NULL != d_token )
    {
        d_token = strtok(NULL, "");
    }

    d_token2 = strtok(d_token, ",");

    if( NULL != d_token2 )
    {
        d_ip = d_token2;
        d_token3 = strtok(NULL, "");
    }

    d_token3 = strtok(d_token3, ",");

    if( NULL != d_token3 )
    {
        d_port = (unsigned short int) atoi(d_token3);
        d_area = atoi(strtok(NULL, ","));
    }

    int sock;
    struct sockaddr_in server;
    char server_reply[MSG_SIZE];

    //Create socket
    sock = socket(AF_INET , SOCK_STREAM , 0);
    if (sock == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");

    server.sin_addr.s_addr = inet_addr( ip );
    server.sin_family = AF_INET;
    server.sin_port = htons( port );

    //Connect to remote server
    if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        perror("connect failed. Error");
        return 1;
    }

    puts("Connected\n");

    char *type, *action;
    // System State (Off by default)
    char *state = ON;

    // Register Message
    char msg[MSG_SIZE];
    char log_msg[MSG_SIZE];

    sprintf(msg,
            "Type:register;Action:%s-%s-%d-%d",
            d_type, d_ip, d_port, d_area);
    //Send the register message (Register will be the only message sent from database)
    write(sock, msg, strlen(msg));

    while(1)
    {
        // The database will only receive commands from Gateway
        if( recv(sock , server_reply , MSG_SIZE , 0) < 0)
        {
            puts("Gateway reply failed");
            break;
        }

        puts("Gateway reply:");
        puts(server_reply);

        getCommands(server_reply,&type,&action);

        if ( strncmp( type, CMD_INSERT, strlen(CMD_INSERT) ) == 0 )
        {
            strcpy(log_msg, action);
            printf("Value: %s\n", log_msg);

            fprintf(db, "%s", log_msg);
            fflush(db);

        }

        memset(log_msg, 0, sizeof(log_msg));
        memset(msg, 0, sizeof(msg));
        memset(server_reply, 0, sizeof(server_reply));
    }

    close(db);
    close(sock);
    return 0;
}
LanguageType Application::getCurrentLanguage()
{
    char *pLanguageName = getenv("LANG");
    LanguageType ret = LanguageType::ENGLISH;
    if (!pLanguageName)
    {
        return LanguageType::ENGLISH;
    }
    strtok(pLanguageName, "_");
    if (!pLanguageName)
    {
        return LanguageType::ENGLISH;
    }
    
    if (0 == strcmp("zh", pLanguageName))
    {
        ret = LanguageType::CHINESE;
    }
    else if (0 == strcmp("en", pLanguageName))
    {
        ret = LanguageType::ENGLISH;
    }
    else if (0 == strcmp("fr", pLanguageName))
    {
        ret = LanguageType::FRENCH;
    }
    else if (0 == strcmp("it", pLanguageName))
    {
        ret = LanguageType::ITALIAN;
    }
    else if (0 == strcmp("de", pLanguageName))
    {
        ret = LanguageType::GERMAN;
    }
    else if (0 == strcmp("es", pLanguageName))
    {
        ret = LanguageType::SPANISH;
    }
    else if (0 == strcmp("nl", pLanguageName))
    {
        ret = LanguageType::DUTCH;
    }
    else if (0 == strcmp("ru", pLanguageName))
    {
        ret = LanguageType::RUSSIAN;
    }
    else if (0 == strcmp("ko", pLanguageName))
    {
        ret = LanguageType::KOREAN;
    }
    else if (0 == strcmp("ja", pLanguageName))
    {
        ret = LanguageType::JAPANESE;
    }
    else if (0 == strcmp("hu", pLanguageName))
    {
        ret = LanguageType::HUNGARIAN;
    }
    else if (0 == strcmp("pt", pLanguageName))
    {
        ret = LanguageType::PORTUGUESE;
    }
    else if (0 == strcmp("ar", pLanguageName))
    {
        ret = LanguageType::ARABIC;
    }
    else if (0 == strcmp("nb", pLanguageName))
    {
        ret = LanguageType::NORWEGIAN;
    }
    else if (0 == strcmp("pl", pLanguageName))
    {
        ret = LanguageType::POLISH;
    }
    else if (0 == strcmp("tr", pLanguageName))
    {
        ret = LanguageType::TURKISH;
    }
    else if (0 == strcmp("uk", pLanguageName))
    {
        ret = LanguageType::UKRAINIAN;
    }
    else if (0 == strcmp("ro", pLanguageName))
    {
        ret = LanguageType::ROMANIAN;
    }
    else if (0 == strcmp("bg", pLanguageName))
    {
        ret = LanguageType::BULGARIAN;
    }
    
    return ret;
}
//
//得到本机的IP地址
//
int GetSrcIpAddr()
{
	//访问注册表,此程序包括应用层和驱动层都只支持单网卡。没有考虑多网卡的问题。
	//因此在应用程序中只需要寻找单网卡的IP,如果有两个以上的IP,不能保证该程序
	//正确
	
	HKEY hKey;
	//DWORD disposition;
 
	LPBYTE owner_Get=new BYTE[256]; 
    DWORD Type=REG_SZ; 
	DWORD DataSize=256;

	//用来存储中间结果
	TCHAR StrMid[256];
    memset(StrMid,0,256);

	//临时字符串变量,用来试探键值
	TCHAR CommonSignal[5];
	memset(CommonSignal,0,5);
	int   num=0;

	//字符串数组用来存放子键值
	char SubKey[256];

	for(num=0;num<1000;num++)
	{
		sprintf(CommonSignal,"%d",num);
		if((RegOpenKeyEx(
		    HKEY_LOCAL_MACHINE,
		    strcat(strcpy(SubKey,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards\\"),CommonSignal),
			0,
		    KEY_READ,//不能为0,根据下面是查询还是修改/删除,赋为KEY_READ或KEY_WRITE
		    &hKey))!=ERROR_SUCCESS)
			continue;
		else
			break;
		return 0;
	}

    if( RegQueryValueEx(
		 hKey,
		 "ServiceName",
		 NULL,
		 &Type,
		 owner_Get,
		 &DataSize)== ERROR_SUCCESS)
	{
		 strcpy(StrMid,(char*)owner_Get);
	}
	else 
		return 0;

	//
	//下面是根据StrMid的值来得到IP
	//
    if((RegOpenKeyEx(
		HKEY_LOCAL_MACHINE,
		strcat(strcat(strcpy(SubKey,"SYSTEM\\CurrentControlSet\\Services\\"),StrMid),"\\Parameters\\Tcpip"),
		0,
		KEY_READ,
		&hKey))==ERROR_SUCCESS)
	{
		 if( RegQueryValueEx(
		     hKey,
		     "IPAddress",
		     NULL,
		     &Type,
		     owner_Get,
		     &DataSize)== ERROR_SUCCESS)
		 {
			 //得到IP地址,将其保存到全局变量SrcIpAddr中,并返回真
		     strcpy(StrMid,(char*)owner_Get);
			 char *token= strtok( StrMid, "." );
			 int i=0;
             while( token != NULL)
			 {
                 Global.SrcIpAddr[i]=(unsigned char)(atoi(token));
				 token = strtok( NULL, "." );
				 i++;
			 }
			 return 1;
		 }
	}

	return 0;
}
int main(int argc, char *argv[])
{

    FILE *in=NULL, *wikiout=NULL,*htmlout=NULL;
    char * ptrch;
    char header[MAX_BUFFER][MAX_STRING];
    char col[MAX_BUFFER][MAX_STRING];
    char buffer[4096];
    int c,index, option_index = 0;
    char *param_wiki_output=NULL;
    char *param_html_output=NULL;
    char *param_file_input=NULL;
    int  linecounter=0;
    static struct option long_options[] = {
            {"wiki", 1, 0, 0},
            {"html", 1, 0, 0},
            {"i", 1, 0, 0}
     };

    int j=0,i=0;
    char separator[5];
    separator[0]=',';
    separator[1]='"';
    separator[2]='\0';


    prog_desc(argv);  //program descripton and title
    while(1) {
        c = getopt_long (argc, argv,"",long_options, &option_index);

        if (c == -1)
            break;

        switch (c) {
            case 0:
                index=option_index;
                switch (index) {
                   case 0:  //wiki
                        param_wiki_output = optarg;
                        break;
                   case 1:  // html
                        param_html_output = optarg;
                        break;
                    case 2:  // input
                        param_file_input = optarg;
                        break;
                    default:
                        printf("Unknown Parameter: %i\n",index);
                        helpme(argv);

                }
                break;
            default:
                        printf("Invalid Parameter: %i\n",c);
                        helpme(argv);

        }
    }

    if (optind < argc) {
        printf (" Ignored no option parameter(s): ");
        while (optind < argc)
            printf ("%s ", argv[optind++]);
        printf ("\n");
    }


    if ((param_wiki_output==NULL) &&( param_html_output==NULL)) {

         printf(" Error:  No output file specified:  use --wiki fname or --html fname\n\n");
         helpme(argv);

    }
    else {
		if (param_wiki_output !=NULL){
            wikiout=fopen(param_wiki_output,"w");
            if(wikiout==NULL ){
                printf("Can't create wiki output file %s\n",param_wiki_output);
                exit(1);
            }
		}
		if (param_html_output !=NULL) {
            htmlout=fopen(param_html_output,"w");
            if(htmlout==NULL ){
                printf("Can't create html output file %s\n",param_html_output);
                exit(1);
            }
        }
    }
    if (param_file_input ==NULL){
        printf("input text file required\n");
        helpme(argv);
    }
    else {
       in =fopen(param_file_input,"r");
       if(in==NULL ){
             printf("Can't open input file %s\n",param_file_input);
             exit(1);
       }
    }

	linecounter=0;
	while(!feof(in)) {
		if(fgets(buffer, MAX_STRING, in)) {
			//buflen=strlen(buffer);
			if (linecounter==0){
				// linecounter==0 means we are dealing with a header
				//remove double quotes("), replace comman (,) with !
				// do the column header first

				ptrch = strtok (buffer,",");  //tokens are delimited with pairs of quote comma
				i=0;
				while (ptrch != NULL) {
					   strcpy(header[i],ptrch);
					   removeQuotes(header[i]);
					   i++;
					   ptrch = strtok (NULL, ",");
				}

				if (htmlout!=NULL){
					 fprintf(htmlout,"<table class='wikitable' border='1'>\n");
					 fprintf(htmlout,"<tr>\n");
					 for (j=0; j < i;j++) {
						fprintf(htmlout,"<th scope='col'>%s</th>\n",header[j]);
					 }
					 fprintf(htmlout,"</tr>\n");
				}
				if (wikiout!=NULL){
					 fprintf(wikiout,"== Partlist ==\n\n");
					 fprintf(wikiout,"{| border='1' class='wikitable'\n");
					 fprintf(wikiout,"!%s",header[0]);
					 for(j=1;j < i;j++) {
						fprintf(wikiout,"!!%s",header[j]);
					 }
					// fprintf(wikiout,"\n");
				}



			}   // linecounter =0 only
            else {
                // tokens are separated by pair of quotes

				ptrch = strtok (buffer,"\"");  //tokens are delimited with quotes
				i=0;
				while (ptrch != NULL) {
				       if(*ptrch !=','){
                           strcpy(col[i],ptrch);
                           removeQuotes(col[i]);
                           i++;
                        }
					    ptrch = strtok (NULL, "\"");
				}


				 if (htmlout!=NULL){
					 fprintf(htmlout,"<tr>");
					 for (j=0;j < i-1;j++) {
						fprintf(htmlout,"<td>%s</td> ",col[j]);
					 }
					 fprintf(htmlout,"</tr>\n");

				 }
				  if (wikiout!=NULL){
					 fprintf(wikiout,"|-\n");
					 fprintf(wikiout,"|%s",col[0]);
					 for (j=1;j<i-1;j++) {
						fprintf(wikiout,"||%s",col[j]);
					 }
					  fprintf(wikiout,"\n");

				 }
            }

		}  //if (fgets(
         linecounter++;
	} //while !feof

	if (htmlout!=NULL){
	fprintf(htmlout,"</table>\n\n");
	printf("\n HTML FIle created: %s\n",param_html_output);
	}

   if (wikiout!=NULL){
        fprintf(wikiout,"|}\n\n");
        printf("\n Wiki FIle created: %s\n",param_wiki_output);
   }


   fclose(in);

   if(htmlout!=NULL ){
         fclose(htmlout);
   }
   if(wikiout!=NULL ) {
         fclose(wikiout);
   }
   return 0;
}
Example #12
0
/*{{{  data*/
void ReadDataDistanceMatrix(value** points, FILE* inputFile, int k) {
	List tempList;

	size_t lineSize = 0;

	char* lineBuff = NULL;
	char* temp;
	char delims[5] = "\t ,\n";
	char* token = NULL;
	int num = 0;
	int i;
	int line = 0;

	dm = malloc(sizeof(datadistanceMatrix));
	dm->data=NULL;
	dm->dataDist=NULL;
	dm->dataNum=0;
	dm->queries=NULL;
	dm->iterator=0;
	dm->queryDist=NULL;
	dm->queryNum=0;
	dm->qIterator=0;
	dm->k = k;
	getline(&lineBuff, &lineSize, inputFile);
	/*skip the first value*/
	token = strtok(lineBuff, delims);

	InitList(&tempList, BUFFSIZE * sizeof(char), NULL, NULL,NULL);
	
	while (token != NULL) {
		token = strtok(NULL, delims);
		if (token == NULL)
			break;
		temp = malloc((LABELSIZE + 1) * sizeof(char));
		memcpy(temp, token, strlen(token));
		temp[strlen(token)] = '\0';
		InsertValueList(tempList, temp);
		num++;
		free(temp);
	}

	SetDataSize(num);
	*points = malloc(num*sizeof(value));
	value* newData = *points;

	char* tempVal = GetFirst(tempList);
	for (i = 0; i < num; i++) {
		newData[i].name = malloc(LABELSIZE * sizeof(char));
		memset(newData[i].name,'\0',LABELSIZE);
		if(tempVal ==NULL)
			continue;
		strcpy(newData[i].name, tempVal);
		tempVal=GetNext(tempList);
	}

	dm->dataDist = malloc(num * sizeof(double*));
	while (getline(&lineBuff, &lineSize, inputFile) != -1) {

		dm->dataDist[line] = malloc(num * sizeof(double));
		newData[line].content=malloc(sizeof(int));
		memcpy(newData[line].content,&line,sizeof(int));


		token = strtok(lineBuff, delims);
		if (token == NULL)
			break;
		for (i = 0; i < num; i++) {
			dm->dataDist[line][i] = atoi(token);
			token = strtok(NULL, delims);
		}
		line++;
	}
	dm->dataNum=line;
	data.tableSize = dm->dataNum;
	DestroyList(&tempList);

	free(lineBuff);


}
Example #13
0
void process_cmd(char *readbuf, int length) {
   typedef enum pipe_cmd_type{ca,im,tl,px,bo,tv,an,as,at,ac,ab,sh,co,br,sa,is,vs,rl,ec,em,wb,mm,ie,ce,ro,fl,ri,ss,qu,pv,bi,ru,md,sc,rs,bu,mn,mt,mi,mb,me,mx,mf,vm,vp,wd,sy,cn,st} pipe_cmd_type;
   char pipe_cmds[] = "ca,im,tl,px,bo,tv,an,as,at,ac,ab,sh,co,br,sa,is,vs,rl,ec,em,wb,mm,ie,ce,ro,fl,ri,ss,qu,pv,bi,ru,md,sc,rs,bu,mn,mt,mi,mb,me,mx,mf,vm,vp,wd,sy,cn,st";
   pipe_cmd_type pipe_cmd;
   int parcount;
   char pars[128][10];
   long int par0;
   char cmd[3];
   char par[MAX_COMMAND_LEN];
   char *parstring=0, *temp;
   int key = -1;
   
   if (length < 2 || length > (MAX_COMMAND_LEN - 2)) return;
   
   //Get cmd
   strncpy(cmd, readbuf, 2);
    //find 2 letter command and translate into enum
   temp = strstr(pipe_cmds, cmd);
   if (temp == NULL) return;
   pipe_cmd = (pipe_cmd_type)((temp - pipe_cmds) / 3);
  
   if(length > 3) {
      strcpy(par, readbuf + 3);
      par[length-3] = 0;
      //extract space separated numeric parameters
      // and make separate string parameter (strtok changes the original)
      asprintf(&parstring, "%s", par);
      parcount = 0;
      temp = strtok(par, " ");
      while(parcount<10 && temp != NULL) {
         strcpy(pars[parcount], temp);
         parcount++;
         temp = strtok(NULL, " ");
      }
      par0 = strtol(pars[0], NULL, 10);
   } else {
      par0 = 0;
   }
   
   switch(pipe_cmd) {
      case ca:
         if(par0 == 1) {
            if (parcount > 1) {
               long vtime = strtol(pars[1], NULL, 10);
               video_stoptime = time(NULL) + vtime;
               printLog("Capturing %d seconds\n", vtime);
            }
            start_video(0);
         }  else {
            stop_video(0);
         }
         break;
      case im:
         capt_img();
         break;
      case tl:
         if(par0) {
            timelapse = 1;
            lapse_cnt = 1;
            updateStatus();
            printLog("Timelapse started\n");
         }
         else {
            image2_cnt++;
            timelapse = 0;
            updateStatus();
            printLog("Timelapse stopped\n");
         }
         break;
      case px:
         stop_all();
         addUserValue(c_video_width, pars[0]);
         addUserValue(c_video_height, pars[1]);
         addUserValue(c_video_fps, pars[2]);
         addUserValue(c_MP4Box_fps, pars[3]);
         addUserValue(c_image_width, pars[4]);
         addUserValue(c_image_height, pars[5]);
         start_all(0);
         break;
      case bo:
         addUserValue(c_MP4Box, pars[0]);
         break;
      case tv:
         addUserValue(c_tl_interval, pars[0]);
         break;
      case an:
         addUserValue(c_annotation, parstring);
         break;
      case as:
         addUserValue(c_anno_text_size, pars[0]);
         break;
      case at:
         addUserValue(c_anno3_custom_text_colour, pars[0]);
         addUserValue(c_anno3_custom_text_Y, pars[1]);
         addUserValue(c_anno3_custom_text_U, pars[2]);
         addUserValue(c_anno3_custom_text_V, pars[3]);
         break;
      case ac:
         addUserValue(c_anno3_custom_background_colour, pars[0]);
         addUserValue(c_anno3_custom_background_Y, pars[1]);
         addUserValue(c_anno3_custom_background_U, pars[2]);
         addUserValue(c_anno3_custom_background_V, pars[3]);
         break;
      case ab:
         addUserValue(c_anno_background, pars[0]);
         break;
      case sh:
         key = c_sharpness;
         break;
      case co:
         key = c_contrast;
         break;
      case br:
         key = c_brightness;
         break;
      case sa:
         key = c_saturation;
         break;
      case is:
         key = c_iso;
         break;
      case vs:
         key = c_video_stabilisation;
         break;
      case rl:
         key = c_raw_layer;
         break;
      case ec:
         key = 1000 + c_exposure_compensation;
         break;
      case em:
         key = 1000 + c_exposure_mode;
         break;
      case wb:
         key = 1000 + c_white_balance;
         break;
      case mm:
         key = 1000 + c_metering_mode;
         break;
      case ie:
         key = 1000 + c_image_effect;
         break;
      case ce:
         addUserValue(c_colour_effect_u, pars[1]);
         addUserValue(c_colour_effect_v, pars[2]);
         key = c_colour_effect_en;
         break;
      case ro:
         key = c_rotation;
         break;
      case fl:
         if(par0 & 1) addUserValue(c_hflip, "1"); else addUserValue(c_hflip, "0"); 
         if((par0 >> 1) & 1) addUserValue(c_vflip, "1"); else addUserValue(c_vflip, "0"); 
         cam_set(c_hflip);
         break;
      case ri:
         addUserValue(c_sensor_region_y, pars[1]);
         addUserValue(c_sensor_region_w, pars[2]);
         addUserValue(c_sensor_region_h, pars[3]);
         key = c_sensor_region_x;
         break;
      case ss:
         addUserValue(c_shutter_speed, pars[0]);
         key = c_shutter_speed;
         break;
      case qu:
         key = c_image_quality;
         break;
      case pv:
         stop_all();
         addUserValue(c_quality, pars[0]);
         addUserValue(c_width, pars[1]);
         addUserValue(c_divider, pars[2]);
         start_all(0);
         break;
      case bi:
         stop_all();
         addUserValue(c_video_bitrate, pars[0]);
         start_all(0);
         break;
      case st:
         stop_all();
         addUserValue(c_stat_pass, pars[0]);
         start_all(0);
         break;
      case wd:
         addUserValue(c_watchdog_interval, pars[0]);
         addUserValue(c_watchdog_errors, pars[1]);
         break;
      case ru:
         if (par0 == 0) {
            stop_all();
            idle = 1;
            printLog("Stream halted\n");
         } else {
            start_all(1);
            idle = 0;
            printLog("Stream continued\n");
         }
         updateStatus();
         break;
      case mx:
         key = c_motion_external;
         //If switching to internal with motion detection on then try to kill external motion
         if (cfg_val[c_motion_detection] != 0 && !par0) {
            if(system("killall motion") == -1) error("Could not stop external motion", 1);
            printLog("External motion detection stopped\n");
         }
         break;
      case md:
         exec_macro(cfg_stru[c_do_cmd], readbuf);
         stop_all();
         if (cfg_val[c_motion_external]) {
            if(par0 == 0) {
               if(system("killall motion") == -1) error("Could not stop external motion", 1);
               printLog("External motion detection stopped\n");
            }
            else {
               if (cfg_val[c_motion_detection] == 0) {
                  if(system("motion") == -1) error("Could not start external motion", 1);
                  printLog("External motion detection started\n");
               } else {
                  printLog("Motion already running. md 1 ignored\n");
               }
            }
         } else {
            if(par0 == 0) {
               printLog("Internal motion detection stopped\n");
            }
            else {
               printLog("Internal motion detection started\n");
            }
         }
         cfg_val[c_motion_detection] = par0?1:0;
         start_all(0);
         updateStatus();
         break;
      case sc:
         set_counts();
         printLog("Scan for highest count\n");
         break;
      case rs:
         printLog("Reset settings to defaults\n");
         stop_all();
         read_config("/etc/raspimjpeg", 1);
         saveUserConfig(cfg_stru[c_user_config]);
         start_all(0);
         break;
      case bu:
         key = c_video_buffer;
         break;
      case vp:
         stop_all();
         addUserValue(c_vector_preview, pars[0]);
         start_all(0);
         break;
      case mn:
         key = c_motion_noise;
         break;
      case mt:
         key = c_motion_threshold;
         break;
      case mi:
         key = c_motion_image + 1000;
         break;
      case mb:
         key = c_motion_startframes;
         break;
      case me:
         key = c_motion_stopframes;
         break;
      case mf:
         key = c_motion_file;
         break;
      case vm:
         key = c_vector_mode;
         break;
      case sy:
         exec_macro(parstring, NULL);
         break;
      case cn:
         stop_all();
         addUserValue(c_camera_num, pars[0]);
         start_all(0);
         break;
      default:
         printLog("Unrecognised pipe command\n");
         break;
   }
Example #14
0
void NoVoHT::merge(){
   char buf[300];
   char sec[300];
	sem_wait(&map_lock);
   sem_wait(&write_lock);
   fflush(dbfile);
   rewind(dbfile);
   while (readTabString(dbfile,buf) != NULL){
      if(buf[0] == '~'){
         readTabString(dbfile, sec);
         char * pos;
         pos = strtok(sec, ",");
         while (pos != NULL) {
            fseek(swapFile, (off_t) atoi(pos), SEEK_SET);
            char test[300];
            readTabString(swapFile,test);
            if (strcmp(test,(buf+1)) == 0){
               fseek(swapFile, (off_t) atoi(pos), SEEK_SET);
               fputc('~',swapFile);
            }
            pos = strtok(NULL, ",");
         }
      }
      else{
         //while (map_lock) {}
         //map_lock = true;
         //sem_wait(&map_lock);
         fseek(swapFile, 0, SEEK_END);
         string s(buf);
         readTabString(dbfile,sec);
         kvpair* p = kvpairs[hash(s)%size];
         while (p != NULL){
            if (p->key.compare(s) == 0){
               destroyFposList(p->positions);
               p->positions = new fpos_list;
               p->positions->next = NULL;
               fgetpos(swapFile, &(p->positions->pos));
               fprintf(swapFile, "%s\t%s\t", p->key.c_str(), p->val.c_str());
               printf("%s\t%s\t", p->key.c_str(), p->val.c_str());
               p->diff = false;
               break;
            }
            else
               p = p->next;
         }
         //map_lock = false;
         //sem_post(&map_lock);
      }
   }
	fclose(dbfile);
   fclose(swapFile);
   rename(".novoht.swp", filename.c_str());
   dbfile = fopen(filename.c_str(), "r+");
   //remove(".novoht.mrg");
	int rmrc = unlink(".novoht.mrg");
   if (rmrc) {
      perror("Error deleting merge file");
   }
   rewriting = false;
	sem_post(&map_lock);
   sem_post(&write_lock);
}
Example #15
0
void mint_AnimCreateFromXML(MintTexture* mintTexture, char* xmlPath)
{
	FILE* fp;
	char buf[1024];
	int i;
	int j;

	// TODO(jeru): Note this limitation
	SDL_Rect rects[999];
	char names[999][99];
	int frameCount = 0;
	char* token;
	char tokens[11][99];
	char currentToken = 0;

	if ((fp = fopen(xmlPath, "r")) == NULL) {
		printf("Failed to load xml");
		return;
	}

	while (fgets(buf, sizeof(buf), fp) != NULL) {
		buf[strlen(buf) - 1] = '\0';

		if (buf[0] == ' ' && buf[4] == '<') {
			currentToken = 0;
			token = strtok(buf, "\"");

			while (token != NULL) {
				strcpy(tokens[currentToken], token);
				currentToken++;
				token = strtok(NULL, "\"");
			}

			for (i = strlen(tokens[1]); ; i--) {
				if (tokens[1][i] == '_') {
					tokens[1][i+1] = '\0';
					break;
				}
			}

			strcpy(names[frameCount], tokens[1]);
			rects[frameCount].x = atoi(tokens[3]);
			rects[frameCount].y = atoi(tokens[5]);
			rects[frameCount].w = atoi(tokens[7]);
			rects[frameCount].h = atoi(tokens[9]);
			frameCount++;
		}
	}

	fclose(fp);

	int totalAnims = 0;
	char* currentName;

	currentName = names[0];

	for (i = 0; i < frameCount; i++) {
		if (strcmp(currentName, names[i])) {
			totalAnims++;
			currentName = names[i];
		}
	}

	mint_AnimInit(mintTexture, totalAnims);

	int startFrame = 0;
	int endFrame = 0;
	int currentAnim = 0;

	strcpy(currentName, names[0]);

	// NOTE(jeru): Make sure everything ends with _XXXX.png
	for (i = 0; i < frameCount; i++) {
		if (strcmp(currentName, names[i])) {
			endFrame = i;
			mint_AnimCreate(mintTexture, currentAnim, currentName, endFrame - startFrame, 60);
			for (j = startFrame; j < endFrame; j++) {
				mint_AnimDefineFrame(mint_AnimGetByIndex(mintTexture, currentAnim),
			                       j - startFrame,
			                       rects[j].x,
			                       rects[j].y,
			                       rects[j].w,
			                       rects[j].h);
			}
			startFrame = endFrame;
			currentAnim++;
			currentName = names[i];
		}
	}
}
Example #16
0
int main(int argc ,char *argv[])
{
    char infname[512], ine2pname[512], in_rom_patch[512];
    char outfname[512], oute2pname[512], out_rom_patch[512];
	char chipsets[1024];
	char fw_name[128], e2p_name[128], rom_patch_name[128];
    char *rt28xxdir;
    char *chipset, *token;
	char *wow, *rt28xx_mode;
	int is_bin2h_fw = 0, is_bin2h_rom_patch = 0, is_bin2h_e2p=0;
   
    rt28xxdir = (char *)getenv("RT28xx_DIR");
    chipset = (char *)getenv("CHIPSET");
	memcpy(chipsets, chipset, strlen(chipset));
	wow = (char *)getenv("HAS_WOW_SUPPORT");
	rt28xx_mode = (char *)getenv("RT28xx_MODE");

    if(!rt28xxdir) {
		printf("Environment value \"RT28xx_DIR\" not export \n");
	 	return -1;
    }

    if(!chipset) {
		printf("Environment value \"CHIPSET\" not export \n");
		return -1;
    }	    
	
	if (strlen(rt28xxdir) > (sizeof(infname)-100)) {
		printf("Environment value \"RT28xx_DIR\" is too long!\n");
		return -1;
	}
    
	chipset = strtok(chipsets, " ");

	while (chipset != NULL) {
		printf("chipset = %s\n", chipset);
    	memset(infname, 0, 512);
		memset(ine2pname, 0, 512);
    	memset(outfname, 0, 512);
		memset(oute2pname, 0, 512);
		memset(fw_name, 0, 128);
		memset(e2p_name, 0, 128);
		memset(in_rom_patch, 0, 512);
		memset(out_rom_patch, 0, 512);	
		memset(rom_patch_name, 0, 128);
    	strcat(infname,rt28xxdir);
		strcat(ine2pname, rt28xxdir);
		strcat(in_rom_patch, rt28xxdir);
    	strcat(outfname,rt28xxdir);
		strcat(oute2pname, rt28xxdir);
		strcat(out_rom_patch, rt28xxdir);
		is_bin2h_fw = 0;
		is_bin2h_rom_patch = 0;
		is_bin2h_e2p = 0;
		if (strncmp(chipset, "2860",4) == 0) {
			strcat(infname,"/mcu/bin/rt2860.bin");
    		strcat(outfname,"/include/mcu/rt2860_firmware.h");
			strcat(fw_name, "RT2860_FirmwareImage");
			is_bin2h_fw = 1;
		} else if (strncmp(chipset, "2870",4) == 0) {
			if ((strncmp(wow, "y", 1) == 0) && (strncmp(rt28xx_mode, "STA", 3) == 0)) {
	    		strcat(infname,"/mcu/bin/rt2870_wow.bin");
    			strcat(outfname,"/include/mcu/rt2870_wow_firmware.h");
				strcat(fw_name, "RT2870_WOW_FirmwareImage");
				is_bin2h_fw = 1;
			} else {
	    		strcat(infname,"/mcu/bin/rt2870.bin");
    			strcat(outfname,"/include/mcu/rt2870_firmware.h");
				strcat(fw_name, "RT2870_FirmwareImage");
				is_bin2h_fw = 1;
			}
		} else if (strncmp(chipset, "3090",4) == 0) {
	    	strcat(infname,"/mcu/bin/rt2860.bin");
    		strcat(outfname,"/include/mcu/rt2860_firmware.h");
			strcat(fw_name, "RT2860_FirmwareImage");
			is_bin2h_fw = 1;
		} else if (strncmp(chipset, "2070",4) == 0) {
			if ((strncmp(wow, "y", 1) == 0) && (strncmp(rt28xx_mode, "STA", 3) == 0)) {
	    		strcat(infname,"/mcu/bin/rt2870_wow.bin");
    			strcat(outfname,"/include/mcu/rt2870_wow_firmware.h");
				strcat(fw_name, "RT2870_WOW_FirmwareImage");
				is_bin2h_fw = 1;
			} else {
	    		strcat(infname,"/mcu/bin/rt2870.bin");
    			strcat(outfname,"/include/mcu/rt2870_firmware.h");
				strcat(fw_name, "RT2870_FirmwareImage");
				is_bin2h_fw = 1;
			}
		} else if (strncmp(chipset, "3070",4) == 0) {
			if ((strncmp(wow, "y", 1) == 0) && (strncmp(rt28xx_mode, "STA", 3) == 0)) {
	    		strcat(infname,"/mcu/bin/rt2870_wow.bin");
    			strcat(outfname,"/include/mcu/rt2870_wow_firmware.h");
				strcat(fw_name, "RT2870_WOW_FirmwareImage");
				is_bin2h_fw = 1;
			} else {
	    		strcat(infname,"/mcu/bin/rt2870.bin");
    			strcat(outfname,"/include/mcu/rt2870_firmware.h");
				strcat(fw_name, "RT2870_FirmwareImage");
				is_bin2h_fw = 1;
			}
		} else if (strncmp(chipset, "3572",4) == 0) {
			if ((strncmp(wow, "y", 1) == 0) && (strncmp(rt28xx_mode, "STA", 3) == 0)) {
	    		strcat(infname,"/mcu/bin/rt2870_wow.bin");
    			strcat(outfname,"/include/mcu/rt2870_wow_firmware.h");
				strcat(fw_name, "RT2870_WOW_FirmwareImage");
				is_bin2h_fw = 1;
			} else {
	    		strcat(infname,"/mcu/bin/rt2870.bin");
    			strcat(outfname,"/include/mcu/rt2870_firmware.h");
				strcat(fw_name, "RT2870_FirmwareImage");
				is_bin2h_fw = 1;
			}
		} else if (strncmp(chipset, "3573",4) == 0) {
			if ((strncmp(wow, "y", 1) == 0) && (strncmp(rt28xx_mode, "STA", 3) == 0)) {
	    		strcat(infname,"/mcu/bin/rt2870_wow.bin");
    			strcat(outfname,"/include/mcu/rt2870_wow_firmware.h");
				strcat(fw_name, "RT2870_WOW_FirmwareImage");
				is_bin2h_fw = 1;
			} else {
	    		strcat(infname,"/mcu/bin/rt2870.bin");
    			strcat(outfname,"/include/mcu/rt2870_firmware.h");
				strcat(fw_name, "RT2870_FirmwareImage");
				is_bin2h_fw = 1;
			}
		} else if (strncmp(chipset, "3370",4) == 0) {
			if ((strncmp(wow, "y", 1) == 0) && (strncmp(rt28xx_mode, "STA", 3) == 0)) {
	    		strcat(infname,"/mcu/bin/rt2870_wow.bin");
    			strcat(outfname,"/include/mcu/rt2870_wow_firmware.h");
				strcat(fw_name, "RT2870_WOW_FirmwareImage");
				is_bin2h_fw = 1;
			} else {
	    		strcat(infname,"/mcu/bin/rt2870.bin");
    			strcat(outfname,"/include/mcu/rt2870_firmware.h");
				strcat(fw_name, "RT2870_FirmwareImage");
				is_bin2h_fw = 1;
			}
		} else if (strncmp(chipset, "5370",4) == 0) {
			if ((strncmp(wow, "y", 1) == 0) && (strncmp(rt28xx_mode, "STA", 3) == 0)) {
	    		strcat(infname,"/mcu/bin/rt2870_wow.bin");
    			strcat(outfname,"/include/mcu/rt2870_wow_firmware.h");
				strcat(fw_name, "RT2870_WOW_FirmwareImage");
				is_bin2h_fw = 1;
			} else {
	    		strcat(infname,"/mcu/bin/rt2870.bin");
    			strcat(outfname,"/include/mcu/rt2870_firmware.h");
				strcat(fw_name, "RT2870_FirmwareImage");
				is_bin2h_fw = 1;
			}
		} else if (strncmp(chipset, "5572",4) == 0) {
			strcat(infname,"/mcu/bin/rt2870.bin");
    		strcat(outfname,"/include/mcu/rt2870_firmware.h");
			strcat(fw_name, "RT2870_FirmwareImage");
			is_bin2h_fw = 1;
		} else if (strncmp(chipset, "5592",4) == 0) {
			strcat(infname,"/mcu/bin/rt2860.bin");
    		strcat(outfname,"/include/mcu/rt2860_firmware.h");
			strcat(fw_name, "RT2860_FirmwareImage");
			is_bin2h_fw = 1;
		} else if ((strncmp(chipset, "mt7601e", 7) == 0)
				|| (strncmp(chipset, "mt7601u", 7) == 0)) {
			strcat(infname,"/mcu/bin/MT7601_formal_1.6.bin");
			//strcat(infname,"/mcu/bin/MT7601.bin");
			strcat(outfname,"/include/mcu/mt7601_firmware.h");
			strcat(fw_name, "MT7601_FirmwareImage");
			is_bin2h_fw = 1;
			strcat(ine2pname, "/eeprom/MT7601_USB_V0_D-20130416.bin");
			strcat(oute2pname, "/include/eeprom/mt7601_e2p.h");
			strcat(e2p_name, "MT7601_E2PImage");
			is_bin2h_e2p = 1;
		} else if ((strncmp(chipset, "mt7650e", 7) == 0)
				|| (strncmp(chipset, "mt7650u", 7) == 0)
				|| (strncmp(chipset, "mt7630e", 7) == 0)
				|| (strncmp(chipset, "mt7630u", 7) == 0)) {
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr.20121031.modify.USB.flow.bin"); // pmu
			strcat(infname, "/mcu/bin/MT7650.bin"); // pmu
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210302000.bin"); // pmu
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_10292045.bin"); // pmu
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr.for.PMU.print.bin"); // pmu
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_20121029.bin"); // pmu
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210231140.bin"); // atomic bw
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210181030.bin"); // PMU
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210180939.bin"); // PMU
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210151438.bin"); // led
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210171346.bin");
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210151547.bin");
			//strcat(infname, "/mcu/bin/MT7650_1012.bin");
			//strcat(infname,"/mcu/bin/MT7610.bin");
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_201210031435.bin");
			//strcat(infname,"/mcu/bin/MT7610_201210021430.bin"); // turn on debug log same as 10020138.bin
			//strcat(infname,"/mcu/bin/MT7610_201210020138.bin");
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_10021442.bin");
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_1002.bin");
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_shang_1001.bin");
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_Lv5.bin");
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_Lv4.bin");
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_20120919.bin"); // wifi
			//strcat(infname,"/mcu/bin/MT7650E2_V01007870_20120921.bin"); // bt
			//strcat(infname,"/mcu/bin/MT7650.bin");
    		strcat(outfname,"/include/mcu/mt7650_firmware.h");
			strcat(fw_name, "MT7650_FirmwareImage");
			is_bin2h_fw = 1;
		} else if ((strncmp(chipset, "mt7610e", 7) == 0)
				|| (strncmp(chipset, "mt7610u", 7) == 0)) {
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr.20121031.modify.USB.flow.bin"); // pmu
			strcat(infname, "/mcu/bin/MT7650.bin"); // pmu
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr.20121031.modify.USB.flow.bin"); // pmu
			//strcat(infname, "/mcu/bin/MT7650E2_3_4V01008449_20121207.bin"); // pmu
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210302000.bin"); // pmu
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_10292045.bin"); // pmu
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr.for.PMU.print.bin"); // pmu
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_20121029.bin"); // pmu
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210231140.bin"); // atomic bw
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210181030.bin"); // PMU
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210181030.bin"); // PMU
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210180939.bin"); // PMU
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210151438.bin"); // led
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210171346.bin");
			//strcat(infname, "/mcu/bin/MT7650_E2_hdr_201210151547.bin");
			//strcat(infname, "/mcu/bin/MT7650_1012.bin");
			//strcat(infname,"/mcu/bin/MT7610.bin");
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_201210031435.bin");
			//strcat(infname,"/mcu/bin/MT7610_201210021430.bin"); // turn on debug log same as 10020138.bin
			//strcat(infname,"/mcu/bin/MT7610_201210031425.bin"); 
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_10021442.bin");
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_shang_1001.bin");
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_1002.bin");
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_Lv5.bin");
			//strcat(infname,"/mcu/bin/MT7610_201210020138.bin");
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_Lv4.bin");
			//strcat(infname,"/mcu/bin/MT7650_E2_hdr_20120919.bin");
    		strcat(outfname, "/include/mcu/mt7610_firmware.h");
			strcat(fw_name, "MT7610_FirmwareImage");
			is_bin2h_fw = 1;

			if ((strncmp(chipset, "mt7610e", 7) == 0)) {
				strcat(ine2pname, "/eeprom/MT7610U_FEM_V1_1.bin");
				strcat(oute2pname, "/include/eeprom/mt7610e_e2p.h");
				strcat(e2p_name, "MT7610E_E2PImage");
			} else if ((strncmp(chipset, "mt7610u", 7) == 0)) {
				strcat(ine2pname, "/eeprom/MT7610U_FEM_V1_1.bin");
				strcat(oute2pname, "/include/eeprom/mt7610u_e2p.h");
				strcat(e2p_name, "MT7610U_E2PImage");
			}
		} else if ((strncmp(chipset, "mt7662e", 7) == 0)
				|| (strncmp(chipset, "mt7662u", 7) == 0)
				|| (strncmp(chipset, "mt7632e", 7) == 0)
				|| (strncmp(chipset, "mt7632u", 7) == 0) 
				|| (strncmp(chipset, "mt7612e", 7) == 0)
				|| (strncmp(chipset, "mt7612u", 7) == 0)) {
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_2SS.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_1SS.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_debug.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130605_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_RADIO_OFF.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_tssi_average.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_tssi_0618.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_v1.4.bin");
			strcat(infname, "/mcu/bin/mt7662_firmware_e3_v1.8.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_v1.7.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_v1.6_20140905.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_v1.6.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_v1.5.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20140220.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20140213.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_v1.3.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20131211.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20131127.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_v1.1.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20131111.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20130913.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20130904.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20130903.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20130829.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20130826.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20130817.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20130814.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20130813.bin");
			//strcat(infname, "/mcu/bin/mt7662_firmware_e3_20130811.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130729_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130703_b2.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130701_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130624_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130619_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130529_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_COEX_20130528.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_BT_COEX_20130502.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130521_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130520_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130514_tssi_fix.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130514_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130509_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130508_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130507_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130430_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130424.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130423_b2.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130423.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130422.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130419.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130418.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130416.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130415.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130411_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130408_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130402.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130321_b2.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130314_b1.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130313.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130311.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130308.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_latest_0306.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_0306_ram_reset.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_0306.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_0305_new3.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_0305_new.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_2013_03_03.bin");
			//strcat(infname, "/mcu/bin/WIFI_RAM_CODE_ALL_20130304_fpga.bin");
    			strcat(outfname, "/include/mcu/mt7662_firmware.h");
			strcat(fw_name, "MT7662_FirmwareImage");
			strcat(in_rom_patch, "/mcu/bin/mt7662_patch_e3_hdr_v0.0.2_P69.bin");
			//strcat(in_rom_patch, "/mcu/bin/mt7662_patch_e3_hdr_v0.0.2_P48.bin");
			//strcat(in_rom_patch, "/mcu/bin/mt7662_patch_e3_hdr_v0.0.0.1.bin");
			//strcat(in_rom_patch, "/mcu/bin/mt7662_patch_e1_hdr_v0.0.0.9.bin");
			//strcat(in_rom_patch, "/mcu/bin/mt7662_patch_e1_hdr_coex_v0.0.0.2.bin");
			//strcat(in_rom_patch, "/mcu/bin/mt7662_patch_e1_hdr_v0.0.0.8.bin");
			//strcat(in_rom_patch, "/mcu/bin/mt7662_patch_e1_hdr_v0.0.0.7.bin");
			//strcat(in_rom_patch, "/mcu/bin/mt7662_patch_e1_hdr_v0.0.0.6.bin");
			//strcat(in_rom_patch, "/mcu/bin/mt7662_patch_e1_hdr_20130426.bin");
			//strcat(in_rom_patch, "/mcu/bin/mt7662_patch_e1_hdr_v0.0.0.5.bin");
			//strcat(in_rom_patch, "/mcu/bin/mt7612_patch_e1_hdr_0417.bin");
			//strcat(in_rom_patch, "/mcu/bin/mt7662_patch_e1_hdr_v0.0.0.3.bin");
			strcat(out_rom_patch, "/include/mcu/mt7662_rom_patch.h");
			strcat(rom_patch_name, "mt7662_rom_patch");
			strcat(ine2pname, "/eeprom/MT7612E_EEPROM_layout_20131121_2G5G_ePAeLNA_TXTC_off.bin");
			//strcat(ine2pname, "/eeprom/MT7612E3_EEPROM_layout_20131022_2G5G_iPAiLNA_wTSSI_default_slope_offset.bin");
			strcat(oute2pname, "/include/eeprom/mt76x2_e2p.h");
			strcat(e2p_name, "MT76x2_E2PImage");
			is_bin2h_fw = 1;
			is_bin2h_rom_patch = 1;
			is_bin2h_e2p = 1;
		} else {
			printf("unknown chipset = %s\n", chipset);
		}

		if (is_bin2h_fw)
     		bin2h(infname, outfname, fw_name);

		if (is_bin2h_rom_patch)
			bin2h(in_rom_patch, out_rom_patch, rom_patch_name);

		if (is_bin2h_e2p)
			bin2h(ine2pname, oute2pname, e2p_name);

		chipset = strtok(NULL, " ");
	}

    exit(0);
}	
Example #17
0
int main(void)
{
		int sockfd;
		struct addrinfo hints, *clientinfo, *p, *serverinfo;
		char *pch;
		int count;
		int rv;
		void *addr;
		void *port;
		int i;
		int numbytes;
		FILE *ptr_file;
		char filebuffer[MAXBUFLEN];
		char pwd[MAXBUFLEN];
		char peername[MAXBUFLEN];
		char ipstr[INET6_ADDRSTRLEN];
		char s[INET6_ADDRSTRLEN];
		char buf[MAXBUFLEN];
		struct sockaddr_storage their_addr;
		socklen_t addr_len;
		struct sockaddr_in myaddr;         
		int len; 
		char data[MAXBUFLEN];
		char port_no[MAXBUFLEN];
		int port_no_int;
	
		
		memset(&hints, 0, sizeof hints);
		hints.ai_family = AF_INET;
		hints.ai_socktype = SOCK_DGRAM;
		
		// Getting the address details of the peer
		if ((rv = getaddrinfo("localhost",NULL, &hints, &clientinfo)) != 0) 
		{
			fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
			return 1;
		}
		
		for(p = clientinfo; p != NULL; p = p->ai_next) 
		{
			if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1) 
			{
				perror("Failed to get a socket");
				continue;
			}
			break;
		}
		if (p == NULL) 
		{
				fprintf(stderr, "Failed to bind socket");
				return 2;
		}
			struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
			addr = &(ipv4->sin_addr);
			inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
			
		
		if (bind(sockfd, (struct sockaddr *) &myaddr, sizeof(myaddr)) < 0) 
		{
				perror("bind failed");
				exit(1);
		}
		len = sizeof(myaddr);
		if (getsockname(sockfd, (struct sockaddr *)&myaddr, &len) < 0) 
		{
				perror("Error getting socketname \n");
				exit(1);
		}
		// Getting the dynamic port number of the port of the peer
		port_no_int =ntohs(myaddr.sin_port);
		sprintf(port_no, "%d",port_no_int);
		
		// Getting the address details of the server
		printf("Peer 3 Phase 1: The dynamic UDP port number:%d and IP address:%s \n",ntohs(myaddr.sin_port),ipstr);
		if ((rv = getaddrinfo("localhost",SERVERPORT, &hints, &serverinfo)) != 0) 
		{
			fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
			return 1;
		}
		
		for(p = serverinfo; p != NULL; p = p->ai_next) 
		{
			if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1) 
			{
				perror("Failed to get a socket");
				continue;
			}
			break;
		}
		if (p == NULL) 
		{
				fprintf(stderr, "Failed to bind socket");
				return 2;
		}
			
		// Reading the file and copying over the required details for authentication message
		
		ptr_file = fopen("peer_3.txt", "r");
		if (!ptr_file) return 1;
		memset(filebuffer, 0, sizeof filebuffer);
		memset(peername, 0, sizeof peername);
		fgets(filebuffer,1000,ptr_file);
		pch = strtok(filebuffer," ");
		count=0;
			while(pch != NULL)
			{
				
				if(strcmp(pch,"m") != 0)
				{
					if(strcmp(pch,"w") != 0)
					{
					if(count != 0)
					strcat(peername," ");
					strcat(peername,pch);
					}
					
				}
				pch = strtok(NULL," ");
				count++;
				
			
			}
		
			printf("%s Phase 1: Sending the authentication information to the server <%s>\n",strtok(filebuffer," "),peername);
			
			// Sending and receiving the authentication information and result
			if (sendto(sockfd,peername, sizeof peername,0,p->ai_addr, p->ai_addrlen) == -1) 
			{
				perror(" Unable to send the data\n");
				exit(1);
			}
			addr_len = sizeof their_addr;
			if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,(struct sockaddr *)&their_addr, &addr_len)) == -1) 
			{
					perror("Unable to receive data \n");
					exit(1);
			}
			buf[numbytes] = '\0';
			if(strcmp(buf,"ACK") == 0)
			{
				printf("%s Phase 1: Authentication successful\n", strtok(filebuffer," "));
				memset(filebuffer, 0, sizeof filebuffer);
				memset(data, 0, sizeof data);
				ptr_file = fopen("peer_3.txt", "r");
				if (!ptr_file) return 1;
				fgets(filebuffer,1000,ptr_file);
				strcpy(pwd,filebuffer);
				//printf("The contents on file buffer is %s\n", filebuffer);
				// Constructing the token by parsing through each element of the string
				strcat(data, strtok(filebuffer," "));
					strcat(data," ");
					strcat(data,ipstr);
					strcat(data," ");
					strcat(data,PEER_3_PORT);
					strcat(data," ");
					//printf("The contents on file buffer 1 is %s\n", filebuffer);
					fgets(filebuffer,1000,ptr_file);
					//printf("The contents on file buffer 2 is %s\n", pwd);
					if(strstr(pwd,"m") != NULL)
						{
							strcat(data,"Mac");
						}
						else 
						{
							strcat(data,"Windows");
						}
					printf("%s Phase 1: Sending the file transfer information to the server %s\n",strtok(filebuffer," "),data);
				
					if (sendto(sockfd,data, sizeof data,0,p->ai_addr, p->ai_addrlen) == -1) 
					{
						perror("talker: sendto");
						exit(1);
					}
					if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,(struct sockaddr *)&their_addr, &addr_len)) == -1) 
					{
					perror("recvfrom");
					exit(1);
					}
					printf(" %s Phase 1: Information received by the server\n", strtok(filebuffer," "));
			//printf("listener: got packet from %s\n",inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr *)&their_addr),s, sizeof s));
			//printf("listener: packet is %d bytes long\n", numbytes);
			buf[numbytes] = '\0';
			//printf("listener: packet contains \"%s\"\n", buf);
			freeaddrinfo(clientinfo);
				close(sockfd);
				//return 0;
				
			}
			// If we get a NAK, client will tear down the connection
			else if(strcmp(buf,"NAK") == 0)
			{
				printf("%s Phase 1: Authentication unsuccessful\n", peername);
				freeaddrinfo(clientinfo);
				close(sockfd);
				//return 0;
				
			}
			printf("%s Phase 1: End of Phase 1\n",strtok(filebuffer," "));
			printf("%s Phase 3: The %s has static TCP port number %s and IP address %s\n",strtok(filebuffer," "),strtok(filebuffer," "),PEER_3_PORT,ipstr);
			int new_fd;			
			struct addrinfo *servinfo;
			int yes = 1;
			struct sigaction sa;
			socklen_t sin_size;
			char *peer;
			char *ip;
			char *port_msg;
			char *sender;
			char temp[MAXBUFLEN];
			char message[MAXBUFLEN];
			char buf1[MAXBUFLEN];
			char *machine_type;
			int count_token = 0;
			

			memset(&hints, 0, sizeof hints);
			memset(message, 0, sizeof message);
			memset(temp, 0, sizeof temp);
			hints.ai_family = AF_INET;
			hints.ai_socktype = SOCK_STREAM;
			hints.ai_flags = AI_PASSIVE; 		
		
		if ((rv = getaddrinfo("localhost",PEER_3_PORT, &hints, &servinfo)) != 0) 
		{
			fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
			return 1;
		}
		for(p = servinfo; p != NULL; p = p->ai_next)
	       	{
			if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1) 
			{
					perror("server: socket");
					continue;
			}
			if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(int)) == -1) 
			{
				perror("setsockopt");
				exit(1);
			}
			if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) 
			{
				close(sockfd);
				perror("server: bind");
				continue;
			}
			break;
		}
		if (p == NULL)  
		{
			fprintf(stderr, "server: failed to bind\n");
			return 2;
		}
		
		if (listen(sockfd, BACKLOG) == -1) {
		perror("listen");
		exit(1);
		}

		sa.sa_handler = sigchld_handler; 
		sigemptyset(&sa.sa_mask);
		sa.sa_flags = SA_RESTART;
		if (sigaction(SIGCHLD, &sa, NULL) == -1) 
		{
			perror("sigaction");
			exit(1);
		}
		//printf("peer 2: waiting for connections...\n");
		sin_size = sizeof their_addr;
		new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
		if (new_fd == -1) 
		{
			perror("accept");
			
		}

		inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr *)&their_addr),s, sizeof s);
		//printf("peer 2: got connection from %s\n", s);
		if (!fork()) 
		{ 
			close(sockfd); 
			if ((numbytes = recv(new_fd, buf, MAXDATASIZE-1, 0)) == -1) 
			{
		    		perror("recv");
		    		exit(1);
			}
			buf[numbytes] = '\0';
			strcpy(temp,buf);
			sender = strtok(buf," ");
			peer = strtok(NULL," ");
			ip = strtok(NULL," ");
			port_msg = strtok(NULL," ");
			machine_type = strtok(NULL, " ");
			printf("%s Phase 3: Received the file from %s \n",strtok(filebuffer," "),sender); 
			//printf("The peer:%s and IP: %s and port: %s\n", peer,ip,port_msg);
			//printf("Temp contents are: '%s'\n",temp);
			//printf("Buf contents are: '%s'\n",buf);
			strcpy(buf1,temp);
			strcat(message,"peer3");
			strcat(message," ");
			pch = strtok(buf1," ");
			while(pch != NULL)
			{
				//printf( "The token is : %s\n",pch);
				count_token++;
				if(count_token > 5)
				{
					//printf( "Inside the loop token is : %s\n",pch);
					strcat(message,pch);
					strcat(message," ");
					
				}
    			        pch = strtok(NULL," ");
			}
			//printf("The counter is %d\n", count_token);
			//printf("The message is %s\n", message);
			close(new_fd);
			//printf("%s Phase 3: The contents of the file are as follows : %s \n",strtok(filebuffer," "), temp);
			if(count_token >= 5)
			{
				printf("%s Phase 3: The contents of the file are as follows : %s \n",strtok(filebuffer," "), temp);
			}
			else
			{
				printf("%s Phase 3: There are no more contents in the file\n",strtok(filebuffer," "));
			}
		if(count_token >= 5)
		{
		
			if ((rv = getaddrinfo("localhost",NULL, &hints, &servinfo)) != 0) 
			{
				fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
				return 1;
			}
			for(p = servinfo; p != NULL; p = p->ai_next) 
			{
				if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1) 
			{
				perror("Failed to get a socket");
				continue;
			}
			break;
			}
			if (p == NULL) 
			{
				fprintf(stderr, "Failed to bind socket");
				return 2;
			}
					
			len = sizeof(myaddr);
			myaddr.sin_family = AF_INET;
			myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
			myaddr.sin_port = 0;
			bind(sockfd,(struct sockaddr *)&myaddr,len);
		
			if (getsockname(sockfd, (struct sockaddr *)&myaddr, &len) < 0) 
			{
				perror("Error getting socketname \n");
				exit(1);
			}
				printf("%s Phase 3: The peer has dynamic TCP port number:%d and IP address:%s\n",strtok(filebuffer," "),ntohs(myaddr.sin_port),ipstr);
		memset(&hints, 0, sizeof hints);
		hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_STREAM;
		if ((rv = getaddrinfo(ip,port_msg, &hints, &servinfo)) != 0) 
		{
				fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
				return 1;
		}
		for(p = servinfo; p != NULL; p = p->ai_next) 
		{
			if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1) 
			{
				perror("client: socket");
				continue;
			}

			if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) 
			{
				close(sockfd);
				perror("client: connect");
				continue;
			}

			break;
		}

		if (p == NULL) 
		{
			fprintf(stderr, "client: failed to connect\n");
			return 2;
		}
		inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),s, sizeof s);
		//printf("peer_2: connecting to %s\n", s);
		freeaddrinfo(servinfo);
	printf("%s Phase 3: Sending file to %s having IP address %s and static TCP port number %s\n",strtok(filebuffer," "),peer,ip,port_msg);
		if (send(sockfd, message, sizeof message, 0) == -1)
		{
			perror("Send Error");
		}
	}	
			printf("%s Phase 3: File Transfer successful\n",strtok(filebuffer," "));
			printf("%s Phase 3: End of Phase 3\n",strtok(filebuffer," "));
			close(new_fd);
			exit(0);
		}
		close(new_fd);  
		return 0;
			
			
}
Example #18
0
/***********************************************************************************************
MISS �϶� �����Ǵ� �Լ��μ� ������ response(header, data)�� �о��ͼ� ������������ �����ϰ� �ٽ� cache
�� �����ϴ� ���� �Ѵ�.
************************************************************************************************/
void  connect_web_srv( char *buf, char *whole_dir )
{
   int qfile, write_n, read_n, a, b; 
   char domain_name[DNSIZE], response[BUFFSIZE];
   char ws_request[BUFFSIZE];

   struct hostent *hp; /*�������� �ּҸ� ���������� �ޱ����� �ּ� ����ü.*/
   struct sockaddr_in web_serv;

   bzero(response, sizeof(response));      
   bzero(domain_name, sizeof(domain_name));
   bzero(ws_request, sizeof(ws_request));

   /****** socket()  **************************************************************************/
   if( (connect_sd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) 
   {
      perror("Cannot open stream socket.");
      exit(1);
   }
   
   /*domain name���� parsing*/
   for(a=0;a<DNSIZE;a++)
   {                        
      if( buf[a] == '/' )
      {
         for(b=0;b<DNSIZE-a;b++)
         {
            if( buf[a+b+2] == '/' )
               break;
            domain_name[b] = buf[a+b+2]; 
         }
         break;                                 
      }
   }
  
   /* �������� �ּҿ� ���� ������ �޴´�.*/
   if( (hp = gethostbyname(domain_name)) == NULL )             
   {
      errpage(domain_name);               /*�߰� ���� �Լ�*/       
      access_local_cache("./error.html"); /*      "      */
      exit(1);  
   }

   bzero( (char*) &web_serv, sizeof(web_serv) );

   web_serv.sin_addr = *( (struct in_addr*)hp->h_addr_list[0] );                               
   web_serv.sin_family = AF_INET;                                                      
   web_serv.sin_port   = htons(WEBPORT); 
            
   /******  connect()  ************************************************************************/                                                                                             
   if( connect(connect_sd, (struct sockaddr*)&web_serv, sizeof(web_serv)) < 0)         
   { 
      perror("Connect error.");
      exit(1);
   } 
           
   /* �������� Moved���� ������ ������ �� response�� �޾ƿ� �� ���� �DZ⶧���� request header
   �� �ٽ� �Ľ��ϴ� �Լ��̴�.*/        
   get_ws_request(buf, ws_request);

   /* cache�� �������κ��� �޾ƿ� ����Ÿ�� ������ ������ ���� open() */
   qfile = open( whole_dir, O_WRONLY | O_CREAT, 0666 );  
   
   write(connect_sd, ws_request, BUFFSIZE ); /* �������� request header ����.*/
 
   do{                                                                   
      alarm(TIMEOUT);                                                   
      while( (read_n = read(connect_sd, response, MAXLINE )) > 0 )       
      {                                                                 
          do{                                                            
             write_n = write(accept_sd, response, read_n);/*Ŭ���̾�Ʈ�� ����Ÿ ����.*/  
             write( qfile, response, read_n );            /*cache�� ����Ÿ ����.    */
             bzero(response, sizeof(response)); 
          }while( write_n == -1 && errno == EINTR);                                                                                                    
      }                                                                 
   }while( read_n == -1 && errno == EINTR );                            

   close(qfile);       
   close(accept_sd);       /* ���� ����ũ����, ���ϵ���ũ���͸� ���� �ݴ´�. ���� ����.*/              
   close(connect_sd);

   printf("MISS : [ip:%s] ", inet_ntoa(web_serv.sin_addr));
   printf("%s\n", strtok(buf, "\n"));

}
/*****************************************************************************
*
* Handle one single socket connection request.
*
* RETURNS:
*	0			Bad request;
*	100
*	101
*	110
*	111
*	120
*	121
*
*****************************************************************************/
static int handleTransaction(int sock)
{
	FILE	*fsock;

	char	buf[2048];
	char	cmd[2048];
	int		status = 1;
	char	*method;
	char	*url;
	char	*lasts;
	char	*ret;

	/* Create a stream for reading AND writing */
    if ((fsock = fdopen(sock, "r+b")) == NULL)
    {
        perror("fdopen");
        return(0);
    }

	/* Read the request phase request line */
	ret = fgets(cmd, sizeof(cmd), fsock);
	if (ret != NULL)
	{	/* Got the command line of the request... grab the good stuff */

		method = strtok(cmd, " ");
		url = strtok(NULL, " ");

		if (method==NULL || url==NULL)
		{
			debug("handleTransaction() got bogus request line\n");
			fclose(fsock);
			return(0);
		}
		debug("method: '%s', url: '%s'\n", method, url);
	}

	/* Read rest of the request phase header lines and toss them */
	ret = fgets(buf, sizeof(buf), fsock);
	while (ret!=NULL && buf[0]!='\r' && buf[0]!='\n')
	{
		/*debug("Got input data line: '%s'\n", buf);*/
		ret = fgets(buf, sizeof(buf), fsock);
	}

	/* This is strange at best... is Solaris hosed? */
	fseek(fsock, 0L, SEEK_END);	

	if (!strcmp(method, "HEAD"))
	{
		if ((status = reqHead(fsock, url)) == 0)
			status = 100;
		else
			status = 101;
	}
	else if (!strcmp(method, "GET"))
	{
		if ((status = reqGet(fsock, url)) == 0)
			status = 110;
		else
			status = 111;
	}
	else
	{
		if ((status = reqBogus(fsock, url)) == 0)
			status = 120;
		else
			status = 121;
	}

	fflush(fsock);	/* force the stream to write any buffered data */
	fclose(fsock);	/* closes the stream AND the file descriptor(socket) */
	return(status);
}
Example #20
0
/*
 * This function takes a pointer to a struct batch_status for a job, and
 * fills in the appropriate fields of the supplied job struct.  It returns
 * the number of items that were found.
 */
int
schd_get_jobinfo(Batch_Status *bs, Job *job)
  {
  char *id = "schd_get_jobinfo";
  int     changed = 0;
  int     cpu_req = 0;
  size_t  mem_req = 0;
  char     *host;
  char *p, *tmp_p, *var_p;
  AttrList *attr;
  char      canon[PBS_MAXHOSTNAME + 1];
  int     istrue;

  memset((void *)job, 0, sizeof(Job));

  job->jobid = schd_strdup(bs->name);

  if (job->jobid == NULL)
    {
    log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id,
               "schd_strdup(bs->name)");
    return (-1);
    }

  changed ++;

  for (attr = bs->attribs; attr != NULL; attr = attr->next)
    {

    /*
     * If this is the 'owner' field, chop it into 'owner' and 'host'
     * fields, and copy them into the Job struct.
     */
    if (!strcmp(attr->name, ATTR_owner))
      {

      /* Look for the '@' that separates user and hostname. */
      host = strchr(attr->value, '@');

      if (host)
        {
        *host = '\0'; /* Replace '@' with NULL (ends username). */
        host ++; /* Move to first character of hostname. */
        }

      job->owner = schd_strdup(attr->value);

      if (job->owner == NULL)
        {
        log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id,
                   "schd_strdup(job->owner)");
        return (-1);
        }

      changed ++;

      job->host  = schd_strdup(host);

      if (job->host == NULL)
        {
        log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id,
                   "schd_strdup(job->host)");
        return (-1);
        }

      changed ++;

      /*
       * We don't "own" the attribute strings, so put back the '@'
       * character we removed above, in case something else expects
       * it to be there.
       * Note that 'host' points to the first character of the host-
       * name, not the hole one character behind.
       */

      if (host)
        {
        host --; /* Step back one character. */
        *host = '@'; /* Replace the '@' that was deleted above. */
        }

      /* That's all for the owner field. */
      continue;
      }

    /* The group to which to charge the resources for this job. */
    if (!strcmp(attr->name, ATTR_egroup))
      {
      job->group = schd_strdup(attr->value);

      if (job->group == NULL)
        {
        log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id,
                   "schd_strdup(job->group)");
        return (-1);
        }

      changed ++;

      continue;
      }

    /* The comment currently assigned to this job. */
    if (!strcmp(attr->name, ATTR_comment))
      {
      job->comment = schd_strdup(attr->value);

      if (job->comment == NULL)
        {
        log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id,
                   "schd_strdup(job->comment)");
        return (-1);
        }

      changed ++;

      continue;
      }

    /* The host on which this job is running. */
    if (!strcmp(attr->name, ATTR_exechost))
      {
      job->exechost = schd_strdup(attr->value);

      if (job->exechost == NULL)
        {
        log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id,
                   "schd_strdup(job->exechost)");
        return (-1);
        }

      changed ++;

      continue;
      }

    if (!strcmp(attr->name, ATTR_inter))
      {
      /* Is this job interactive or not? */
      if (schd_val2bool(attr->value, &istrue) == 0)
        {
        if (istrue)
          job->flags |= JFLAGS_INTERACTIVE;
        else
          job->flags &= ~JFLAGS_INTERACTIVE;

        changed ++;
        }
      else
        {
        DBPRT(("%s: can't parse %s = %s into boolean\n", id,
               attr->name, attr->value));
        }

      continue;
      }

    if (!strcmp(attr->name, ATTR_state))
      {
      /* State is one of 'R', 'Q', 'E', etc. */
      job->state = attr->value[0];
      changed ++;

      continue;
      }

    if (!strcmp(attr->name, ATTR_queue))
      {
      job->qname = schd_strdup(attr->value);

      if (job->qname == NULL)
        {
        log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id,
                   "schd_strdup(job->qname)");
        return (-1);
        }

      job->flags |= JFLAGS_QNAME_LOCAL;

      changed ++;

      continue;
      }

    if (!strcmp(attr->name, ATTR_v))
      {
      var_p = schd_strdup(attr->value);

      if (var_p == NULL)
        {
        log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id,
                   "schd_strdup(Variable_List)");
        return (-1);
        }

      p = NULL;

      tmp_p = strstr(var_p, "PBS_O_QUEUE");

      if (tmp_p)
        {
        p = strtok(tmp_p, "=");
        p = strtok(NULL,  ", ");
        }

      if (p != NULL)
        {
        job->oqueue = schd_strdup(p);
        }
      else
        {
        /* if the originating queue is unknown, default
         * to the locally defined "submit" queue.
         */
        job->oqueue = schd_strdup(schd_SubmitQueue->queue->qname);
        }

      free(var_p);

      changed ++;
      continue;
      }

    if (!strcmp(attr->name, ATTR_l))
      {
      if (!strcmp(attr->resource, "walltime"))
        {
        job->walltime = schd_val2sec(attr->value);
        changed ++;

        }
      else if (!strcmp(attr->resource, "ncpus"))
        {
        cpu_req = atoi(attr->value);
        job->nodes = MAX(job->nodes, NODES_FROM_CPU(cpu_req));
        changed ++;

        }
      else if (!strcmp(attr->resource, "mem"))
        {
        mem_req = schd_val2byte(attr->value);
        job->nodes = MAX(job->nodes, NODES_FROM_MEM(mem_req));
        changed ++;

#ifdef NODEMASK
        }
      else if (!strcmp(attr->resource, "nodemask"))
        {
        if (schd_str2mask(attr->value, &job->nodemask))
          {
          (void)sprintf(log_buffer,
                        "bad nodemask %s for job %s", attr->value, job->jobid);
          log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id,
                     log_buffer);
          }
        else
          changed++; /* Job nodemask was valid. */

#endif /* NODEMASK */

        }

      if (!strcmp(attr->resource, HPM_ATTRIBUTE))
        {
        /*
         * If the job requests hpm support, set the flag, otherwise
         * turn it off.
         */
        if (schd_val2bool(attr->value, &istrue) == 0)
          {
          if (istrue)
            job->flags |= JFLAGS_NEEDS_HPM;
          else
            job->flags &= ~JFLAGS_NEEDS_HPM;

          changed ++;
          }
        else
          {
          DBPRT(("%s: can't parse %s = %s into boolean\n", id,
                 attr->name, attr->value));
          }
        }

      /* That's all for requested resources. */
      continue;
      }

    if (!strcmp(attr->name, ATTR_used))
      {
      if (!strcmp(attr->resource, "walltime"))
        {
        job->walltime_used = schd_val2sec(attr->value);

        changed ++;
        }

      /* No other interesting cases. */
      continue;
      }

    /* Creation time attribute. */
    if (!strcmp(attr->name, ATTR_ctime))
      {
      /* How long ago was it put in the queue ? */
      job->time_queued = schd_TimeNow - atoi(attr->value);

      continue;
      }

    /* Modified time attribute. */
    if (!strcmp(attr->name, ATTR_mtime))
      {
      /* When was the job last modified? */
      job->mtime = atoi(attr->value);

      continue;
      }

#ifdef ATTR_etime
    /*
     * When was the job last eligible to run?  When a user-hold is
     * released, this value is updated to the current time.  This
     * prevents users from gaining higher priority from holding their
     * jobs.
     */
    if (!strcmp(attr->name, ATTR_etime))
      {
      job->eligible = schd_TimeNow - atoi(attr->value);

      continue;
      }

#endif /* ATTR_etime */
    }

  /*
   * If this job is in the "Running" state, compute how many seconds
   * remain until it is completed.
   */
  if (job->state == 'R')
    {
    job->time_left = job->walltime - job->walltime_used;
    }

  /*
   * If this job was enqueued since the last time we ran, set the job
   * flag to indicate that we have not yet seen this job.  This makes it
   * a candidate for additional processing.  There may be some inaccuracy,
   * since the time_t has resolution of 1 second.  Attempt to err on the
   * side of caution.
   */
  if ((job->state == 'Q') && (job->time_queued != UNSPECIFIED))
    {
    if (job->time_queued <= (schd_TimeNow - schd_TimeLast))
      {
      job->flags |= JFLAGS_FIRST_SEEN;
      }
    }

  /*
   * If the 'etime' attribute wasn't found, set it to the time the job has
   * been queued.  Most jobs will be eligible to run their entire lifetime.
   * The exception is a job that has been held - if it was a user hold,
   * the release will reset the etime to the latest value.
   * If not eligible time was given, use the job's creation time.
   */
  if (!job->eligible)
    job->eligible = job->time_queued;

  /*
   * If the job provided a memory or CPU resource that does not match
   * the resources that will be allocated by the assigned nodes (i.e.
   * a request for 100mb of memory and 16 CPUs - the job will "get" all
   * 4GB of memory anyway), alter the job attributes such that they
   * will align with the assigned nodes later.
   */
  bump_rsrc_requests(job, cpu_req, mem_req);

  return (changed);
  }
Example #21
0
//NILS
struct gameXMLinfo LoadGameInfo(char* gameid)
/* gameid: full game id */
/* langtxt: "English","French","German" */
{
    // load game info using forced language, or game individual setting, or main language setting
    char langcode[100] = "";
    char *langtxt = GetLangSettingFromGame(gameid);
    strlcpy(langcode,ConvertLangTextToCode(langtxt),sizeof(langcode));

    /* reset all game info */
    gameinfo = gameinfo_reset;

    /* index all IDs */
    nodeindex = mxmlIndexNew(nodedata,"id", NULL);
    nodeid = mxmlIndexReset(nodeindex);
    *element_text = 0;
    /* search for game matching gameid */
    while (1) {
        nodeid = mxmlIndexFind(nodeindex,"id", NULL);
        if (nodeid != NULL) {
            get_nodetext(nodeid, element_text, sizeof(element_text));
            if (!strcmp(element_text,gameid)) {
                break;
            }
        } else {
            break;
        }
    }

    if (!strcmp(element_text,gameid)) {
        /* text from elements */
        strlcpy(gameinfo.id,element_text,sizeof(gameinfo.id));
        GetTextFromNode(nodeid, nodedata, "region", NULL, NULL, MXML_NO_DESCEND, gameinfo.region,sizeof(gameinfo.region));
        GetTextFromNode(nodeid, nodedata, "version", NULL, NULL, MXML_NO_DESCEND, gameinfo.version,sizeof(gameinfo.version));
        GetTextFromNode(nodeid, nodedata, "genre", NULL, NULL, MXML_NO_DESCEND, gameinfo.genre,sizeof(gameinfo.genre));
        GetTextFromNode(nodeid, nodedata, "developer", NULL, NULL, MXML_NO_DESCEND, gameinfo.developer,sizeof(gameinfo.developer));
        GetTextFromNode(nodeid, nodedata, "publisher", NULL, NULL, MXML_NO_DESCEND, gameinfo.publisher,sizeof(gameinfo.publisher));
        GetPublisherFromGameid(gameid,gameinfo.publisherfromid,sizeof(gameinfo.publisherfromid));

        GetTextFromNode(nodeid, nodedata, "input", "players", NULL, MXML_NO_DESCEND, gameinfo.max_players,sizeof(gameinfo.max_players));
		
        /* text from attributes */
        GetTextFromNode(nodeid, nodedata, "date", "year", NULL, MXML_NO_DESCEND, gameinfo.year,sizeof(gameinfo.year));
        GetTextFromNode(nodeid, nodedata, "date", "month", NULL,MXML_NO_DESCEND, gameinfo.month,sizeof(gameinfo.month));
        GetTextFromNode(nodeid, nodedata, "date", "day", NULL, MXML_NO_DESCEND, gameinfo.day,sizeof(gameinfo.day));
        GetTextFromNode(nodeid, nodedata, "rating", "type", NULL, MXML_NO_DESCEND, gameinfo.ratingtype,sizeof(gameinfo.ratingtype));
        GetTextFromNode(nodeid, nodedata, "rating", "value", NULL, MXML_NO_DESCEND, gameinfo.ratingvalue,sizeof(gameinfo.ratingvalue));
        GetTextFromNode(nodeid, nodedata, "rom", "crc", NULL, MXML_NO_DESCEND, gameinfo.iso_crc,sizeof(gameinfo.iso_crc));
        GetTextFromNode(nodeid, nodedata, "rom", "md5", NULL, MXML_NO_DESCEND, gameinfo.iso_md5,sizeof(gameinfo.iso_md5));
        GetTextFromNode(nodeid, nodedata, "rom", "sha1", NULL, MXML_NO_DESCEND, gameinfo.iso_sha1,sizeof(gameinfo.iso_sha1));

        /* text from child elements */
        nodefound = mxmlFindElement(nodeid, nodedata, "locale", "lang", "EN", MXML_NO_DESCEND);
        if (nodefound != NULL) {
            GetTextFromNode(nodefound, nodedata, "title", NULL, NULL, MXML_DESCEND, gameinfo.title_EN,sizeof(gameinfo.title_EN));
            GetTextFromNode(nodefound, nodedata, "synopsis", NULL, NULL, MXML_DESCEND, gameinfo.synopsis_EN,sizeof(gameinfo.synopsis_EN));
        }
        nodefound = mxmlFindElement(nodeid, nodedata, "locale", "lang", langcode, MXML_NO_DESCEND);
        if (nodefound != NULL) {
            GetTextFromNode(nodefound, nodedata, "title", NULL, NULL, MXML_DESCEND, gameinfo.title,sizeof(gameinfo.title));
            GetTextFromNode(nodefound, nodedata, "synopsis", NULL, NULL, MXML_DESCEND, gameinfo.synopsis,sizeof(gameinfo.synopsis));
        }
        // fall back to English title and synopsis if prefered language was not found
        if (!strcmp(gameinfo.title,"")) {
            strlcpy(gameinfo.title,gameinfo.title_EN,sizeof(gameinfo.title));
        }
        if (!strcmp(gameinfo.synopsis,"")) {
            strlcpy(gameinfo.synopsis,gameinfo.synopsis_EN,sizeof(gameinfo.synopsis));
        }

        /* list locale lang attributes */
        nodefound = mxmlFindElement(nodeid, nodedata, "locale", "lang", NULL, MXML_NO_DESCEND);
        if (nodefound != NULL) {
            int incr = 0;
            while (nodefound != NULL) {
                ++incr;
                strlcpy(gameinfo.locales[incr],mxmlElementGetAttr(nodefound, "lang"),sizeof(gameinfo.locales[incr]));
                nodefound = mxmlWalkNext(nodefound, nodedata, MXML_NO_DESCEND);
                if (nodefound != NULL) {
                    nodefound = mxmlFindElement(nodefound, nodedata, "locale", "lang", NULL, MXML_NO_DESCEND);
                }
            }
        }

        /* unbounded child elements */
        GetTextFromNode(nodeid, nodedata, "wi-fi", "players", NULL, MXML_NO_DESCEND, gameinfo.wifiplayers,sizeof(gameinfo.wifiplayers));
        nodefound = mxmlFindElement(nodeid, nodedata, "wi-fi", NULL, NULL, MXML_NO_DESCEND);
        if (nodefound != NULL) {
            gameinfo.wifiCnt = 0;
            nodeindextmp = mxmlIndexNew(nodefound,"feature", NULL);
            nodeidtmp = mxmlIndexReset(nodeindextmp);
            while (nodeidtmp != NULL) {
                nodeidtmp = mxmlIndexFind(nodeindextmp,"feature", NULL);
                if (nodeidtmp != NULL) {
                    ++gameinfo.wifiCnt;
                    GetTextFromNode(nodeidtmp, nodedata, "feature", NULL, NULL, MXML_DESCEND, gameinfo.wififeatures[gameinfo.wifiCnt],
                                    sizeof(gameinfo.wififeatures[gameinfo.wifiCnt]));
                    gameinfo.wififeatures[gameinfo.wifiCnt][0] = toupper((int)gameinfo.wififeatures[gameinfo.wifiCnt][0]);
                    if (gameinfo.wifiCnt == XML_ELEMMAX)
                        break;
                }
            }
            mxmlIndexDelete(nodeindextmp); // placed after each mxmlIndexNew to prevent memory leak
        }

        nodefound = mxmlFindElement(nodeid, nodedata, "rating", NULL, NULL, MXML_NO_DESCEND);
        if (nodefound != NULL) {
            gameinfo.descriptorCnt=0;
            nodeindextmp = mxmlIndexNew(nodefound,"descriptor", NULL);
            nodeidtmp = mxmlIndexReset(nodeindextmp);
            while (nodeidtmp != NULL) {
                nodeidtmp = mxmlIndexFind(nodeindextmp,"descriptor", NULL);
                if (nodeidtmp != NULL) {
                    ++gameinfo.descriptorCnt;
                    GetTextFromNode(nodeidtmp, nodedata, "descriptor", NULL, NULL, MXML_DESCEND,
                                    gameinfo.ratingdescriptors[gameinfo.descriptorCnt], sizeof(gameinfo.ratingdescriptors[gameinfo.descriptorCnt]));
                    if (gameinfo.descriptorCnt == XML_ELEMMAX)
                        break;
                }
            }
            mxmlIndexDelete(nodeindextmp);
        }

        GetTextFromNode(nodeid, nodedata, "input", "players", NULL, MXML_NO_DESCEND, gameinfo.players,sizeof(gameinfo.players));
        nodefound = mxmlFindElement(nodeid, nodedata, "input", NULL, NULL, MXML_NO_DESCEND);
        if (nodefound != NULL) {
            gameinfo.accessoryCnt=0;
            gameinfo.accessoryReqCnt=0;
            nodeindextmp = mxmlIndexNew(nodefound,"control", NULL);
            nodeidtmp = mxmlIndexReset(nodeindextmp);
            while (nodeidtmp != NULL) {
                nodeidtmp = mxmlIndexFind(nodeindextmp,"control", NULL);
                if (nodeidtmp != NULL) {
                    if (!strcmp(mxmlElementGetAttr(nodeidtmp, "required"),"true")  && gameinfo.accessoryReqCnt < XML_ELEMMAX)	{
                        ++gameinfo.accessoryReqCnt;
                        strlcpy(gameinfo.accessoriesReq[gameinfo.accessoryReqCnt],mxmlElementGetAttr(nodeidtmp, "type"),
                                sizeof(gameinfo.accessoriesReq[gameinfo.accessoryReqCnt]));
                    } else if (gameinfo.accessoryCnt < XML_ELEMMAX) {
                        ++gameinfo.accessoryCnt;
                        strlcpy(gameinfo.accessories[gameinfo.accessoryCnt],mxmlElementGetAttr(nodeidtmp, "type"),
                                sizeof(gameinfo.accessories[gameinfo.accessoryCnt]));
                    }
                }
            }
            mxmlIndexDelete(nodeindextmp);
        }

        /* convert rating value */
        ConvertRating(gameinfo.ratingvalue, gameinfo.ratingtype, "CERO",gameinfo.ratingvalueCERO,sizeof(gameinfo.ratingvalueCERO));
        ConvertRating(gameinfo.ratingvalue, gameinfo.ratingtype, "ESRB",gameinfo.ratingvalueESRB,sizeof(gameinfo.ratingvalueESRB));
        ConvertRating(gameinfo.ratingvalue, gameinfo.ratingtype, "PEGI",gameinfo.ratingvaluePEGI,sizeof(gameinfo.ratingvaluePEGI));

        /* provide genre as an array: gameinfo.genresplit */
        if (strcmp(gameinfo.genre,"") != 0) {
            gameinfo.genreCnt=0;
            const char *delimgenre = ",;";
            char genretxt[200];
            strlcpy(genretxt,gameinfo.genre,sizeof(genretxt));
            char *splitresult;
            splitresult = strtok(genretxt, delimgenre);
            if (splitresult != NULL) {
                ++gameinfo.genreCnt;
                trimcopy(splitresult,splitresult,strlen(splitresult)+1);
                strlcpy(gameinfo.genresplit[gameinfo.genreCnt],splitresult,sizeof(gameinfo.genresplit[gameinfo.genreCnt]));
                gameinfo.genresplit[gameinfo.genreCnt][0] = toupper((int)gameinfo.genresplit[gameinfo.genreCnt][0]);
                while (splitresult != NULL) {
                    splitresult = strtok(NULL, delimgenre);
                    if (splitresult != NULL && strcmp(splitresult,"")!=0) {
                        ++gameinfo.genreCnt;
                        trimcopy(splitresult,splitresult,strlen(splitresult)+1);
                        strlcpy(gameinfo.genresplit[gameinfo.genreCnt],splitresult,sizeof(gameinfo.genresplit[gameinfo.genreCnt]));
                        gameinfo.genresplit[gameinfo.genreCnt][0] = toupper((int)gameinfo.genresplit[gameinfo.genreCnt][0]);
                        if (gameinfo.genreCnt == XML_ELEMMAX)
                            break;
                    }
                }
            }

        }

    }

    // if game was not found or info is missing
    // guess publisher from game id in case it is missing
    if (!strcmp(gameinfo.publisher,"")) {
        GetPublisherFromGameid(gameid,gameinfo.publisherfromid,sizeof(gameinfo.publisherfromid));
        strlcpy(gameinfo.publisher,gameinfo.publisherfromid,sizeof(gameinfo.publisher));
    }

    // if missing, get region from game ID
    if (!strcmp(gameinfo.region,"")) {
        if (gameid[3] == 'E') strlcpy(gameinfo.region,"NTSC-U",sizeof(gameinfo.region));
        if (gameid[3] == 'J') strlcpy(gameinfo.region,"NTSC-J",sizeof(gameinfo.region));
        if (gameid[3] == 'W') strlcpy(gameinfo.region,"NTSC-J",sizeof(gameinfo.region));
        if (gameid[3] == 'K') strlcpy(gameinfo.region,"NTSC-K",sizeof(gameinfo.region));
        if (gameid[3] == 'P') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region));
        if (gameid[3] == 'D') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region));
        if (gameid[3] == 'F') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region));
        if (gameid[3] == 'I') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region));
        if (gameid[3] == 'S') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region));
        if (gameid[3] == 'H') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region));
        if (gameid[3] == 'U') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region));
		if (gameid[3] == 'X') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region));
        if (gameid[3] == 'Y') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region));
        if (gameid[3] == 'Z') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region));
    }

    // free memory
    mxmlIndexDelete(nodeindex);

    return gameinfo;
}
Example #22
0
extern "C" DLL_EXPORT uint _dbg_sendmessage(DBGMSG type, void* param1, void* param2)
{
    if(dbgisstopped())
    {
        switch(type)  //ignore win events
        {
        //these functions are safe to call when we did not initialize yet
        case DBG_DEINITIALIZE_LOCKS:
        case DBG_INITIALIZE_LOCKS:
        case DBG_GET_FUNCTIONS:
        case DBG_SETTINGS_UPDATED:
        case DBG_GET_THREAD_LIST:
        case DBG_WIN_EVENT:
        case DBG_WIN_EVENT_GLOBAL:
            break;
        //the rest is unsafe -> throw an exception when people try to call them
        default:
            __debugbreak(); //we cannot process messages when the debugger is stopped, this must be a bug
        }
    }
    switch(type)
    {
    case DBG_SCRIPT_LOAD:
    {
        scriptload((const char*)param1);
    }
    break;

    case DBG_SCRIPT_UNLOAD:
    {
        scriptunload();
    }
    break;

    case DBG_SCRIPT_RUN:
    {
        scriptrun((int)(duint)param1);
    }
    break;

    case DBG_SCRIPT_STEP:
    {
        scriptstep();
    }
    break;

    case DBG_SCRIPT_BPTOGGLE:
    {
        return scriptbptoggle((int)(duint)param1);
    }
    break;

    case DBG_SCRIPT_BPGET:
    {
        return scriptbpget((int)(duint)param1);
    }
    break;

    case DBG_SCRIPT_CMDEXEC:
    {
        return scriptcmdexec((const char*)param1);
    }
    break;

    case DBG_SCRIPT_ABORT:
    {
        scriptabort();
    }
    break;

    case DBG_SCRIPT_GETLINETYPE:
    {
        return (duint)scriptgetlinetype((int)(duint)param1);
    }
    break;

    case DBG_SCRIPT_SETIP:
    {
        scriptsetip((int)(duint)param1);
    }
    break;

    case DBG_SCRIPT_GETBRANCHINFO:
    {
        return (duint)scriptgetbranchinfo((int)(duint)param1, (SCRIPTBRANCH*)param2);
    }
    break;

    case DBG_SYMBOL_ENUM:
    {
        SYMBOLCBINFO* cbInfo = (SYMBOLCBINFO*)param1;
        SymEnum(cbInfo->base, cbInfo->cbSymbolEnum, cbInfo->user);
    }
    break;

    case DBG_ASSEMBLE_AT:
    {
        return assembleat((duint)param1, (const char*)param2, 0, 0, false);
    }
    break;

    case DBG_MODBASE_FROM_NAME:
    {
        return ModBaseFromName((const char*)param1);
    }
    break;

    case DBG_DISASM_AT:
    {
        disasmget((uint)param1, (DISASM_INSTR*)param2);
    }
    break;

    case DBG_STACK_COMMENT_GET:
    {
        return stackcommentget((uint)param1, (STACK_COMMENT*)param2);
    }
    break;

    case DBG_GET_THREAD_LIST:
    {
        ThreadGetList((THREADLIST*)param1);
    }
    break;

    case DBG_SETTINGS_UPDATED:
    {
        valuesetsignedcalc(!settingboolget("Engine", "CalculationType")); //0:signed, 1:unsigned
        SetEngineVariable(UE_ENGINE_SET_DEBUG_PRIVILEGE, settingboolget("Engine", "EnableDebugPrivilege"));
        bOnlyCipAutoComments = settingboolget("Disassembler", "OnlyCipAutoComments");
        bListAllPages = settingboolget("Engine", "ListAllPages");
        bUndecorateSymbolNames = settingboolget("Engine", "UndecorateSymbolNames");
        bEnableSourceDebugging = settingboolget("Engine", "EnableSourceDebugging");

        uint setting;
        if(BridgeSettingGetUint("Engine", "BreakpointType", &setting))
        {
            switch(setting)
            {
            case 0: //break_int3short
                SetBPXOptions(UE_BREAKPOINT_INT3);
                break;
            case 1: //break_int3long
                SetBPXOptions(UE_BREAKPOINT_LONG_INT3);
                break;
            case 2: //break_ud2
                SetBPXOptions(UE_BREAKPOINT_UD2);
                break;
            }
        }

        char exceptionRange[MAX_SETTING_SIZE] = "";
        dbgclearignoredexceptions();
        if(BridgeSettingGet("Exceptions", "IgnoreRange", exceptionRange))
        {
            char* entry = strtok(exceptionRange, ",");
            while(entry)
            {
                unsigned long start;
                unsigned long end;
                if(sscanf(entry, "%08X-%08X", &start, &end) == 2 && start <= end)
                {
                    ExceptionRange range;
                    range.start = start;
                    range.end = end;
                    dbgaddignoredexception(range);
                }
                entry = strtok(0, ",");
            }
        }

        char cachePath[MAX_SETTING_SIZE];
        if(BridgeSettingGet("Symbols", "CachePath", cachePath))
        {
            // Trim the buffer to fit inside MAX_PATH
            strncpy_s(szSymbolCachePath, cachePath, _TRUNCATE);
        }
    }
    break;

    case DBG_DISASM_FAST_AT:
    {
        if(!param1 || !param2)
            return 0;
        BASIC_INSTRUCTION_INFO* basicinfo = (BASIC_INSTRUCTION_INFO*)param2;
        if(!disasmfast((uint)param1, basicinfo))
            basicinfo->size = 1;
        return 0;
    }
    break;

    case DBG_MENU_ENTRY_CLICKED:
    {
        int hEntry = (int)(uint)param1;
        pluginmenucall(hEntry);
    }
    break;

    case DBG_FUNCTION_GET:
    {
        FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1;
        return (uint)FunctionGet(info->addr, &info->start, &info->end);
    }
    break;

    case DBG_FUNCTION_OVERLAPS:
    {
        FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1;
        return (uint)FunctionOverlaps(info->start, info->end);
    }
    break;

    case DBG_FUNCTION_ADD:
    {
        FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1;
        return (uint)FunctionAdd(info->start, info->end, info->manual);
    }
    break;

    case DBG_FUNCTION_DEL:
    {
        FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1;
        return (uint)FunctionDelete(info->addr);
    }
    break;

    case DBG_LOOP_GET:
    {
        FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1;
        return (uint)LoopGet(info->depth, info->addr, &info->start, &info->end);
    }
    break;

    case DBG_LOOP_OVERLAPS:
    {
        FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1;
        return (uint)LoopOverlaps(info->depth, info->start, info->end, 0);
    }
    break;

    case DBG_LOOP_ADD:
    {
        FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1;
        return (uint)LoopAdd(info->start, info->end, info->manual);
    }
    break;

    case DBG_LOOP_DEL:
    {
        FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1;
        return (uint)LoopDelete(info->depth, info->addr);
    }
    break;

    case DBG_IS_RUN_LOCKED:
    {
        return (uint)waitislocked(WAITID_RUN);
    }
    break;

    case DBG_IS_BP_DISABLED:
    {
        BREAKPOINT bp;
        if(BpGet((uint)param1, BPNORMAL, 0, &bp))
            return !(uint)bp.enabled;
        return (uint)false;
    }
    break;

    case DBG_SET_AUTO_COMMENT_AT:
    {
        return (uint)CommentSet((uint)param1, (const char*)param2, false);
    }
    break;

    case DBG_DELETE_AUTO_COMMENT_RANGE:
    {
        CommentDelRange((uint)param1, (uint)param2);
    }
    break;

    case DBG_SET_AUTO_LABEL_AT:
    {
        return (uint)LabelSet((uint)param1, (const char*)param2, false);
    }
    break;

    case DBG_DELETE_AUTO_LABEL_RANGE:
    {
        LabelDelRange((uint)param1, (uint)param2);
    }
    break;

    case DBG_SET_AUTO_BOOKMARK_AT:
    {
        return (uint)BookmarkSet((uint)param1, false);
    }
    break;

    case DBG_DELETE_AUTO_BOOKMARK_RANGE:
    {
        BookmarkDelRange((uint)param1, (uint)param2);
    }
    break;

    case DBG_SET_AUTO_FUNCTION_AT:
    {
        return (uint)FunctionAdd((uint)param1, (uint)param2, false);
    }
    break;

    case DBG_DELETE_AUTO_FUNCTION_RANGE:
    {
        FunctionDelRange((uint)param1, (uint)param2);
    }
    break;

    case DBG_GET_STRING_AT:
    {
        STRING_TYPE strtype;
        char string[MAX_STRING_SIZE];
        if(disasmgetstringat((uint)param1, &strtype, string, string, MAX_STRING_SIZE-3))
        {
            if(strtype == str_ascii)
                sprintf((char*)param2, "\"%s\"", string);
            else //unicode
                sprintf((char*)param2, "L\"%s\"", string);
            return true;
        }
        return false;
    }
    break;

    case DBG_GET_FUNCTIONS:
    {
        return (uint)dbgfunctionsget();
    }
    break;

    case DBG_WIN_EVENT:
    {
        return (uint)pluginwinevent((MSG*)param1, (long*)param2);
    }
    break;

    case DBG_WIN_EVENT_GLOBAL:
    {
        return (uint)pluginwineventglobal((MSG*)param1);
    }
    break;

    case DBG_INITIALIZE_LOCKS:
    {
        SectionLockerGlobal::Initialize();
    }
    break;

    case DBG_DEINITIALIZE_LOCKS:
    {
        SectionLockerGlobal::Deinitialize();
    }
    break;

    case DBG_GET_TIME_WASTED_COUNTER:
        return dbggettimewastedcounter();
    }
    return 0;
}
Example #23
0
/* returns the value associated with key; if key is not present,
   returns "" as value and 0.  Otherwise returns 1
*/
int config_getvalue(char *key, char *value)
{
    char curr_line[255];
    char *curr_key;
    char *curr_value;
    char delimiter[] = "\t";
    int i;
    char log_string[255];

    *value = '\0'; /* the default return is an empty string */

    /* position ourselves at the start of the config file
     */
    _config_reset();

    /* iterate over the file; readline() returns 0 at eof
     */
    while(_config_readline(curr_line, 255))
    {

        /*ignore comments */
        if(curr_line[0]!='#')
        {

            /* remove endline character */
            for(i=0; i<255; i++)
            {
                if(*(curr_line+i) == '\n')
                {
                    *(curr_line + i) = '\0';
                    break;
                }
            }

            /* break line at tab-delimiter into key/value pair */
            curr_key = strtok(curr_line, delimiter);

            /* make sure current line is valid key\tvalue */
            if((curr_value=strtok(NULL, delimiter)) != NULL)
            {

                /* does current key match what we're looking for */
                if(!strcmp(key, curr_key))
                {
                    strcpy(value, curr_value);
                }
#ifdef DEBUG_CONFIG
                else
                {
                    sprintf(log_string, "DEBUG:\tPolonator_config: config_getvalue: did not match <%s>:<%s> to <%s>\n", curr_key, curr_value, key);
                    p_log(log_string);
                }
#endif
            }
        }
    }
    if((*value) == '\0')
    {   /* key not found */
        return 0;
    }
    else
    {
        return 1;
    }
}
Example #24
0
int parse_repair_conf_file(char *repair_conf_file, repair_arguments_t *ra) {
  
  char *buf = NULL;
  FILE *fp;
  struct stat file_stats;
  int nbytes;
  
  char *tmp = NULL;
  
  if(stat(repair_conf_file, &file_stats) == -1) {
    printf("Error: %s is not valid file name\n", repair_conf_file);
    fflush(stdout);
    return -1;
  }
  
  /* Allocate memory for buf */
  if(!(buf = (char*)calloc((file_stats.st_size + 1), sizeof(char)))) {
    printf("Could not alloc memory for buffer!\n");
    fflush(stdout);
    return -1;
  }
  
  if((fp = fopen(repair_conf_file, "rb")) == NULL) {
    printf("Error: unable to open file %s\n", repair_conf_file);
    fflush(stdout);
    free(buf);
    return -1;
  }
  
  nbytes = fread(buf, 1, file_stats.st_size, fp);
  
  if(nbytes <= 0) {
    free(buf);
    fclose(fp);
    return -1;
  }
  
  fclose(fp);
  
  tmp = strtok (buf, "=");
  
  while(tmp != NULL) {
    if(strcmp(tmp, "RepairMethod") == 0) {
      tmp = strtok(NULL, "\n");
      memset(ra->repair_method, 0, MAX_PATH_LENGTH);
      strcpy(ra->repair_method, tmp);
      
      if(ra->repair_method[strlen(ra->repair_method)-1] == '\r') {
	ra->repair_method[strlen(ra->repair_method)-1] = '\0';
      }
    }
    else if(strcmp(tmp, "RequestedBlocksFile") == 0) {
      tmp = strtok(NULL, "\n");
      memset(ra->requested_blocks_file, 0, MAX_PATH_LENGTH);
      
      strcpy(ra->requested_blocks_file, tmp);
      
      if(ra->requested_blocks_file[strlen(ra->requested_blocks_file)-1] == '\r') {
	ra->requested_blocks_file[strlen(ra->requested_blocks_file)-1] = '\0';
      }
    }
    else if(strcmp(tmp, "PTMRepairSDPFile") == 0) {
      tmp = strtok(NULL, "\n");
      memset(ra->ptm_repair_sdp_file, 0, MAX_PATH_LENGTH);
      strcpy(ra->ptm_repair_sdp_file, tmp);
      
      if(ra->ptm_repair_sdp_file[strlen(ra->ptm_repair_sdp_file)-1] == '\r') {
	ra->ptm_repair_sdp_file[strlen(ra->ptm_repair_sdp_file)-1] = '\0';
      }
    }
    else if(strcmp(tmp, "FluteConfFile") == 0) {
      tmp = strtok(NULL, "\n");
      memset(ra->flute_conf_file, 0, MAX_PATH_LENGTH);
      strcpy(ra->flute_conf_file, tmp);
      
      if(ra->flute_conf_file[strlen(ra->flute_conf_file)-1] == '\r') {
	ra->flute_conf_file[strlen(ra->flute_conf_file)-1] = '\0';
      }
    }
    
    tmp = strtok (NULL, "=");
  }
  
  free(buf);
  
  return 0;
}
Example #25
0
bool ChatHandler::HandleGOSpawn(const char *args, WorldSession *m_session)
{
	std::stringstream sstext;

	char* pEntryID = strtok((char*)args, " ");
	if (!pEntryID)
		return false;

	uint32 EntryID  = atoi(pEntryID);
	
	bool Save = false;
	char* pSave = strtok(NULL, " ");
	if (pSave)
		Save = atoi(pSave);

	GameObjectInfo* goi = GameObjectNameStorage.LookupEntry(EntryID);
	if(!goi)
	{
		sstext << "GameObject Info '" << EntryID << "' Not Found" << '\0';
		SystemMessage(m_session, sstext.str().c_str());
		return true;
	}

	sLog.outDebug("Spawning GameObject By Entry '%u'", EntryID);
	sstext << "Spawning GameObject By Entry '" << EntryID << "'" << '\0';
	SystemMessage(m_session, sstext.str().c_str());

	GameObject *go = m_session->GetPlayer()->GetMapMgr()->CreateGameObject();
	
	Player *chr = m_session->GetPlayer();
	uint32 mapid = chr->GetMapId();
	float x = chr->GetPositionX();
	float y = chr->GetPositionY();
	float z = chr->GetPositionZ();
	float o = chr->GetOrientation();

	go->SetInstanceID(chr->GetInstanceID());
	go->CreateFromProto(EntryID,mapid,x,y,z,o);
	
	/* f**k blizz coordinate system */
	go->SetFloatValue(GAMEOBJECT_ROTATION_02, sinf(o / 2));
	go->SetFloatValue(GAMEOBJECT_ROTATION_03, cosf(o / 2));
	go->PushToWorld(m_session->GetPlayer()->GetMapMgr());

	// Create sapwn instance
	GOSpawn * gs = new GOSpawn;
	gs->entry = go->GetEntry();
	gs->facing = go->GetOrientation();
	gs->faction = go->GetUInt32Value(GAMEOBJECT_FACTION);
	gs->flags = go->GetUInt32Value(GAMEOBJECT_FLAGS);
	gs->id = objmgr.GenerateGameObjectSpawnID();
	gs->o = go->GetFloatValue(GAMEOBJECT_ROTATION);
	gs->o1 = go->GetFloatValue(GAMEOBJECT_ROTATION_01);
	gs->o2 = go->GetFloatValue(GAMEOBJECT_ROTATION_02);
	gs->o3 = go->GetFloatValue(GAMEOBJECT_ROTATION_03);
	gs->scale = go->GetFloatValue(OBJECT_FIELD_SCALE_X);
	gs->x = go->GetPositionX();
	gs->y = go->GetPositionY();
	gs->z = go->GetPositionZ();
	gs->state = go->GetUInt32Value(GAMEOBJECT_STATE);
	gs->stateNpcLink = 0;

	uint32 cx = m_session->GetPlayer()->GetMapMgr()->GetPosX(m_session->GetPlayer()->GetPositionX());
	uint32 cy = m_session->GetPlayer()->GetMapMgr()->GetPosY(m_session->GetPlayer()->GetPositionY());

	m_session->GetPlayer()->GetMapMgr()->GetBaseMap()->GetSpawnsListAndCreate(cx,cy)->GOSpawns.push_back(gs);
	go->m_spawn = gs;
	go->spawnid = gs->id;

	//go->AddToWorld();

	if(Save == true)
	{
		// If we're saving, create template and add index
		go->SaveToDB();
	}
	return true;
}
Example #26
0
int pstatus (char *arg)
{
	struct ioc_vol v;
	struct ioc_read_subchannel ss;
	struct cd_sub_channel_info data;
	int rc, trk, m, s, f;
	int what = 0;
	char *p, vmcn[(4 * 15) + 1];

	while ((p = strtok(arg, " \t"))) {
	    arg = 0;
	    if (!strncasecmp(p, "audio", strlen(p)))
		what |= STATUS_AUDIO;
	    else if (!strncasecmp(p, "media", strlen(p)))
		what |= STATUS_MEDIA;
	    else if (!strncasecmp(p, "volume", strlen(p)))
		what |= STATUS_VOLUME;
	    else {
		warnx("invalid command arguments");
		return 0;
	    }
	}
	if (!what)
	    what = STATUS_AUDIO|STATUS_MEDIA|STATUS_VOLUME;
	if (what & STATUS_AUDIO) {
	    rc = status (&trk, &m, &s, &f);
	    if (rc >= 0)
		if (verbose)
		    printf ("Audio status = %d<%s>, current track = %d, current position = %d:%02d.%02d\n",
			    rc, strstatus (rc), trk, m, s, f);
		else
		    printf ("%d %d %d:%02d.%02d\n", rc, trk, m, s, f);
	    else
		printf ("No current status info available\n");
	}
	if (what & STATUS_MEDIA) {
	    bzero (&ss, sizeof (ss));
	    ss.data = &data;
	    ss.data_len = sizeof (data);
	    ss.address_format = msf ? CD_MSF_FORMAT : CD_LBA_FORMAT;
	    ss.data_format = CD_MEDIA_CATALOG;
	    rc = ioctl (fd, CDIOCREADSUBCHANNEL, (char *) &ss);
	    if (rc >= 0) {
		printf("Media catalog is %sactive",
		    ss.data->what.media_catalog.mc_valid ? "": "in");
		if (ss.data->what.media_catalog.mc_valid &&
		    ss.data->what.media_catalog.mc_number[0])
		{
		    strvisx (vmcn, ss.data->what.media_catalog.mc_number,
			    (sizeof (vmcn) - 1) / 4, VIS_OCTAL | VIS_NL);
		    printf(", number \"%.*s\"", (int)sizeof (vmcn), vmcn);
		}
		putchar('\n');
	    } else
		printf("No media catalog info available\n");
	}
	if (what & STATUS_VOLUME) {
	    rc = ioctl (fd, CDIOCGETVOL, &v);
	    if (rc >= 0)
		if (verbose)
		    printf ("Left volume = %d, right volume = %d\n",
			    v.vol[0], v.vol[1]);
		else
		    printf ("%d %d\n", v.vol[0], v.vol[1]);
	    else
		printf ("No volume level info available\n");
	}
	return(0);
}
Example #27
0
int start_stunnel(int stunnel_port, int x11vnc_port, int hport, int x11vnc_hport) {
#ifdef SSLCMDS
	char extra[] = ":/usr/sbin:/usr/local/sbin:/dist/sbin";
	char *path, *p, *exe;
	char *stunnel_path = NULL;
	struct stat verify_buf;
	struct stat crl_buf;
	int status, tmp_pem = 0;

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

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

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

	p = strtok(path, ":");

	exe[0] = '\0';

	while (p) {
		struct stat sbuf;

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

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

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

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

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

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

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

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

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

	stunnel_pid = fork();

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

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

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


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

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

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

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

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

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

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

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

		fflush(in);
		rewind(in);

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

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

	waitpid(stunnel_pid, &status, WNOHANG); 

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

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

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

	return 1;
#else
	return 0;
#endif
}
Example #28
0
int ReadIni_bank(ST_BANK_CONFIG *p_bankini)
{
	TIniFile tf;
	ST_BANK_CONFIG t_bank;
	char szBuf[256];
	char bank_unit[10]="";
	char * pch;
	int j=0;
	
	memset(&t_bank,0,sizeof t_bank);
	if (!tf.Open(TRANS_INI_FILE))
	{
		writelog(LOG_ERR,"Cann't open ini file,file's name=[%s]",TRANS_INI_FILE);
		return -1;
	}
	t_bank.BankCount=tf.ReadInt("COMMON","BANK_UNIT",1);
	t_bank.BCC_BASEFUNCNO=tf.ReadInt("COMMON","BCC_BASEFUNCNO",9000);
	t_bank.DRTP_BRANCH=tf.ReadInt("COMMON","DRTP_BRANCH",7000);
	t_bank.TIMEOUT=tf.ReadInt("COMMON","TIMEOUT",5);
	t_bank.DRTP_PORT=tf.ReadInt("COMMON","DRTP_PORT",4000);
	tf.ReadString("COMMON","DRTP_IP","127.0.0.1",t_bank.DRTP_IP,sizeof(t_bank.DRTP_IP)-1);
	tf.ReadString("COMMON","COMPACC_TIME","06",t_bank.COMPACC_TIME,sizeof(t_bank.COMPACC_TIME)-1);
	t_bank.AUTH_MODE=tf.ReadInt("COMMON","AUTH_MODE",1);
	t_bank.LOGIN_MODE=tf.ReadInt("COMMON","LOGIN_MODE",1);
	t_bank.LOG_MODE=tf.ReadInt("COMMON","LOG_MODE",1);
	tf.ReadString("COMMON","SERV_TIME","010000-235959",t_bank.SERV_TIME,sizeof(t_bank.SERV_TIME)-1);
	t_bank.trans_money=tf.ReadInt("COMMON","TRANS_MONEY",100000);
	for(int i=0;i<t_bank.BankCount;i++)
	{
		j=0;
		sprintf(bank_unit,"BANK%d",i+1);
		tf.ReadString(bank_unit,"BANK_IP","26.136.2.9",t_bank.BankUnit[i].szBankIP,sizeof(t_bank.BankUnit[i].szBankIP)-1);
		writelog(LOG_ERR,"read   ip :%s",t_bank.BankUnit[i].szBankIP);
		t_bank.BankUnit[i].iBankID= tf.ReadInt(bank_unit,"BANK_ID",1);
		t_bank.BankUnit[i].iBankPort= tf.ReadInt(bank_unit,"BANK_PORT",5301);
		writelog(LOG_ERR,"read   port :%d",t_bank.BankUnit[i].iBankPort);
		t_bank.BankUnit[i].iBankTimeout= tf.ReadInt(bank_unit,"BANK_DELAY_TIME",5000);
              writelog(LOG_ERR,"read   iBankTimeout :%d",t_bank.BankUnit[i].iBankTimeout);
		t_bank.BankUnit[i].iAuthMode= tf.ReadInt(bank_unit,"AUTH_MODE",1);
		t_bank.BankUnit[i].compare_flag= tf.ReadInt(bank_unit,"COMPARE_FLAG",1);
		t_bank.BankUnit[i].sendcompreq_flag= tf.ReadInt(bank_unit,"SENDCOMPREQ_FLAG",0);
		t_bank.BankUnit[i].compare_count= tf.ReadInt(bank_unit,"COMPARE_COUNT",0);
		tf.ReadString(bank_unit,"BANK_ACCOUNT_NO","2011",t_bank.BankUnit[i].szBankAccountNO,sizeof(t_bank.BankUnit[i].szBankAccountNO)-1);	// 如果是多家银行, 此处需要填写一卡通的银行账户
		tf.ReadString(bank_unit,"BANK_CARD_RANGE","",szBuf,sizeof(szBuf)-1);
		tf.ReadString(bank_unit,"COMPARE_TIME","06",t_bank.BankUnit[i].compare_time,sizeof(t_bank.BankUnit[i].compare_time) - 1);
		tf.ReadString(bank_unit,"SENDCOMPREQ_TIME","05",t_bank.BankUnit[i].sendcompreq_time,sizeof(t_bank.BankUnit[i].sendcompreq_time) - 1);
		tf.ReadString(bank_unit,"COMP_FILE_PATH","/home",t_bank.BankUnit[i].comp_file_path,sizeof(t_bank.BankUnit[i].comp_file_path) - 1);
		//writelog(LOG_INFO,"COMP_FILE_PATH=[%s], BANK_CARD_RANGE=[%s], BANK_ACCOUNT_NO=[%s]", t_bank.BankUnit[i].comp_file_path, szBuf, t_bank.BankUnit[i].szBankAccountNO);
		pch = strtok (szBuf,",");
		while (pch != NULL)
		{
			des2src(t_bank.BankUnit[i].szBankCardRange[j], pch);
			pch = strtok (NULL, ",");
			//writelog(LOG_INFO,"BANKID=[%d], BANKCARDRAGNT=[%s], i=[%d], j=[%d]", t_bank.BankUnit[i].iBankID, t_bank.BankUnit[i].szBankCardRange[j], i, j);
			j++;
			if(j>=MAX_RANGE) 
				break;
		}
	}
	memcpy(p_bankini,&t_bank,sizeof(t_bank));
	tf.Close();
	return 0;   
}
Example #29
0
//-----------------------------------------------------------------------------
// A Scene image file contains all the compiled .XCD
//-----------------------------------------------------------------------------
bool CSceneImage::CreateSceneImageFile( CUtlBuffer &targetBuffer, char const *pchModPath, bool bLittleEndian, bool bQuiet, ISceneCompileStatus *pStatus )
{
	CUtlVector<fileList_t>	vcdFileList;
	CUtlSymbolTable			vcdSymbolTable( 0, 32, true );

	Msg( "\n" );

	// get all the VCD files according to the seacrh paths
	char searchPaths[512];
	g_pFullFileSystem->GetSearchPath( "GAME", false, searchPaths, sizeof( searchPaths ) );
	char *pPath = strtok( searchPaths, ";" );
	while ( pPath )
	{
		int currentCount = vcdFileList.Count();

		char szPath[MAX_PATH];
		V_ComposeFileName( pPath, "scenes/*.vcd", szPath, sizeof( szPath ) );

		scriptlib->FindFiles( szPath, true, vcdFileList );

		Msg( "Scenes: Searching '%s' - Found %d scenes.\n", szPath, vcdFileList.Count() - currentCount );

		pPath = strtok( NULL, ";" );
	}

	if ( !vcdFileList.Count() )
	{
		Msg( "Scenes: No Scene Files found!\n" );
		return false;
	}

	// iterate and convert all the VCD files
	bool bGameIsTF = V_stristr( pchModPath, "\\tf" ) != NULL;
	for ( int i=0; i<vcdFileList.Count(); i++ )
	{
		const char *pFilename = vcdFileList[i].fileName.String();
		const char *pSceneName = V_stristr( pFilename, "scenes\\" );
		if ( !pSceneName )
		{
			continue;
		}

		if ( !bLittleEndian && bGameIsTF && V_stristr( pSceneName, "high\\" ) )
		{
			continue;
		}

		// process files in order they would be found in search paths
		// i.e. skipping later processed files that match an earlier conversion
		UtlSymId_t symbol = vcdSymbolTable.Find( pSceneName );
		if ( symbol == UTL_INVAL_SYMBOL )
		{
			vcdSymbolTable.AddString( pSceneName );

			pStatus->UpdateStatus( pFilename, bQuiet, i, vcdFileList.Count() );

			if ( !CreateTargetFile_VCD( pFilename, "", false, bLittleEndian ) )
			{
				Error( "CreateSceneImageFile: Failed on '%s' conversion!\n", pFilename );
			}


		}
	}

	if ( !g_SceneFiles.Count() )
	{
		// nothing to do
		return true;
	}

	Msg( "Scenes: Finalizing %d unique scenes.\n", g_SceneFiles.Count() );


	// get the string pool
	CUtlVector< unsigned int > stringOffsets;
	CUtlBuffer stringPool;
	g_ChoreoStringPool.GetTableAndPool( stringOffsets, stringPool );

	if ( !bQuiet )
	{
		Msg( "Scenes: String Table: %d bytes\n", stringOffsets.Count() * sizeof( int ) );
		Msg( "Scenes: String Pool: %d bytes\n", stringPool.TellMaxPut() );
	}

	// first header, then lookup table, then string pool blob
	int stringPoolStart = sizeof( SceneImageHeader_t ) + stringOffsets.Count() * sizeof( int );
	// then directory
	int sceneEntryStart = stringPoolStart + stringPool.TellMaxPut();
	// then variable sized summaries
	int sceneSummaryStart = sceneEntryStart + g_SceneFiles.Count() * sizeof( SceneImageEntry_t );
	// then variable sized compiled binary scene data
	int sceneDataStart = 0;

	// construct header
	SceneImageHeader_t imageHeader = { 0 };
	imageHeader.nId = SCENE_IMAGE_ID;
	imageHeader.nVersion = SCENE_IMAGE_VERSION;
	imageHeader.nNumScenes = g_SceneFiles.Count();
	imageHeader.nNumStrings = stringOffsets.Count();
	imageHeader.nSceneEntryOffset = sceneEntryStart;
	if ( !bLittleEndian )
	{
		imageHeader.nId = BigLong( imageHeader.nId );
		imageHeader.nVersion = BigLong( imageHeader.nVersion );
		imageHeader.nNumScenes = BigLong( imageHeader.nNumScenes );
		imageHeader.nNumStrings = BigLong( imageHeader.nNumStrings );
		imageHeader.nSceneEntryOffset = BigLong( imageHeader.nSceneEntryOffset );
	}
	targetBuffer.Put( &imageHeader, sizeof( imageHeader ) );

	// header is immediately followed by string table and pool
	for ( int i = 0; i < stringOffsets.Count(); i++ )
	{
		unsigned int offset = stringPoolStart + stringOffsets[i];
		if ( !bLittleEndian )
		{
			offset = BigLong( offset );
		}
		targetBuffer.PutInt( offset );
	}
	Assert( stringPoolStart == targetBuffer.TellMaxPut() );
	targetBuffer.Put( stringPool.Base(), stringPool.TellMaxPut() );

	// construct directory
	CUtlSortVector< SceneImageEntry_t, CSceneImageEntryLessFunc > imageDirectory;
	imageDirectory.EnsureCapacity( g_SceneFiles.Count() );

	// build directory
	// directory is linear sorted by filename checksum for later binary search
	for ( int i = 0; i < g_SceneFiles.Count(); i++ )
	{
		SceneImageEntry_t imageEntry = { 0 };

		// name needs to be normalized for determinstic later CRC name calc
		// calc crc based on scenes\anydir\anyscene.vcd
		char szCleanName[MAX_PATH];
		V_strncpy( szCleanName, g_SceneFiles[i].fileName.String(), sizeof( szCleanName ) );
		V_strlower( szCleanName );
		V_FixSlashes( szCleanName );
		char *pName = V_stristr( szCleanName, "scenes\\" );
		if ( !pName )
		{
			// must have scenes\ in filename
			Error( "CreateSceneImageFile: Unexpected lack of scenes prefix on %s\n", g_SceneFiles[i].fileName.String() );
		}

		CRC32_t crcFilename = CRC32_ProcessSingleBuffer( pName, strlen( pName ) );
		imageEntry.crcFilename = crcFilename;

		// temp store an index to its file, fixup later, necessary to access post sort
		imageEntry.nDataOffset = i;
		if ( imageDirectory.Find( imageEntry ) != imageDirectory.InvalidIndex() )
		{
			// filename checksums must be unique or runtime binary search would be bogus
			Error( "CreateSceneImageFile: Unexpected filename checksum collision!\n" );
		}		

		imageDirectory.Insert( imageEntry );
	}

	// determine sort order and start of data after dynamic summaries
	CUtlVector< int > writeOrder;
	writeOrder.EnsureCapacity( g_SceneFiles.Count() );
	sceneDataStart = sceneSummaryStart;
	for ( int i = 0; i < imageDirectory.Count(); i++ )
	{
		// reclaim offset, indicates write order of scene file
		int iScene = imageDirectory[i].nDataOffset;
		writeOrder.AddToTail( iScene );

		// march past each variable sized summary to determine start of scene data
		int numSounds = g_SceneFiles[iScene].soundList.Count();
		sceneDataStart += sizeof( SceneImageSummary_t ) + ( numSounds - 1 ) * sizeof( int );
	}

	// finalize and write directory
	Assert( sceneEntryStart == targetBuffer.TellMaxPut() );
	int nSummaryOffset = sceneSummaryStart;
	int nDataOffset = sceneDataStart;
	for ( int i = 0; i < imageDirectory.Count(); i++ )
	{
		int iScene = writeOrder[i];

		imageDirectory[i].nDataOffset = nDataOffset;
		imageDirectory[i].nDataLength = g_SceneFiles[iScene].compiledBuffer.TellMaxPut();
		imageDirectory[i].nSceneSummaryOffset = nSummaryOffset;
		if ( !bLittleEndian )
		{
			imageDirectory[i].crcFilename = BigLong( imageDirectory[i].crcFilename );
			imageDirectory[i].nDataOffset = BigLong( imageDirectory[i].nDataOffset );
			imageDirectory[i].nDataLength = BigLong( imageDirectory[i].nDataLength );
			imageDirectory[i].nSceneSummaryOffset = BigLong( imageDirectory[i].nSceneSummaryOffset );
		}
		targetBuffer.Put( &imageDirectory[i], sizeof( SceneImageEntry_t ) );

		int numSounds = g_SceneFiles[iScene].soundList.Count();
		nSummaryOffset += sizeof( SceneImageSummary_t ) + (numSounds - 1) * sizeof( int );

		nDataOffset += g_SceneFiles[iScene].compiledBuffer.TellMaxPut();
	}

	// finalize and write summaries
	Assert( sceneSummaryStart == targetBuffer.TellMaxPut() );
	for ( int i = 0; i < imageDirectory.Count(); i++ )
	{
		int iScene = writeOrder[i];
		int msecs = g_SceneFiles[iScene].msecs;
		int soundCount = g_SceneFiles[iScene].soundList.Count();
		if ( !bLittleEndian )
		{
			msecs = BigLong( msecs );
			soundCount = BigLong( soundCount );
		}
		targetBuffer.PutInt( msecs );
		targetBuffer.PutInt( soundCount );
		for ( int j = 0; j < g_SceneFiles[iScene].soundList.Count(); j++ )
		{
			int soundId = g_SceneFiles[iScene].soundList[j];
			if ( !bLittleEndian )
			{
				soundId = BigLong( soundId );
			}
			targetBuffer.PutInt( soundId );
		}
	}

	// finalize and write data
	Assert( sceneDataStart == targetBuffer.TellMaxPut() );
	for ( int i = 0; i < imageDirectory.Count(); i++ )
	{	
		int iScene = writeOrder[i];
		targetBuffer.Put( g_SceneFiles[iScene].compiledBuffer.Base(), g_SceneFiles[iScene].compiledBuffer.TellMaxPut() );
	}

	if ( !bQuiet )
	{
		Msg( "Scenes: Final size: %.2f MB\n", targetBuffer.TellMaxPut() / (1024.0f * 1024.0f ) );
	}

	// cleanup
	g_SceneFiles.Purge();

	return true;
}
Example #30
-1
int nis_get_service (
  int num_connect_fails,
  char *generic_service_name,
  char *service_name,
  char *node,
  int *mode
) {

static int init = 1;
static char nodes[2][31+1];
static int modes[] = { RPC_K_MASTER, RPC_K_LOCAL };
int stat, ret_stat, i, item;
unsigned short len;
struct dsc$descriptor dsc;
char *ptr, buf[127+1];

  if ( init ) {
    strcpy( nodes[0], "ORIB01" );
    strcpy( nodes[1], "ORIB01" );
    init = 0;
  }

  if ( strstr( generic_service_name, "::" ) ) {

    strncpy( buf, generic_service_name, 127 );
    ptr = strtok( buf, "::" );
    strncpy( node, ptr, 7 );
    ptr = strtok( NULL, "::" );
    strcpy( service_name, ptr );

  }
  else if ( strncmp( generic_service_name,
    "IOSCNR", strlen("IOSCNR") ) == 0 ) {

    i = 0;

    strcpy( service_name, "IOS" );
    strncpy( node, nodes[i], 7 );
    *mode = modes[i];

  }
  else if ( strncmp( generic_service_name,
    "REM_CONSOLE", strlen("REM_CONSOLE") ) == 0 ) {

    i = 0;

    strcpy( service_name, "CONSOLE" );
    strncpy( node, nodes[i], 7 );
    *mode = modes[i];

  }
  else if ( strncmp( generic_service_name,
    "DBSCANSRV", strlen("DBSCANSRV") ) == 0 ) {

    i = 0;

    strcpy( service_name, "DBSCANSRV" );
    strncpy( node, nodes[i], 7 );
    *mode = modes[i];

  }
  else if ( strncmp( generic_service_name,
    "TEST", strlen("TEST") ) == 0 ) {

    i = 0;

    strcpy( service_name, "TEST" );
    strncpy( node, nodes[i], 7 );
    *mode = modes[i];

  }
  else {

    ret_stat = NIS_UNKSVC;
    goto err_return;

  }

norm_return:
  return NIS_SUCCESS;

err_return:

  strcpy( service_name, "" );
  strcpy( node, "" );
  *mode = 0;

  return ret_stat;

}