Пример #1
0
/* 处理客户端的连接 */
void handle_client(int client_sock, struct sockaddr_in client_addr)
{
    int is_http_tunnel = 0; 
    if(strlen(remote_host) == 0) /* 未指定远端主机名称从http 请求 HOST 字段中获取 */
    {
        
        #ifdef DEBUG
        LOG(" ============ handle new client ============\n");
        LOG(">>>Header:%s\n",header_buffer);
        #endif
        
        if(read_header(client_sock,header_buffer) < 0)
        {
            LOG("Read Http header failed\n");
            return;
        } else 
        {
            char * p = strstr(header_buffer,"CONNECT"); /* 判断是否是http 隧道请求 */
            if(p) 
            {
                LOG("receive CONNECT request\n");
                is_http_tunnel = 1;
            }

            if(strstr(header_buffer,"GET /mproxy") >0 ) 
            {
                LOG("====== hand mproxy info request ====");
                //返回mproxy的运行基本信息
                hand_mproxy_info_req(client_sock,header_buffer);

                return; 
            }

            if(extract_host(header_buffer) < 0) 
            {
                LOG("Cannot extract host field,bad http protrotol");
                return;
            }
            LOG("Host:%s port: %d io_flag:%d\n",remote_host,remote_port,io_flag);

        }
    }

    if ((remote_sock = create_connection()) < 0) {
        LOG("Cannot connect to host [%s:%d]\n",remote_host,remote_port);
        return;
    }

    if (fork() == 0) { // 创建子进程用于从客户端转发数据到远端socket接口

        if(strlen(header_buffer) > 0 && !is_http_tunnel) 
        {
            forward_header(remote_sock); //普通的http请求先转发header
        } 
        
        forward_data(client_sock, remote_sock);
        exit(0);
    }

    if (fork() == 0) { // 创建子进程用于转发从远端socket接口过来的数据到客户端

        if(io_flag == W_S_ENC)
        {
            io_flag = R_C_DEC; //发送请求给服务端进行编码,读取服务端的响应则进行解码
        } else if (io_flag == R_C_DEC)
        {
             io_flag = W_S_ENC; //接收客户端请求进行解码,那么响应客户端请求需要编码
        }

        if(is_http_tunnel)
        {
            send_tunnel_ok(client_sock);
        } 

        forward_data(remote_sock, client_sock);
        exit(0);
    }

    close(remote_sock);
    close(client_sock);
}
Пример #2
0
SnesCartridge::SnesCartridge(const uint8_t *data, unsigned size) {
  read_header(data, size);

  string xml;
  markup = "<?xml version='1.0' encoding='UTF-8'?>\n";

  if(type == TypeBsx) {
    markup.append("<cartridge/>\n");
    return;
  }

  if(type == TypeSufamiTurbo) {
    markup.append("<cartridge/>\n");
    return;
  }

  if(type == TypeGameBoy) {
    markup.append("<cartridge rtc='", gameboy_has_rtc(data, size), "'\n");
    if(gameboy_ram_size(data, size) > 0) {
      markup.append("  <ram size='0x", hex(gameboy_ram_size(data, size)), "'>\n");
    }
    markup.append("</cartridge>\n");
    return;
  }

  const char *range = (rom_size > 0x200000) || (ram_size > 32 * 1024) ? "0000-7fff" : "0000-ffff";
  markup.append("<cartridge region='", region == NTSC ? "NTSC" : "PAL", "'>\n");

  if(type == TypeSuperGameBoy1Bios || type == TypeSuperGameBoy2Bios) markup.append(
    "  <rom>\n"
    "    <map mode='linear' address='00-7f:8000-ffff'/>\n"
    "    <map mode='linear' address='80-ff:8000-ffff'/>\n"
    "  </rom>\n"
    "  <icd2 revision='1'>\n"
    "    <map address='00-3f:6000-7fff'/>\n"
    "    <map address='80-bf:6000-7fff'/>\n"
    "  </icd2>\n"
  );

  else if(has_cx4) markup.append(
    "  <hitachidsp model='HG51B169' frequency='20000000' firmware='cx4.bin' sha256='ae8d4d1961b93421ff00b3caa1d0f0ce7783e749772a3369c36b3dbf0d37ef18'>\n"
    "    <rom>\n"
    "      <map mode='linear' address='00-7f:8000-ffff'/>\n"
    "      <map mode='linear' address='80-ff:8000-ffff'/>\n"
    "    </rom>\n"
    "    <mmio>\n"
    "      <map address='00-3f:6000-7fff'/>\n"
    "      <map address='80-bf:6000-7fff'/>\n"
    "    </mmio>\n"
    "  </hitachidsp>\n"
  );

  else if(has_spc7110) {
    markup.append(
      "  <rom>\n"
      "    <map mode='shadow' address='00-0f:8000-ffff'/>\n"
      "    <map mode='shadow' address='80-bf:8000-ffff'/>\n"
      "    <map mode='linear' address='c0-cf:0000-ffff'/>\n"
      "  </rom>\n"
      "  <spc7110>\n"
      "    <ram size='0x", hex(ram_size), "'>\n"
      "      <map mode='linear' address='00:6000-7fff'/>\n"
      "      <map mode='linear' address='30:6000-7fff'/>\n"
      "    </ram>\n"
      "    <mmio>\n"
      "      <map address='00-3f:4800-483f'/>\n"
      "      <map address='80-bf:4800-483f'/>\n"
      "    </mmio>\n"
      "    <mcu>\n"
      "      <map address='d0-ff:0000-ffff' offset='0x100000' size='0x", hex(size - 0x100000), "'/>\n"
      "    </mcu>\n"
      "    <dcu>\n"
      "      <map address='50:0000-ffff'/>\n"
      "    </dcu>\n"
    );
    if(has_spc7110rtc) markup.append(
      "    <rtc>\n"
      "      <map address='00-3f:4840-4842'/>\n"
      "      <map address='80-bf:4840-4842'/>\n"
      "    </rtc>\n"
    );
    markup.append(
      "  </spc7110>\n"
    );
  }

  else if(mapper == LoROM) {
    markup.append(
      "  <rom>\n"
      "    <map mode='linear' address='00-7f:8000-ffff'/>\n"
      "    <map mode='linear' address='80-ff:8000-ffff'/>\n"
      "  </rom>\n"
    );
    if(ram_size > 0) markup.append(string(
      string("  <ram size='0x", hex(ram_size), "'>\n"),
      string("    <map mode='linear' address='20-3f:6000-7fff'/>\n"
      "    <map mode='linear' address='a0-bf:6000-7fff'/>\n"),
      string("    <map mode='linear' address='70-7f:", range, "'/>\n"),
      string("    <map mode='linear' address='f0-ff:", range, "'/>\n"),
      "  </ram>\n"
    ));
  }

  else if(mapper == HiROM) {
    markup.append(
      "  <rom>\n"
      "    <map mode='shadow' address='00-3f:8000-ffff'/>\n"
      "    <map mode='linear' address='40-7f:0000-ffff'/>\n"
      "    <map mode='shadow' address='80-bf:8000-ffff'/>\n"
      "    <map mode='linear' address='c0-ff:0000-ffff'/>\n"
      "  </rom>\n"
    );
    if(ram_size > 0) markup.append(
      "  <ram size='0x", hex(ram_size), "'>\n"
      "    <map mode='linear' address='20-3f:6000-7fff'/>\n"
      "    <map mode='linear' address='a0-bf:6000-7fff'/>\n"
      "    <map mode='linear' address='70-7f:", range, "'/>\n"
      "  </ram>\n"
    );
  }

  else if(mapper == ExLoROM) {
    markup.append(
      "  <rom>\n"
      "    <map mode='linear' address='00-3f:8000-ffff'/>\n"
      "    <map mode='linear' address='40-7f:0000-ffff'/>\n"
      "    <map mode='linear' address='80-bf:8000-ffff'/>\n"
      "  </rom>\n"
    );
    if(ram_size > 0) markup.append(
      "  <ram size='0x", hex(ram_size), "'>\n"
      "    <map mode='linear' address='20-3f:6000-7fff'/>\n"
      "    <map mode='linear' address='a0-bf:6000-7fff'/>\n"
      "    <map mode='linear' address='70-7f:0000-7fff'/>\n"
      "  </ram>\n"
    );
  }

  else if(mapper == ExHiROM) {
    markup.append(
      "  <rom>\n"
      "    <map mode='shadow' address='00-3f:8000-ffff' offset='0x400000'/>\n"
      "    <map mode='linear' address='40-7f:0000-ffff' offset='0x400000'/>\n"
      "    <map mode='shadow' address='80-bf:8000-ffff' offset='0x000000'/>\n"
      "    <map mode='linear' address='c0-ff:0000-ffff' offset='0x000000'/>\n"
      "  </rom>\n"
    );
    if(ram_size > 0) markup.append(
      "  <ram size='0x", hex(ram_size), "'>\n"
      "    <map mode='linear' address='20-3f:6000-7fff'/>\n"
      "    <map mode='linear' address='a0-bf:6000-7fff'/>\n"
      "    <map mode='linear' address='70-7f:", range, "'/>\n"
      "  </ram>\n"
    );
  }

  else if(mapper == SuperFXROM) markup.append(
    "  <superfx revision='2'>\n"
    "    <rom>\n"
    "      <map mode='linear' address='00-3f:8000-ffff'/>\n"
    "      <map mode='linear' address='40-5f:0000-ffff'/>\n"
    "      <map mode='linear' address='80-bf:8000-ffff'/>\n"
    "      <map mode='linear' address='c0-df:0000-ffff'/>\n"
    "    </rom>\n"
    "    <ram size='0x", hex(ram_size), "'>\n"
    "      <map mode='linear' address='00-3f:6000-7fff' size='0x2000'/>\n"
    "      <map mode='linear' address='60-7f:0000-ffff'/>\n"
    "      <map mode='linear' address='80-bf:6000-7fff' size='0x2000'/>\n"
    "      <map mode='linear' address='e0-ff:0000-ffff'/>\n"
    "    </ram>\n"
    "    <mmio>\n"
    "      <map address='00-3f:3000-32ff'/>\n"
    "      <map address='80-bf:3000-32ff'/>\n"
    "    </mmio>\n"
    "  </superfx>\n"
  );

  else if(mapper == SA1ROM) markup.append(
    "  <sa1>\n"
    "    <mcu>\n"
    "      <rom>\n"
    "        <map mode='direct' address='00-3f:8000-ffff'/>\n"
    "        <map mode='direct' address='80-bf:8000-ffff'/>\n"
    "        <map mode='direct' address='c0-ff:0000-ffff'/>\n"
    "      </rom>\n"
    "      <ram>\n"
    "        <map mode='direct' address='00-3f:6000-7fff'/>\n"
    "        <map mode='direct' address='80-bf:6000-7fff'/>\n"
    "      </ram>\n"
    "    </mcu>\n"
    "    <iram size='0x800'>\n"
    "      <map mode='linear' address='00-3f:3000-37ff'/>\n"
    "      <map mode='linear' address='80-bf:3000-37ff'/>\n"
    "    </iram>\n"
    "    <bwram size='0x", hex(ram_size), "'>\n"
    "      <map mode='linear' address='40-4f:0000-ffff'/>\n"
    "    </bwram>\n"
    "    <mmio>\n"
    "      <map address='00-3f:2200-23ff'/>\n"
    "      <map address='80-bf:2200-23ff'/>\n"
    "    </mmio>\n"
    "  </sa1>\n"
  );

  else if(mapper == BSCLoROM) markup.append(
    "  <rom>\n"
    "    <map mode='linear' address='00-1f:8000-ffff' offset='0x000000'/>\n"
    "    <map mode='linear' address='20-3f:8000-ffff' offset='0x100000'/>\n"
    "    <map mode='linear' address='80-9f:8000-ffff' offset='0x200000'/>\n"
    "    <map mode='linear' address='a0-bf:8000-ffff' offset='0x100000'/>\n"
    "  </rom>\n"
    "  <ram size='0x", hex(ram_size), "'>\n"
    "    <map mode='linear' address='70-7f:0000-7fff'/>\n"
    "    <map mode='linear' address='f0-ff:0000-7fff'/>\n"
    "  </ram>\n"
    "  <bsx>\n"
    "    <slot>\n"
    "      <map mode='linear' address='c0-ef:0000-ffff'/>\n"
    "    </slot>\n"
    "  </bsx>\n"
  );

  else if(mapper == BSCHiROM) markup.append(
    "  <rom>\n"
    "    <map mode='shadow' address='00-1f:8000-ffff'/>\n"
    "    <map mode='linear' address='40-5f:0000-ffff'/>\n"
    "    <map mode='shadow' address='80-9f:8000-ffff'/>\n"
    "    <map mode='linear' address='c0-df:0000-ffff'/>\n"
    "  </rom>\n"
    "  <ram size='0x", hex(ram_size), "'>\n"
    "    <map mode='linear' address='20-3f:6000-7fff'/>\n"
    "    <map mode='linear' address='a0-bf:6000-7fff'/>\n"
    "  </ram>\n"
    "  <bsx>\n"
    "    <slot>\n"
    "      <map mode='shadow' address='20-3f:8000-ffff'/>\n"
    "      <map mode='linear' address='60-7f:0000-ffff'/>\n"
    "      <map mode='shadow' address='a0-bf:8000-ffff'/>\n"
    "      <map mode='linear' address='e0-ff:0000-ffff'/>\n"
    "    </slot>\n"
    "  </bsx>\n"
  );

  else if(mapper == BSXROM) markup.append(
    "  <bsx>\n"
    "    <mcu>\n"
    "      <map address='00-3f:8000-ffff'/>\n"
    "      <map address='80-bf:8000-ffff'/>\n"
    "      <map address='40-7f:0000-ffff'/>\n"
    "      <map address='c0-ff:0000-ffff'/>\n"
    "      <map address='20-3f:6000-7fff'/>\n"
    "    </mcu>\n"
    "    <mmio>\n"
    "      <map address='00-3f:5000-5fff'/>\n"
    "      <map address='80-bf:5000-5fff'/>\n"
    "    </mmio>\n"
    "  </bsx>\n"
  );

  else if(mapper == STROM) markup.append(
    "  <rom>\n"
    "    <map mode='linear' address='00-1f:8000-ffff'/>\n"
    "    <map mode='linear' address='80-9f:8000-ffff'/>\n"
    "  </rom>\n"
    "  <sufamiturbo>\n"
    "    <slot id='A'>\n"
    "      <rom>\n"
    "        <map mode='linear' address='20-3f:8000-ffff'/>\n"
    "        <map mode='linear' address='a0-bf:8000-ffff'/>\n"
    "      </rom>\n"
    "      <ram size='0x20000'>\n"
    "        <map mode='linear' address='60-63:8000-ffff'/>\n"
    "        <map mode='linear' address='e0-e3:8000-ffff'/>\n"
    "      </ram>\n"
    "    </slot>\n"
    "    <slot id='B'>\n"
    "      <rom>\n"
    "        <map mode='linear' address='40-5f:8000-ffff'/>\n"
    "        <map mode='linear' address='c0-df:8000-ffff'/>\n"
    "      </rom>\n"
    "      <ram size='0x20000'>\n"
    "        <map mode='linear' address='70-73:8000-ffff'/>\n"
    "        <map mode='linear' address='f0-f3:8000-ffff'/>\n"
    "      </ram>\n"
    "    </slot>\n"
    "  </sufamiturbo>\n"
  );

  if(has_srtc) markup.append(
    "  <srtc>\n"
    "    <map address='00-3f:2800-2801'/>\n"
    "    <map address='80-bf:2800-2801'/>\n"
    "  </srtc>\n"
  );

  if(has_sdd1) markup.append(
    "  <sdd1>\n"
    "    <mcu>\n"
    "      <map address='c0-ff:0000-ffff'/>\n"
    "    </mcu>\n"
    "    <mmio>\n"
    "      <map address='00-3f:4800-4807'/>\n"
    "      <map address='80-bf:4800-4807'/>\n"
    "    </mmio>\n"
    "  </sdd1>\n"
  );

  if(has_obc1) markup.append(
    "  <obc1>\n"
    "    <map address='00-3f:6000-7fff'/>\n"
    "    <map address='80-bf:6000-7fff'/>\n"
    "  </obc1>\n"
  );

  if(has_dsp1) {
    markup.append("  <necdsp model='uPD7725' frequency='8000000' firmware='dsp1b.bin' sha256='4d42db0f36faef263d6b93f508e8c1c4ae8fc2605fd35e3390ecc02905cd420c'>\n");
    if(dsp1_mapper == DSP1LoROM1MB) markup.append(
      "    <dr>\n"
      "      <map address='20-3f:8000-bfff'/>\n"
      "      <map address='a0-bf:8000-bfff'/>\n"
      "    </dr>\n"
      "    <sr>\n"
      "      <map address='20-3f:c000-ffff'/>\n"
      "      <map address='a0-bf:c000-ffff'/>\n"
      "    </sr>\n"
    );
    if(dsp1_mapper == DSP1LoROM2MB) markup.append(
      "    <dr>\n"
      "      <map address='60-6f:0000-3fff'/>\n"
      "      <map address='e0-ef:0000-3fff'/>\n"
      "    </dr>\n"
      "    <sr>\n"
      "      <map address='60-6f:4000-7fff'/>\n"
      "      <map address='e0-ef:4000-7fff'/>\n"
      "    </sr>\n"
    );
    if(dsp1_mapper == DSP1HiROM) markup.append(
      "    <dr>\n"
      "      <map address='00-1f:6000-6fff'/>\n"
      "      <map address='80-9f:6000-6fff'/>\n"
      "    </dr>\n"
      "    <sr>\n"
      "      <map address='00-1f:7000-7fff'/>\n"
      "      <map address='80-9f:7000-7fff'/>\n"
      "    </sr>\n"
    );
    markup.append("  </necdsp>\n");
  }

  if(has_dsp2) markup.append(
    "  <necdsp model='uPD7725' frequency='8000000' firmware='dsp2.bin' sha256='5efbdf96ed0652790855225964f3e90e6a4d466cfa64df25b110933c6cf94ea1'>\n"
    "    <dr>\n"
    "      <map address='20-3f:8000-bfff'/>\n"
    "      <map address='a0-bf:8000-bfff'/>\n"
    "    </dr>\n"
    "    <sr>\n"
    "      <map address='20-3f:c000-ffff'/>\n"
    "      <map address='a0-bf:c000-ffff'/>\n"
    "    </sr>\n"
    "  </necdsp>\n"
  );

  if(has_dsp3) markup.append(
    "  <necdsp model='uPD7725' frequency='8000000' firmware='dsp3.bin' sha256='2e635f72e4d4681148bc35429421c9b946e4f407590e74e31b93b8987b63ba90'>\n"
    "    <dr>\n"
    "      <map address='20-3f:8000-bfff'/>\n"
    "      <map address='a0-bf:8000-bfff'/>\n"
    "    </dr>\n"
    "    <sr>\n"
    "      <map address='20-3f:c000-ffff'/>\n"
    "      <map address='a0-bf:c000-ffff'/>\n"
    "    </sr>\n"
    "  </necdsp>\n"
  );

  if(has_dsp4) markup.append(
    "  <necdsp model='uPD7725' frequency='8000000' firmware='dsp4.bin' sha256='63ede17322541c191ed1fdf683872554a0a57306496afc43c59de7c01a6e764a'>\n"
    "    <dr>\n"
    "      <map address='30-3f:8000-bfff'/>\n"
    "      <map address='b0-bf:8000-bfff'/>\n"
    "    </dr>\n"
    "    <sr>\n"
    "      <map address='30-3f:c000-ffff'/>\n"
    "      <map address='b0-bf:c000-ffff'/>\n"
    "    </sr>\n"
    "  </necdsp>\n"
  );

  if(has_st010) markup.append(
    "  <necdsp model='uPD96050' frequency='10000000' firmware='st0010.bin' sha256='55c697e864562445621cdf8a7bf6e84ae91361e393d382a3704e9aa55559041e'>\n"
    "    <dr>\n"
    "      <map address='60:0000'/>\n"
    "      <map address='e0:0000'/>\n"
    "    </dr>\n"
    "    <sr>\n"
    "      <map address='60:0001'/>\n"
    "      <map address='e0:0001'/>\n"
    "    </sr>\n"
    "    <dp>\n"
    "      <map address='68-6f:0000-0fff'/>\n"
    "      <map address='e8-ef:0000-0fff'/>\n"
    "    </dp>\n"
    "  </necdsp>\n"
  );

  if(has_st011) markup.append(
    "  <necdsp model='uPD96050' frequency='15000000' firmware='st0011.bin' sha256='651b82a1e26c4fa8dd549e91e7f923012ed2ca54c1d9fd858655ab30679c2f0e'>\n"
    "    <dr>\n"
    "      <map address='60:0000'/>\n"
    "      <map address='e0:0000'/>\n"
    "    </dr>\n"
    "    <sr>\n"
    "      <map address='60:0001'/>\n"
    "      <map address='e0:0001'/>\n"
    "    </sr>\n"
    "    <dp>\n"
    "      <map address='68-6f:0000-0fff'/>\n"
    "      <map address='e8-ef:0000-0fff'/>\n"
    "    </dp>\n"
    "  </necdsp>\n"
  );

  if(has_st018) markup.append(
    "  <setarisc firmware='ST-0018'>\n"
    "    <map address='00-3f:3800-38ff'/>\n"
    "    <map address='80-bf:3800-38ff'/>\n"
    "  </setarisc>\n"
  );

  markup.append("</cartridge>\n");
}
Пример #3
0
/* read a request message, returns <0 in case of errors,
   this function closes the socket */
static void handleconnection(nssov_info *ni,int sock,Operation *op)
{
  TFILE *fp;
  int32_t action;
  struct timeval readtimeout,writetimeout;
  uid_t uid;
  gid_t gid;
  char authid[sizeof("gidNumber=4294967295+uidNumber=424967295,cn=peercred,cn=external,cn=auth")];
  char peerbuf[8];
  struct berval peerbv = { sizeof(peerbuf), peerbuf };

  /* log connection */
  if (LUTIL_GETPEEREID(sock,&uid,&gid,&peerbv))
    Debug( LDAP_DEBUG_TRACE,"nssov: connection from unknown client: %s\n",strerror(errno),0,0);
  else
    Debug( LDAP_DEBUG_TRACE,"nssov: connection from uid=%d gid=%d\n",
                      (int)uid,(int)gid,0);

  /* Should do authid mapping too */
  op->o_dn.bv_len = sprintf(authid,"gidNumber=%d+uidNumber=%d,cn=peercred,cn=external,cn=auth",
  	(int)uid, (int)gid );
  op->o_dn.bv_val = authid;
  op->o_ndn = op->o_dn;

  /* set the timeouts */
  readtimeout.tv_sec=0; /* clients should send their request quickly */
  readtimeout.tv_usec=500000;
  writetimeout.tv_sec=5; /* clients could be taking some time to process the results */
  writetimeout.tv_usec=0;
  /* create a stream object */
  if ((fp=tio_fdopen(sock,&readtimeout,&writetimeout,
                     READBUFFER_MINSIZE,READBUFFER_MAXSIZE,
                     WRITEBUFFER_MINSIZE,WRITEBUFFER_MAXSIZE))==NULL)
  {
    Debug( LDAP_DEBUG_ANY,"nssov: cannot create stream for writing: %s",strerror(errno),0,0);
    (void)close(sock);
    return;
  }
  /* read request */
  if (read_header(fp,&action))
  {
    (void)tio_close(fp);
    return;
  }
  /* handle request */
  switch (action)
  {
    case NSLCD_ACTION_ALIAS_BYNAME:     (void)nssov_alias_byname(ni,fp,op); break;
    case NSLCD_ACTION_ALIAS_ALL:        (void)nssov_alias_all(ni,fp,op); break;
    case NSLCD_ACTION_ETHER_BYNAME:     (void)nssov_ether_byname(ni,fp,op); break;
    case NSLCD_ACTION_ETHER_BYETHER:    (void)nssov_ether_byether(ni,fp,op); break;
    case NSLCD_ACTION_ETHER_ALL:        (void)nssov_ether_all(ni,fp,op); break;
    case NSLCD_ACTION_GROUP_BYNAME:     (void)nssov_group_byname(ni,fp,op); break;
    case NSLCD_ACTION_GROUP_BYGID:      (void)nssov_group_bygid(ni,fp,op); break;
    case NSLCD_ACTION_GROUP_BYMEMBER:   (void)nssov_group_bymember(ni,fp,op); break;
    case NSLCD_ACTION_GROUP_ALL:        (void)nssov_group_all(ni,fp,op); break;
    case NSLCD_ACTION_HOST_BYNAME:      (void)nssov_host_byname(ni,fp,op); break;
    case NSLCD_ACTION_HOST_BYADDR:      (void)nssov_host_byaddr(ni,fp,op); break;
    case NSLCD_ACTION_HOST_ALL:         (void)nssov_host_all(ni,fp,op); break;
    case NSLCD_ACTION_NETGROUP_BYNAME:  (void)nssov_netgroup_byname(ni,fp,op); break;
    case NSLCD_ACTION_NETWORK_BYNAME:   (void)nssov_network_byname(ni,fp,op); break;
    case NSLCD_ACTION_NETWORK_BYADDR:   (void)nssov_network_byaddr(ni,fp,op); break;
    case NSLCD_ACTION_NETWORK_ALL:      (void)nssov_network_all(ni,fp,op); break;
    case NSLCD_ACTION_PASSWD_BYNAME:    (void)nssov_passwd_byname(ni,fp,op); break;
    case NSLCD_ACTION_PASSWD_BYUID:     (void)nssov_passwd_byuid(ni,fp,op); break;
    case NSLCD_ACTION_PASSWD_ALL:       (void)nssov_passwd_all(ni,fp,op); break;
    case NSLCD_ACTION_PROTOCOL_BYNAME:  (void)nssov_protocol_byname(ni,fp,op); break;
    case NSLCD_ACTION_PROTOCOL_BYNUMBER:(void)nssov_protocol_bynumber(ni,fp,op); break;
    case NSLCD_ACTION_PROTOCOL_ALL:     (void)nssov_protocol_all(ni,fp,op); break;
    case NSLCD_ACTION_RPC_BYNAME:       (void)nssov_rpc_byname(ni,fp,op); break;
    case NSLCD_ACTION_RPC_BYNUMBER:     (void)nssov_rpc_bynumber(ni,fp,op); break;
    case NSLCD_ACTION_RPC_ALL:          (void)nssov_rpc_all(ni,fp,op); break;
    case NSLCD_ACTION_SERVICE_BYNAME:   (void)nssov_service_byname(ni,fp,op); break;
    case NSLCD_ACTION_SERVICE_BYNUMBER: (void)nssov_service_bynumber(ni,fp,op); break;
    case NSLCD_ACTION_SERVICE_ALL:      (void)nssov_service_all(ni,fp,op); break;
    case NSLCD_ACTION_SHADOW_BYNAME:    if (uid==0) (void)nssov_shadow_byname(ni,fp,op); break;
    case NSLCD_ACTION_SHADOW_ALL:       if (uid==0) (void)nssov_shadow_all(ni,fp,op); break;
	case NSLCD_ACTION_PAM_AUTHC:		(void)pam_authc(ni,fp,op); break;
	case NSLCD_ACTION_PAM_AUTHZ:		(void)pam_authz(ni,fp,op); break;
	case NSLCD_ACTION_PAM_SESS_O:		if (uid==0) (void)pam_sess_o(ni,fp,op); break;
	case NSLCD_ACTION_PAM_SESS_C:		if (uid==0) (void)pam_sess_c(ni,fp,op); break;
	case NSLCD_ACTION_PAM_PWMOD:		(void)pam_pwmod(ni,fp,op); break;
    default:
      Debug( LDAP_DEBUG_ANY,"nssov: invalid request id: %d",(int)action,0,0);
      break;
  }
  /* we're done with the request */
  (void)tio_close(fp);
  return;
}
Пример #4
0
long setup_star_read_ztilt(STAR_S *star, int nstar, const PARMS_S *parms, int seed){
    const double ngsgrid=parms->maos.ngsgrid;
    long nstep=0;
    TIC;tic;
    for(int istar=0; istar<nstar; istar++){
	STAR_S *stari=&star[istar];
	int npowfs=parms->maos.npowfs;
	stari->ztiltout=dcellnew(npowfs, 1);
	const double thetax=stari->thetax*206265;/*in as */
	const double thetay=stari->thetay*206265;

	double thxnorm=thetax/ngsgrid;
	double thynorm=thetay/ngsgrid;
	long thxl=(long)floor(thxnorm);/*Used to be double, but -0 appears. */
	long thyl=(long)floor(thynorm);
	double wtx=thxnorm-thxl;
	double wty=thynorm-thyl;
	for(int ipowfs=0; ipowfs<npowfs; ipowfs++){
	    const int msa=parms->maos.msa[ipowfs];
	    const int nsa=parms->maos.nsa[ipowfs];
	    const int ng=nsa*2;
	    char *fnztilt[2][2]={{NULL,NULL},{NULL,NULL}};
	    char *fngoff[2][2]={{NULL, NULL}, {NULL, NULL}};
	    double wtsum=0;
	    for(int ix=0; ix<2; ix++){
		double thx=(thxl+ix)*ngsgrid;
		for(int iy=0; iy<2; iy++){
		    double thy=(thyl+iy)*ngsgrid;
		    double wtxi=fabs(((1-ix)-wtx)*((1-iy)-wty));

		    if(wtxi<0.01){
			/*info("skipping ix=%d,iy=%d because wt=%g\n",ix,iy,wtxi); */
			continue;
		    }
		    fnztilt[iy][ix]=myalloca(PATH_MAX, char);
		    if(parms->skyc.usephygrad){
			warning_once("Using phygrad\n");
			snprintf(fnztilt[iy][ix],PATH_MAX,"%s/phygrad/phygrad_seed%d_sa%d_x%g_y%g",
				 dirstart,seed,msa,thx,thy);
		    }else{
			snprintf(fnztilt[iy][ix],PATH_MAX,"%s/ztiltout/ztiltout_seed%d_sa%d_x%g_y%g",
				 dirstart,seed,msa,thx,thy);
		    }
		    fngoff[iy][ix]=myalloca(PATH_MAX, char);
		    snprintf(fngoff[iy][ix],PATH_MAX,"%s/gradoff/gradoff_sa%d_x%g_y%g",
			     dirstart,msa,thx,thy);
		    if(!zfexist(fnztilt[iy][ix])){
			//warning("%s doesnot exist\n",fnwvf[iy][ix]);
			fnztilt[iy][ix]=fngoff[iy][ix]=NULL;
		    }else{
			wtsum+=wtxi;
		    }
		}
	    }
	    if(wtsum<0.01){
		error("PSF is not available for (%g,%g). wtsum=%g\n",thetax,thetay, wtsum);
	    }
	    /*Now do the actual reading */
	    for(int ix=0; ix<2; ix++){
		for(int iy=0; iy<2; iy++){
		    double wtxi=fabs(((1-ix)-wtx)*((1-iy)-wty))/wtsum;
		    if(fnztilt[iy][ix]){
			file_t *fp_ztilt=zfopen(fnztilt[iy][ix],"rb");
			header_t header={0,0,0,0};
			read_header(&header, fp_ztilt);
			
			if(iscell(&header.magic)){
			    // error("expected data type: %u, got %u\n",(uint32_t)MCC_ANY, header.magic);
			    nstep=header.nx;
			    free(header.str);
			    if(stari->nstep==0){
				stari->nstep=nstep;
			    }else{
				if(stari->nstep!=nstep){
				    error("Different type has different steps\n");
				}
			    }
			    if(!stari->ztiltout->p[ipowfs]){
				stari->ztiltout->p[ipowfs]=dnew(ng, nstep);
			    }
			    dmat  *ztiltout=stari->ztiltout->p[ipowfs];
			    for(long istep=0; istep<nstep; istep++){
				dmat *ztilti=dreaddata(fp_ztilt, 0);
				for(int ig=0; ig<ng; ig++){
				    ztiltout->p[ig+istep*ng]+=ztilti->p[ig]*wtxi;
				}
				dfree(ztilti);
			    }
			}else{
			    dmat *tmp=dreaddata(fp_ztilt, &header);
			    dadd(&stari->ztiltout->p[ipowfs], 1, tmp, wtxi );
			    dfree(tmp);
			}
			zfclose(fp_ztilt);
		    }/* if(fnwvf) */
		    if(fngoff[iy][ix] && zfexist(fngoff[iy][ix])){
			if(!stari->goff){
			    stari->goff=dcellnew(npowfs, 1);
			}
			dmat *tmp=dread("%s", fngoff[iy][ix]);
			dadd(&stari->goff->p[ipowfs], 1, tmp, wtxi);
			dfree(tmp);
		    }
		}/*iy */
	    }/*ix */
	}/*ipowfs */
    }/*istar */
    if(parms->skyc.verbose){
	toc2("Reading PSF");
    }
    //close(fd);
    return nstep;
}
Пример #5
0
/*---------------------------------------------------------------------------*/
static coffee_page_t
get_sector_status(uint16_t sector, struct sector_status *stats)
{
  static coffee_page_t skip_pages;
  static char last_pages_are_active;
  struct file_header hdr;
  coffee_page_t active, obsolete, free;
  coffee_page_t sector_start, sector_end;
  coffee_page_t page;

  memset(stats, 0, sizeof(*stats));
  active = obsolete = free = 0;

  /*
   * get_sector_status() is an iterative function using local static 
   * state. It therefore requires the the caller loops starts from 
   * sector 0 in order to reset the internal state.
   */
  if(sector == 0) {
    skip_pages = 0;
    last_pages_are_active = 0;
  }

  sector_start = sector * COFFEE_PAGES_PER_SECTOR;
  sector_end = sector_start + COFFEE_PAGES_PER_SECTOR;

  /*
   * Account for pages belonging to a file starting in a previous 
   * segment that extends into this segment. If the whole segment is 
   * covered, we do not need to continue counting pages in this iteration.
   */
  if(last_pages_are_active) {
    if(skip_pages >= COFFEE_PAGES_PER_SECTOR) {
      stats->active = COFFEE_PAGES_PER_SECTOR;
      skip_pages -= COFFEE_PAGES_PER_SECTOR;
      return 0;
    }
    active = skip_pages;
  } else {
    if(skip_pages >= COFFEE_PAGES_PER_SECTOR) {
      stats->obsolete = COFFEE_PAGES_PER_SECTOR;
      skip_pages -= COFFEE_PAGES_PER_SECTOR;
      return skip_pages >= COFFEE_PAGES_PER_SECTOR ? 0 : skip_pages;
    }
    obsolete = skip_pages;
  }

  /* Determine the amount of pages of each type that have not been 
     accounted for yet in the current sector. */
  for(page = sector_start + skip_pages; page < sector_end;) {
    read_header(&hdr, page);
    last_pages_are_active = 0;
    if(HDR_ACTIVE(hdr)) {
      last_pages_are_active = 1;
      page += hdr.max_pages;
      active += hdr.max_pages;
    } else if(HDR_ISOLATED(hdr)) {
      page++;
      obsolete++;
    } else if(HDR_OBSOLETE(hdr)) {
      page += hdr.max_pages;
      obsolete += hdr.max_pages;
    } else {
      free = sector_end - page;
      break;
    }
  }

  /*
   * Determine the amount of pages in the following sectors that
   * should be remembered for the next iteration. This is necessary 
   * because no page except the first of a file contains information 
   * about what type of page it is. A side effect of remembering this
   * amount is that there is no need to read in the headers of each 
   * of these pages from the storage.
   */
  skip_pages = active + obsolete + free - COFFEE_PAGES_PER_SECTOR;
  if(skip_pages > 0) {
    if(last_pages_are_active) {
      active = COFFEE_PAGES_PER_SECTOR - obsolete;
    } else {
      obsolete = COFFEE_PAGES_PER_SECTOR - active;
    }
  }

  stats->active = active;
  stats->obsolete = obsolete;
  stats->free = free;

  /*
   * To avoid unnecessary page isolation, we notify the callee that 
   * "skip_pages" pages should be isolated only if the current file extent 
   * ends in the next sector. If the file extent ends in a more distant 
   * sector, however, the garbage collection can free the next sector 
   * immediately without requiring page isolation. 
   */
  return (last_pages_are_active || (skip_pages >= COFFEE_PAGES_PER_SECTOR)) ?
	0 : skip_pages;
}
Пример #6
0
static int
write_log_page(struct file *file, struct log_param *lp)
{
  struct file_header hdr;
  uint16_t region;
  coffee_page_t log_page;
  int16_t log_record;
  uint16_t log_record_size;
  uint16_t log_records;
  cfs_offset_t offset;
  struct log_param lp_out;

  read_header(&hdr, file->page);

  adjust_log_config(&hdr, &log_record_size, &log_records);
  region = modify_log_buffer(log_record_size, &lp->offset, &lp->size);

  log_page = 0;
  if(HDR_MODIFIED(hdr)) {
    /* A log structure has already been created. */
    log_page = hdr.log_page;
    log_record = find_next_record(file, log_page, log_records);
    if(log_record >= log_records) {
      /* The log is full; merge the log. */
      PRINTF("Coffee: Merging the file %s with its log\n", hdr.name);
      return merge_log(file->page, 0);
    }
  } else {
    /* Create a log structure. */
    log_page = create_log(file, &hdr);
    if(log_page == INVALID_PAGE) {
      return -1;
    }
    PRINTF("Coffee: Created a log structure for file %s at page %u\n",
    	hdr.name, (unsigned)log_page);
    hdr.log_page = log_page;
    log_record = 0;
  }

  {
    char copy_buf[COFFEE_PAGE_SIZE];

    lp_out.offset = offset = region * log_record_size;
    lp_out.buf = copy_buf;
    lp_out.size = log_record_size;

    if((lp->offset > 0 || lp->size != log_record_size) &&
	read_log_page(&hdr, log_record, &lp_out) < 0) {
      COFFEE_READ(copy_buf, sizeof(copy_buf),
	  absolute_offset(file->page, offset));
    }

    memcpy(&copy_buf[lp->offset], lp->buf, lp->size);

    /*
     * Write the region number in the region index table.
     * The region number is incremented to avoid values of zero.
     */
    offset = absolute_offset(log_page, 0);
    ++region;
    COFFEE_WRITE(&region, sizeof(region),
		 offset + log_record * sizeof(region));

    offset += log_records * sizeof(region);
    COFFEE_WRITE(copy_buf, sizeof(copy_buf),
		 offset + log_record * log_record_size);
    file->record_count = log_record + 1;
  }

  return lp->size;
}
Пример #7
0
cell *readdata_by_id(file_t *fp, uint32_t id, int level, header_t *header){
    header_t header2={0};
    if(!header){
	header=&header2;
	read_header(header, fp);
    }
    void *out=0;
    if(level<0 && !iscell(&header->magic)){
	level=0;
    }
    if(zfisfits(fp) || level==0){
	switch(level){
	case 0:/*read a mat*/
	    if(!id) id=header->magic;
	    switch(id){
	    case M_DBL: 
	    case M_FLT:
		out=dreaddata(fp, header);break;
	    case M_CMP: 
	    case M_ZMP:
		out=creaddata(fp, header);break;
	    case M_LONG: out=lreaddata(fp, header);break;
	    case M_LOC64: out=locreaddata(fp, header); break;
	    case M_MAP64: out=mapreaddata(fp, header); break;
	    case M_DSP32: case M_DSP64: /**Possible to read mismatched integer*/
		out=dspreaddata(fp, header);break;
	    case M_SSP32: case M_SSP64:
		out=sspreaddata(fp, header);break;
	    case M_CSP32: case M_CSP64:
		out=cspreaddata(fp, header);break;
	    case M_ZSP64: case M_ZSP32:
		out=zspreaddata(fp, header);break;	
	    default:error("data type id=%u not supported\n", id);
	    }
	    break;
	case 1:{/*read a cell from fits*/
	    int maxlen=10;
	    void **tmp=malloc(maxlen*sizeof(void*));
	    int nx=0;
	    do{
		if(nx>=maxlen){
		    maxlen*=2;
		    tmp=realloc(tmp, sizeof(void*)*maxlen);
		}
		tmp[nx++]=readdata_by_id(fp, id, 0, header);
		free(header->str);header->str=0;
	    }while(!read_header2(header, fp));
	    cell *dcout=cellnew(nx, 1);
	    memcpy(dcout->p, tmp, sizeof(void*)*nx);
	    free(tmp);
	    out=dcout;
	}
	    break;
	default:
	    error("Only support zero or one level of cell when reading fits file\n");
	}
    }else{
	if(!iscell(&header->magic)){
	    //wrap array into cell
	    info2("Read cell from non cell data\n");
	    cell *dcout=cellnew(1,1);
	    dcout->p[0]=readdata_by_id(fp, id, level-1, header);
	    out=dcout;
	}else{
	    long nx=header->nx;
	    long ny=header->ny;
	    cell *dcout=cellnew(nx, ny);
	    dcout->header=header->str; header->str=0;
	    for(long i=0; i<nx*ny; i++){
		dcout->p[i]=readdata_by_id(fp, id, level-1, 0);
	    }
	    out=dcout;
	}
    }
    free(header->str);header->str=0;
    return out;
}
Пример #8
0
dt_imageio_retval_t dt_imageio_open_png(dt_image_t *img, const char *filename, dt_mipmap_buffer_t *mbuf)
{
  const char *ext = filename + strlen(filename);
  while(*ext != '.' && ext > filename) ext--;
  if(strncmp(ext, ".png", 4) && strncmp(ext, ".PNG", 4)) return DT_IMAGEIO_FILE_CORRUPTED;
  if(!img->exif_inited) (void)dt_exif_read(img, filename);

  dt_imageio_png_t image;
  uint8_t *buf = NULL;
  uint32_t width, height;
  uint16_t bpp;


  if(read_header(filename, &image) != 0) return DT_IMAGEIO_FILE_CORRUPTED;

  width = img->width = image.width;
  height = img->height = image.height;
  bpp = image.bit_depth;

  img->bpp = 4 * sizeof(float);

  float *mipbuf = (float *)dt_mipmap_cache_alloc(mbuf, img);
  if(!mipbuf)
  {
    fclose(image.f);
    png_destroy_read_struct(&image.png_ptr, NULL, NULL);
    fprintf(stderr, "[png_open] could not alloc full buffer for image `%s'\n", img->filename);
    return DT_IMAGEIO_CACHE_FULL;
  }

  buf = dt_alloc_align(16, (size_t)width * height * 3 * (bpp < 16 ? 1 : 2));
  if(!buf)
  {
    fclose(image.f);
    png_destroy_read_struct(&image.png_ptr, NULL, NULL);
    fprintf(stderr, "[png_open] could not alloc intermediate buffer for image `%s'\n", img->filename);
    return DT_IMAGEIO_CACHE_FULL;
  }

  if(read_image(&image, (void *)buf) != 0)
  {
    dt_free_align(buf);
    fprintf(stderr, "[png_open] could not read image `%s'\n", img->filename);
    return DT_IMAGEIO_FILE_CORRUPTED;
  }

  for(size_t j = 0; j < height; j++)
  {
    if(bpp < 16)
      for(size_t i = 0; i < width; i++)
        for(int k = 0; k < 3; k++)
          mipbuf[4 * (j * width + i) + k] = buf[3 * (j * width + i) + k] * (1.0f / 255.0f);
    else
      for(size_t i = 0; i < width; i++)
        for(int k = 0; k < 3; k++)
          mipbuf[4 * (j * width + i) + k] = (256.0f * buf[2 * (3 * (j * width + i) + k)]
                                             + buf[2 * (3 * (j * width + i) + k) + 1]) * (1.0f / 65535.0f);
  }

  dt_free_align(buf);
  return DT_IMAGEIO_OK;
}
Пример #9
0
/**
 * Downloads the contents of a URL to memory
 * This method is not threadsafe (because networking is not threadsafe on the Wii)
 */
struct block downloadfile(const char *url)
{
	int sslcontext = -1;

	//Check if the url starts with "http://", if not it is not considered a valid url
	if (strncmp(url, "http://", strlen("http://")) == 0)
		http_port = 80;
	else if(strncmp(url, "https://", strlen("https://")) == 0)
	{
		http_port = 443;
		gprintf("Initializing ssl...\n");
		if(ssl_init() < 0)
			return emptyblock;
	}
	else
		return emptyblock;

	//Locate the path part of the url by searching for '/' past "http://"
	char *path = 0;
	if(http_port == 443)
		path = strchr(url + strlen("https://"), '/');
	else
		path = strchr(url + strlen("http://"), '/');

	//At the very least the url has to end with '/', ending with just a domain is invalid
	if (path == NULL)
	{
		//printf("URL '%s' has no PATH part\n", url);
		return emptyblock;
	}

	//Extract the domain part out of the url
	int domainlength = path - url - strlen("http://") - (http_port == 443 ? 1 : 0);

	if (domainlength == 0)
	{
		//printf("No domain part in URL '%s'\n", url);
		return emptyblock;
	}

	char domain[domainlength + 1];
	strlcpy(domain, url + strlen("http://") + (http_port == 443 ? 1 : 0), domainlength + 1);

	//Parsing of the URL is done, start making an actual connection
	u32 ipaddress = getipbynamecached(domain);

	if (ipaddress == 0)
	{
		//printf("\ndomain %s could not be resolved", domain);
		return emptyblock;
	}

	s32 connection = tcp_connect(ipaddress, http_port);

	if (connection < 0)
	{
		//printf("Error establishing connection");
		return emptyblock;
	}

	if(http_port == 443)
	{
		//patched out anyways so just to set something
		sslcontext = ssl_new((u8*)domain,0);

		if(sslcontext < 0)
		{
			//gprintf("ssl_new\n");
			result = HTTPR_ERR_CONNECT;
			net_close (connection);
			return emptyblock;
		}
		//patched out anyways so just to set something
		ssl_setbuiltinclientcert(sslcontext,0);
		if(ssl_connect(sslcontext,connection) < 0)
		{
			//gprintf("ssl_connect\n");
			result = HTTPR_ERR_CONNECT;
			ssl_shutdown(sslcontext);
			net_close (connection);
			return emptyblock;
		}
		int ret = ssl_handshake(sslcontext);
		if(ret < 0)
		{
			//gprintf("ssl_handshake %i\n", ret);
			result = HTTPR_ERR_STATUS;
			ssl_shutdown(sslcontext);
			net_close (connection);
			return emptyblock;
		}
	}

	// Remove Referer from the request header for incompatible websites (ex. Cloudflare proxy)
	char referer[domainlength + 12];
	snprintf(referer, sizeof(referer), "Referer: %s\r\n", domain);
	if(strstr(url, "geckocodes"))
	{
		strcpy(referer, "");
	}

	//Form a nice request header to send to the webserver
	char* headerformat = "GET %s HTTP/1.0\r\nHost: %s\r\n%sUser-Agent: USBLoaderGX r%s\r\n\r\n";
	char header[strlen(headerformat) + strlen(path) + strlen(domain) + strlen(referer) + 100];
	sprintf(header, headerformat, path, domain, referer, GetRev());
	//gprintf("\nHTTP Request:\n");
	//gprintf("%s\n",header);

	//Do the request and get the response
	tcp_write(http_port == 443 ? sslcontext : connection, header);
	read_header( http_port == 443 ? sslcontext : connection);

	if (http_status >= 400) // Not found
	{
		//gprintf("HTTP ERROR: %d\n", http_status);
		return emptyblock;
	}

	if(!content_length)
		content_length = 0;

	// create data buffer to return
	struct block response;
	response.data = malloc(content_length);
	response.size = content_length;
	if (response.data == NULL)
	{
		return emptyblock;
	}

	if (http_status == 200)
	{
		if(displayProgressWindow)
		{
			ProgressCancelEnable(true);
			StartProgress(tr("Downloading file..."), tr("Please wait"), 0, false, false);
		}

		int ret = tcp_readData(http_port == 443 ? sslcontext : connection, &response.data, content_length);
		if(!ret)
		{
			free(response.data);
			result = HTTPR_ERR_RECEIVE;
			if(http_port == 443)
				ssl_shutdown(sslcontext);
			net_close (connection);
			return emptyblock;
		}
	}
	else if (http_status == 302) // 302 FOUND (redirected link)
	{
		// close current connection
		if(http_port == 443)
			ssl_shutdown(sslcontext);
		net_close (connection);

		// prevent infinite loops
		retryloop++;
		if(retryloop > 3)
		{
			retryloop = 0;
			return emptyblock;
		}

		struct block redirected = downloadfile(content_location);
		if(redirected.size == 0)
			return emptyblock;

		// copy the newURL data into the original data
		u8 * tmp = realloc(response.data, redirected.size);
		if (tmp == NULL)
		{
			gprintf("Could not allocate enough memory for new URL. Download canceled.\n");
			free(response.data);
			response.size = 0;
			free(redirected.data);
			result = HTTPR_ERR_RECEIVE;
			if(http_port == 443)
				ssl_shutdown(sslcontext);
			net_close (connection);
			return emptyblock;
		}
		response.data = tmp;
		memcpy(response.data, redirected.data, redirected.size);
		free(redirected.data);
		response.size = redirected.size;

	}
	retryloop = 0;
	
	// reset progress window if used
	if(displayProgressWindow)
	{
		ProgressStop();
		ProgressCancelEnable(false);
		displayProgressWindow = false;
	}

	return response;
}
Пример #10
0
int load_pic(char *name)
{
  FILE *fd = fopen(name, "rb");
  Uint32 type;

  /* Couldn't open */
  if (!fd) return 0;

  type = read_header(fd);

  /* Not an IFF file */
  if (!type)
  {
    fclose(fd);
    return 0;
  }

  switch(type)
  {
    case PBM:
    {
      if (find_chunk(fd, BMHD))
      {
        Uint16 sizex = freadhe16(fd);
        Uint16 sizey = freadhe16(fd);
        Uint8 compression;
        int colors = 256;
        Uint32 bodylength;

        /*
         * Hop over the "hotspot", planes & masking (stencil pictures are
         * always saved as ILBMs!
         */
        fseek(fd, 6, SEEK_CUR);
        compression = fread8(fd);
        fread8(fd);
        fread8(fd);
        fread8(fd);
        /*
         * That was all we needed of the BMHD, now the CMAP (optional hehe!)
         */
        if (find_chunk(fd, CMAP))
        {
          int count;
          for (count = 0; count < colors; count++)
          {
            sc.red[count] = fread8(fd) >> 2;
            sc.green[count] = fread8(fd) >> 2;
            sc.blue[count] = fread8(fd) >> 2;
          }
        }
        /*
         * Now the BODY chunk, this is important!
         */
        bodylength = find_chunk(fd, BODY);

        if (bodylength)
        {
          sc.sizex = sizex;
          sc.sizey = sizey;
          sc.data = malloc(sc.sizex * sc.sizey);
          if (!sc.data)
          {
            fclose(fd);
            return 0;
          }
          if (!compression)
          {
            int ycount;
            for (ycount = 0; ycount < sizey; ycount++)
            {
              fread(&sc.data[sc.sizex * ycount], sizex, 1, fd);
            }
          }
          else
          {
            int ycount;

            char *ptr = malloc(bodylength);
            char *origptr = ptr;
            if (!ptr)
            {
              fclose(fd);
              return 0;
            }

            fread(ptr, bodylength, 1, fd);

            /* Run-length encoding */
            for (ycount = 0; ycount < sizey; ycount++)
            {
              int total = 0;
              while (total < sizex)
              {
                signed char decision = *ptr++;
                if (decision >= 0)
                {
                  memcpy(&sc.data[sc.sizex * ycount + total], ptr, decision + 1);
                  ptr += decision + 1;
                  total += decision + 1;
                }
                if ((decision < 0) && (decision != -128))
                {
                  memset(&sc.data[sc.sizex * ycount + total], *ptr++, -decision + 1);
                  total += -decision + 1;
                }
              }
            }
            free(origptr);
          }
        }
      }
    }
    break;

    case ILBM:
    {
      if (find_chunk(fd, BMHD))
      {
        Uint16 sizex = freadhe16(fd);
        Uint16 sizey = freadhe16(fd);
        Uint8 compression;
        Uint8 planes;
        Uint8 mask;
        int colors;
        Uint32 bodylength;

        /*
         * Hop over the "hotspot"
         */
        fseek(fd, 4, SEEK_CUR);
        planes = fread8(fd);
        mask = fread8(fd);
        compression = fread8(fd);
        fread8(fd);
        fread8(fd);
        fread8(fd);
        colors = poweroftwo[planes];
        if (mask > 1) mask = 0;
        /*
         * That was all we needed of the BMHD, now the CMAP (optional hehe!)
         */
        if (find_chunk(fd, CMAP))
        {
          int count;
          for (count = 0; count < 256; count++)
          {
            sc.red[count] = 0;
            sc.green[count] = 0;
            sc.blue[count] = 0;
          }
          sc.red[255] = 255;
          sc.green[255] = 255;
          sc.blue[255] = 255;
          for (count = 0; count < colors; count++)
          {
            sc.red[count] = fread8(fd) >> 2;
            sc.green[count] = fread8(fd) >> 2;
            sc.blue[count] = fread8(fd) >> 2;
          }
        }
        /*
         * Now the BODY chunk, this is important!
         */
        bodylength = find_chunk(fd, BODY);

        if (bodylength)
        {
          char *ptr;
          char *origptr;
          char *unpackedptr;
          char *workptr;
          int ycount, plane;
          int bytes, dbytes;

          sc.sizex = sizex;
          sc.sizey = sizey;
          sc.data = malloc(sc.sizex * sc.sizey);
          memset(sc.data, 0, sc.sizex * sc.sizey);
          if (!sc.data)
          {
            fclose(fd);
            return 0;
          }
          origptr = malloc(bodylength * 2);
          ptr = origptr;
          if (!origptr)
          {
            fclose(fd);
            return 0;
          }
          fread(origptr, bodylength, 1, fd);
          if (compression)
          {
            dbytes = sizey * (planes + mask) * ((sizex + 7) / 8);
            unpackedptr = malloc(dbytes);
            workptr = unpackedptr;
            if (!unpackedptr)
          {
        fclose(fd);
        return 0;
      }
            bytes = 0;
            while (bytes < dbytes)
            {
              signed char decision = *ptr++;
              if (decision >= 0)
              {
                memcpy(workptr, ptr, decision + 1);
                workptr += decision + 1;
                ptr += decision + 1;
                bytes += decision + 1;
              }
              if ((decision < 0) && (decision != -128))
              {
                memset(workptr, *ptr++, -decision + 1);
                workptr += -decision + 1;
                bytes += -decision + 1;
              }
            }
            free(origptr);
            origptr = unpackedptr;
            ptr = unpackedptr;
          }
          for (ycount = 0; ycount < sizey; ycount++)
          {
            for (plane = 0; plane < planes; plane++)
            {
              int xcount = (sizex + 7) / 8;
              int xcoord = 0;
              while (xcount)
              {
                if (*ptr & 128) sc.data[sc.sizex * ycount + xcoord + 0] |= poweroftwo[plane];
                if (*ptr & 64 ) sc.data[sc.sizex * ycount + xcoord + 1] |= poweroftwo[plane];
                if (*ptr & 32 ) sc.data[sc.sizex * ycount + xcoord + 2] |= poweroftwo[plane];
                if (*ptr & 16 ) sc.data[sc.sizex * ycount + xcoord + 3] |= poweroftwo[plane];
                if (*ptr & 8  ) sc.data[sc.sizex * ycount + xcoord + 4] |= poweroftwo[plane];
                if (*ptr & 4  ) sc.data[sc.sizex * ycount + xcoord + 5] |= poweroftwo[plane];
                if (*ptr & 2  ) sc.data[sc.sizex * ycount + xcoord + 6] |= poweroftwo[plane];
                if (*ptr & 1  ) sc.data[sc.sizex * ycount + xcoord + 7] |= poweroftwo[plane];
                ptr++;
                xcoord += 8;
                xcount--;
              }
            }
            if (mask)
            {
              ptr += (sizex + 7) / 8;
            }
          }
          free(origptr);
        }
      }
    }
    break;
  }
  fclose(fd);
  return 1;
}
Пример #11
0
int main( int ac, char** av )
{
    try
    {
        comma::command_line_options options( ac, av, usage );
        if( ac < 2 ) { usage(); }
        if( options.exists( "--output-fields" ) )
        {
            std::string s = options.value< std::string >( "--output-fields" );
            unsigned int type = s.empty() || s == "-" ? read_header( std::cin ).point_data_format() : boost::lexical_cast< unsigned int >( s );
            switch( type )
            {
                case 1:
                    std::cout << comma::join( comma::csv::names< point< 1 > >( false ), ',' ) << std::endl;
                    return 0;
                case 0:
                case 2:
                case 3:
                case 4:
                case 5:
                    std::cerr << "las-to-csv: output fields for point data format " << type << ": todo" << std::endl;
                    return 1;
                default:
                    std::cerr << "las-to-csv: expected point data format between 0 and 5, got: " << type << std::endl;
                    return 1;
            }
            return 0;
        }
        std::string what = av[1];
        snark::las::header header = read_header( std::cin );
        if( what == "header" ) { comma::write_json( header, std::cout ); return 0; }
        if( what == "points" )
        {
            std::vector< char > offset( header.offset_to_point_data() - header.header_size() );
            std::cin.read( &offset[0], offset.size() );
            int count = std::cin.gcount();
            if( count < int( offset.size() ) ) { std::cerr << "las-to-csv: expected " << offset.size() << " bytes, got only: " << count << std::endl; return 1; }
            switch( header.point_data_format() )
            {
                case 1:
                    return read_points< 1 >( header, comma::csv::options( options ) );
                case 0:
                case 2:
                case 3:
                case 4:
                case 5:
                    std::cerr << "las-to-csv: point data format " << header.point_data_format() << ": todo" << std::endl;
                    return 1;
                default:
                    std::cerr << "las-to-csv: expected point data format between 0 and 5, got: " << header.point_data_format() << std::endl;
                    return 1;
            }
            return 0;
        }
        std::cerr << "las-to-csv: expected operation, got: \"" << what << "\"" << std::endl;
        return 1;
    }
    catch( std::exception& ex )
    {
        std::cerr << "las-to-csv: " << ex.what() << std::endl;
    }
    catch( ... )
    {
        std::cerr << "las-to-csv: unknown exception" << std::endl;
    }
    return 1;
}
Пример #12
0
/* Test that fill_header generate right header
 * Test header and packet are right size header=8 packet=1024
 * Test fill_packet generate right packet
 * Test read_header return right header data structure
 * Test read_packet reads correct amount of payload*/
int main(int argc, char *argv[])
{
	init_test(argc,argv);
	assert(sizeof(header_t)==8);
	assert(sizeof(packet_t)==1024);
	packet_t test_packet;
	header_t test_header;
	/* Test write and read header */
	/* fill_header fills buf with header */
	fill_header(100,200,333,ACK,&test_packet);
	/* We have empty test_header, read data in buf and assign it to test_heaer */
	read_header(&test_header,&test_packet);
	assert(test_header.seq==100);
	assert(test_header.ack==200);
	assert(test_header.offset==333);
	assert(test_header.flag==ACK);
	/* Test write and read payload */
	/* Initial send buffer */
	u_char sender_buf[2048],recv_buf[2048];
	memset(recv_buf,0,2048);
	u_char * psend=sender_buf;
	u_char * precv=recv_buf;
	int i;
	for (i=0;i<1016;i++)
	{
		sender_buf[i]=5;
	}
	for (i=1016;i<2032;i++)
	{
		sender_buf[i]=6;
	}
	for (i=2032;i<2048;i++)
	{
		sender_buf[i]=7;
	}
	/* Send 1016 bytes payload packet */
	fill_packet(psend,&test_packet,PAYLOAD_SIZE);
	/* Suppose we send test_packet...... */
	/* OK, Now we receive new data, cast it into test_packet */
	read_packet(precv,&test_packet,PAYLOAD_SIZE);
	for (i=0;i<1016;i++)
	{
		assert(recv_buf[i]==5);
	}
	psend+=PAYLOAD_SIZE;
	precv+=PAYLOAD_SIZE;
	fill_packet(psend,&test_packet,PAYLOAD_SIZE);
	read_packet(precv,&test_packet,PAYLOAD_SIZE);
	for (i=1016;i<2032;i++)
	{
		assert(recv_buf[i]==6);
	}
	psend+=PAYLOAD_SIZE;
	precv+=PAYLOAD_SIZE;
	fill_packet(psend,&test_packet,16);
	read_packet(precv,&test_packet,16);
	for (i=2032;i<2048;i++)
	{
		assert(recv_buf[i]==7);
	}

	return 0;
}
Пример #13
0
/**
   Read in asterism WFS wvf.*/
long setup_star_read_wvf(STAR_S *star, int nstar, const PARMS_S *parms, int seed){
    const double ngsgrid=parms->maos.ngsgrid;
    const int nwvl=parms->maos.nwvl;
    long nstep=0;
    TIC;tic;
    for(int istar=0; istar<nstar; istar++){
	STAR_S *stari=&star[istar];
	int npowfs=parms->maos.npowfs;
	stari->wvfout=mycalloc(npowfs,ccell**);
	const double thetax=stari->thetax*206265;/*in as */
	const double thetay=stari->thetay*206265;

	double thxnorm=thetax/ngsgrid;
	double thynorm=thetay/ngsgrid;
	long thxl=(long)floor(thxnorm);/*Used to be double, but -0 appears. */
	long thyl=(long)floor(thynorm);
	double wtx=thxnorm-thxl;
	double wty=thynorm-thyl;
	for(int ipowfs=0; ipowfs<npowfs; ipowfs++){
	    const int msa=parms->maos.msa[ipowfs];
	    const int nsa=parms->maos.nsa[ipowfs];
	    if(stari->use[ipowfs]==0){
		continue;
	    }
	    char *fnwvf[2][2]={{NULL,NULL},{NULL,NULL}};
	    PISTAT_S *pistati=&stari->pistat[ipowfs];
	    
	    /*info2("Reading PSF for (%5.1f, %5.1f), ipowfs=%d\n",thetax,thetay,ipowfs); */
	    double wtsum=0;
	    for(int ix=0; ix<2; ix++){
		double thx=(thxl+ix)*ngsgrid;
		for(int iy=0; iy<2; iy++){
		    double thy=(thyl+iy)*ngsgrid;
		    double wtxi=fabs(((1-ix)-wtx)*((1-iy)-wty));

		    if(wtxi<0.01){
			/*info("skipping ix=%d,iy=%d because wt=%g\n",ix,iy,wtxi); */
			continue;
		    }
		    fnwvf[iy][ix]=myalloca(PATH_MAX, char);
		    snprintf(fnwvf[iy][ix],PATH_MAX,"%s/wvfout/wvfout_seed%d_sa%d_x%g_y%g",
			     dirstart,seed,msa,thx,thy);
	
		    if(!zfexist(fnwvf[iy][ix])){
			//warning("%s doesnot exist\n",fnwvf[iy][ix]);
			fnwvf[iy][ix]=0;
		    }else{
			wtsum+=wtxi;
		    }
		}
	    }
	    if(wtsum<0.01){
		error("PSF is not available for (%g,%g). wtsum=%g\n",thetax,thetay, wtsum);
	    }
	    /*Now do the actual reading */
	    for(int ix=0; ix<2; ix++){
		for(int iy=0; iy<2; iy++){
		    double wtxi=fabs(((1-ix)-wtx)*((1-iy)-wty))/wtsum;
		    if(fnwvf[iy][ix]){
			/*info("Loading %.4f x %s\n", wtxi, fnwvf[iy][ix]); */
			file_t *fp_wvf=zfopen(fnwvf[iy][ix],"rb");
			header_t header={0,0,0,0};
			read_header(&header, fp_wvf);
			if(!iscell(&header.magic)){
			    error("expected data type: %u, got %u\n",(uint32_t)MCC_ANY, header.magic);
			}
			nstep=header.nx;
			free(header.str);
			if(parms->skyc.limitnstep >0 && nstep>parms->skyc.limitnstep){
			    nstep=parms->skyc.limitnstep;
			    warning("Only read %ld steps\n",nstep);
			}
			if(stari->nstep==0){
			    stari->nstep=nstep;
			}else{
			    if(stari->nstep!=nstep){
				error("Different type has different steps\n");
			    }
			}
		    
			if(!stari->wvfout[ipowfs]){
			    stari->wvfout[ipowfs]=mycalloc(nstep,ccell*);
			}
			ccell **pwvfout=stari->wvfout[ipowfs];
			for(long istep=0; istep<nstep; istep++){
			    ccell *wvfi=ccellreaddata(fp_wvf, 0);
			    ccelladd(&(pwvfout[istep]), 1, wvfi, wtxi);
			    ccellfree(wvfi);
			}
			/*zfeof(fp_wvf); */
			zfclose(fp_wvf);
		    }
		}/*iy */
	    }/*ix */
	    /*Don't bother to scale ztiltout since it does not participate in physical optics simulations. */
	    if(parms->skyc.bspstrehl){
		dmat*  scale=pistati->scale;
		ccell **pwvfout=stari->wvfout[ipowfs];
		for(int iwvl=0; iwvl<nwvl; iwvl++){
		    for(int isa=0; isa<nsa; isa++){
			/*info("Scaling WVF isa %d iwvl %d with %g\n", isa, iwvl, IND(scale,isa,iwvl)); */
			for(long istep=0; istep<stari->nstep; istep++){
			    cscale(pwvfout[istep]->p[isa+nsa*iwvl], IND(scale,isa,iwvl));
			}/*istep */
		    }/*isa */
		}/*iwvl */
	    }/* */
	}/*ipowfs */
    }/*istar */
Пример #14
0
void
delete_archive_members (void)
{
  enum read_header logical_status = HEADER_STILL_UNREAD;
  enum read_header previous_status = HEADER_STILL_UNREAD;

  /* FIXME: Should clean the routine before cleaning these variables :-( */
  struct name *name;
  off_t blocks_to_skip = 0;
  off_t blocks_to_keep = 0;
  int kept_blocks_in_record;

  name_gather ();
  open_archive (ACCESS_UPDATE);
  acting_as_filter = strcmp (archive_name_array[0], "-") == 0;

  do
    {
      enum read_header status = read_header (true);

      switch (status)
	{
	case HEADER_STILL_UNREAD:
	  abort ();

	case HEADER_SUCCESS:
	  if ((name = name_scan (current_stat_info.file_name)) == NULL)
	    {
	      skip_member ();
	      break;
	    }
	  name->found_count++;
	  if (!ISFOUND(name))
	    {
	      skip_member ();
	      break;
	    }

	  /* Fall through.  */
	case HEADER_SUCCESS_EXTENDED:
	  logical_status = status;
	  break;

	case HEADER_ZERO_BLOCK:
	  if (ignore_zeros_option)
	    {
	      set_next_block_after (current_header);
	      break;
	    }
	  /* Fall through.  */
	case HEADER_END_OF_FILE:
	  logical_status = HEADER_END_OF_FILE;
	  break;

	case HEADER_FAILURE:
	  set_next_block_after (current_header);
	  switch (previous_status)
	    {
	    case HEADER_STILL_UNREAD:
	      WARN ((0, 0, _("This does not look like a tar archive")));
	      /* Fall through.  */

	    case HEADER_SUCCESS:
	    case HEADER_SUCCESS_EXTENDED:
	    case HEADER_ZERO_BLOCK:
	      ERROR ((0, 0, _("Skipping to next header")));
	      /* Fall through.  */

	    case HEADER_FAILURE:
	      break;

	    case HEADER_END_OF_FILE:
	      abort ();
	    }
	  break;
	}

      previous_status = status;
    }
  while (logical_status == HEADER_STILL_UNREAD);

  records_skipped = records_read - 1;
  new_record = xmalloc (record_size);

  if (logical_status == HEADER_SUCCESS
      || logical_status == HEADER_SUCCESS_EXTENDED)
    {
      write_archive_to_stdout = false;

      /* Save away blocks before this one in this record.  */

      new_blocks = current_block - record_start;
      if (new_blocks)
	memcpy (new_record, record_start, new_blocks * BLOCKSIZE);

      if (logical_status == HEADER_SUCCESS)
	{
	  /* FIXME: Pheew!  This is crufty code!  */
	  logical_status = HEADER_STILL_UNREAD;
	  goto flush_file;
	}

      /* FIXME: Solaris 2.4 Sun cc (the ANSI one, not the old K&R) says:
	 "delete.c", line 223: warning: loop not entered at top
	 Reported by Bruno Haible.  */
      while (1)
	{
	  enum read_header status;

	  /* Fill in a record.  */

	  if (current_block == record_end)
	    flush_archive ();
	  status = read_header (false);

	  xheader_decode (&current_stat_info);

	  if (status == HEADER_ZERO_BLOCK && ignore_zeros_option)
	    {
	      set_next_block_after (current_header);
	      continue;
	    }
	  if (status == HEADER_END_OF_FILE || status == HEADER_ZERO_BLOCK)
	    {
	      logical_status = HEADER_END_OF_FILE;
	      break;
	    }

	  if (status == HEADER_FAILURE)
	    {
	      ERROR ((0, 0, _("Deleting non-header from archive")));
	      set_next_block_after (current_header);
	      continue;
	    }

	  /* Found another header.  */

	  if ((name = name_scan (current_stat_info.file_name)) != NULL)
	    {
	      name->found_count++;
	      if (ISFOUND(name))
		{
		flush_file:
		  set_next_block_after (current_header);
		  blocks_to_skip = (current_stat_info.stat.st_size
				    + BLOCKSIZE - 1) / BLOCKSIZE;
		  
		  while (record_end - current_block <= blocks_to_skip)
		    {
		      blocks_to_skip -= (record_end - current_block);
		      flush_archive ();
		    }
		  current_block += blocks_to_skip;
		  blocks_to_skip = 0;
		  continue;
		}
	    }
	  /* Copy header.  */

	  if (current_stat_info.xhdr.size)
	    {
	      write_recent_bytes (current_stat_info.xhdr.buffer,
				  current_stat_info.xhdr.size);
	    }
	  else
	    {
	      write_recent_blocks (recent_long_name, recent_long_name_blocks);
	      write_recent_blocks (recent_long_link, recent_long_link_blocks);
	    }
	  new_record[new_blocks] = *current_header;
	  new_blocks++;
	  blocks_to_keep
	    = (current_stat_info.stat.st_size + BLOCKSIZE - 1) / BLOCKSIZE;
	  set_next_block_after (current_header);
	  if (new_blocks == blocking_factor)
	    write_record (1);

	  /* Copy data.  */

	  kept_blocks_in_record = record_end - current_block;
	  if (kept_blocks_in_record > blocks_to_keep)
	    kept_blocks_in_record = blocks_to_keep;

	  while (blocks_to_keep)
	    {
	      int count;

	      if (current_block == record_end)
		{
		  flush_read ();
		  current_block = record_start;
		  kept_blocks_in_record = blocking_factor;
		  if (kept_blocks_in_record > blocks_to_keep)
		    kept_blocks_in_record = blocks_to_keep;
		}
	      count = kept_blocks_in_record;
	      if (blocking_factor - new_blocks < count)
		count = blocking_factor - new_blocks;

	      if (! count)
		abort ();

	      memcpy (new_record + new_blocks, current_block, count * BLOCKSIZE);
	      new_blocks += count;
	      current_block += count;
	      blocks_to_keep -= count;
	      kept_blocks_in_record -= count;

	      if (new_blocks == blocking_factor)
		write_record (1);
	    }
	}

      if (logical_status == HEADER_END_OF_FILE)
	{
	  /* Write the end of tape.  FIXME: we can't use write_eot here,
	     as it gets confused when the input is at end of file.  */

	  int total_zero_blocks = 0;

	  do
	    {
	      int zero_blocks = blocking_factor - new_blocks;
	      memset (new_record + new_blocks, 0, BLOCKSIZE * zero_blocks);
	      total_zero_blocks += zero_blocks;
	      write_record (total_zero_blocks < 2);
	    }
	  while (total_zero_blocks < 2);
	}

      if (! acting_as_filter && ! _isrmt (archive))
	{
	  if (sys_truncate (archive))
	    truncate_warn (archive_name_array[0]);
	}
    }
  free (new_record);

  close_archive ();
  names_notfound ();
}
Пример #15
0
static int parse_index(git_index *index, const char *buffer, size_t buffer_size)
{
	unsigned int i;
	struct index_header header;
	git_oid checksum_calculated, checksum_expected;

#define seek_forward(_increase) { \
	if (_increase >= buffer_size) \
		return git__throw(GIT_EOBJCORRUPTED, "Failed to seek forward. Buffer size exceeded"); \
	buffer += _increase; \
	buffer_size -= _increase;\
}

	if (buffer_size < INDEX_HEADER_SIZE + INDEX_FOOTER_SIZE)
		return git__throw(GIT_EOBJCORRUPTED, "Failed to parse index. Buffer too small");

	/* Precalculate the SHA1 of the files's contents -- we'll match it to
	 * the provided SHA1 in the footer */
	git_hash_buf(&checksum_calculated, buffer, buffer_size - INDEX_FOOTER_SIZE);

	/* Parse header */
	if (read_header(&header, buffer) < GIT_SUCCESS)
		return git__throw(GIT_EOBJCORRUPTED, "Failed to parse index. Header is corrupted");

	seek_forward(INDEX_HEADER_SIZE);

	git_vector_clear(&index->entries);

	/* Parse all the entries */
	for (i = 0; i < header.entry_count && buffer_size > INDEX_FOOTER_SIZE; ++i) {
		size_t entry_size;
		git_index_entry *entry;

		entry = git__malloc(sizeof(git_index_entry));
		if (entry == NULL)
			return GIT_ENOMEM;

		entry_size = read_entry(entry, buffer, buffer_size);

		/* 0 bytes read means an object corruption */
		if (entry_size == 0)
			return git__throw(GIT_EOBJCORRUPTED, "Failed to parse index. Entry size is zero");

		if (git_vector_insert(&index->entries, entry) < GIT_SUCCESS)
			return GIT_ENOMEM;

		seek_forward(entry_size);
	}

	if (i != header.entry_count)
		return git__throw(GIT_EOBJCORRUPTED, "Failed to parse index. Header entries changed while parsing");

	/* There's still space for some extensions! */
	while (buffer_size > INDEX_FOOTER_SIZE) {
		size_t extension_size;

		extension_size = read_extension(index, buffer, buffer_size);

		/* see if we have read any bytes from the extension */
		if (extension_size == 0)
			return git__throw(GIT_EOBJCORRUPTED, "Failed to parse index. Extension size is zero");

		seek_forward(extension_size);
	}

	if (buffer_size != INDEX_FOOTER_SIZE)
		return git__throw(GIT_EOBJCORRUPTED, "Failed to parse index. Buffer size does not match index footer size");

	/* 160-bit SHA-1 over the content of the index file before this checksum. */
	git_oid_fromraw(&checksum_expected, (const unsigned char *)buffer);

	if (git_oid_cmp(&checksum_calculated, &checksum_expected) != 0)
		return git__throw(GIT_EOBJCORRUPTED, "Failed to parse index. Calculated checksum does not match expected checksum");

#undef seek_forward

	/* force sorting in the vector: the entries are
	 * assured to be sorted on the index */
	index->entries.sorted = 1;
	return GIT_SUCCESS;
}
Пример #16
0
main(int argc, char *argv[]) 
{
	FILE *fileptr, *outfile;
	char filename[1024],*telescope,*backend,*datatype,message[80],unit[16];
	int i,j,year,month,day,check,rah,ram,ded,dem;
	double ras,des,frac,tobs;
	char sra[6],sde[6],decsign;
	int raw,uth,utm,uts;
	long long numsamps,datasize,headersize;
	double readsec,skipsec;

	readsec=1;
	skipsec=0;


	fileptr=stdin;
	outfile=stdout;
	strcpy(filename,"stdin");
	strcpy(rawdatafile,"stdin");
	pulsarcentric=barycentric=0;


	if (argc>1) {
		print_version(argv[0],argv[1]);
		if (help_required(argv[1])) {
			chop_fil_help();
			exit(0);
		} else if (file_exists(argv[1])) {
			strcpy(filename,argv[1]);
			fileptr=open_file(filename,"rb");
		} else if (!file_exists(argv[1]) && (strncmp(argv[1],"-",1) !=0)) {
			sprintf(message,"Data file: %s not found...\n",argv[1]);
			error_message(message);
			exit(1);
		}
	}


	if (!(headersize=read_header(fileptr))) {
		rewind(fileptr);
		if ((raw=typeof_inputdata(fileptr,filename))) {
			data_type=0;
			switch (raw) {
				case 1:
					headersize=32768;
					break;
				case 5:
					headersize=32768;
					break;
				case 3:
					headersize=wapp_header_size+wapp_incfile_length;
					break;
				default:
					break;
			}
		} else {
			error_message("could not read header parameters!");
			exit(1);
		}
	}

	/* attempt to find number of bytes of data and number of samples */
	if (!strings_equal(filename,"stdin")) {
		datasize=sizeof_file(filename)-headersize;
		numsamps=nsamples(filename,headersize,nbits,nifs,nchans);
	} else if (!strings_equal(rawdatafile,"stdin")) {
		datasize=sizeof_file(rawdatafile)-headersize;
		numsamps=nsamples(rawdatafile,headersize,nbits,nifs,nchans);
	} else {
		datasize=numsamps=0;
	}

	telescope=telescope_name(telescope_id);
	backend=backend_name(machine_id);
	datatype=data_category(data_type);

	if (argc>2) {
		check=1;
		i=2;
	} else if ((argc>1) && strings_equal(filename,"stdin")) {
		check=1;
		i=1;
	} else {
		check=0;
	}
	char force_read=0;

	for (i = 0; i < argc ; i++){
		if (strcmp(argv[i],"-s")==0){
			skipsec=atof(argv[++i]);
		}
		if (strcmp(argv[i],"-r")==0){
			readsec=atof(argv[++i]);
		}
		if (strcmp(argv[i],"-f")==0){
		   force_read=1;
		}

	}

	rewind(fileptr);

	char* block_array;
	unsigned long long int count;
	unsigned long long int update_count;
	unsigned long long int bytes_per_sample=(unsigned long long int)(nchans*nbits)/8;
	unsigned long long int bytes_to_read=bytes_per_sample * (unsigned long long int)(readsec / tsamp +0.5);
	unsigned long long int bytes_to_skip=bytes_per_sample * (unsigned long long int)(skipsec / tsamp + 0.5);
	unsigned long long int blocksize = bytes_per_sample;
	unsigned long long int numblocks = bytes_to_read / blocksize;
	unsigned long long int update_size = (unsigned long long int) (10.0 * (bytes_per_sample/tsamp));
	fprintf(stderr,"Bytes per sample = %lld\n",bytes_per_sample);
	fprintf(stderr,"Bytes to read    = %lld\n",bytes_to_read);
	fprintf(stderr,"Bytes to skip    = %lld\n",bytes_to_skip);


	fprintf(stderr,"\n\n==============\n");
	fprintf(stderr,"Copying header (%d bytes)\n",headersize);

	block_array = (char*)malloc(headersize);
	count = fread(block_array,1,headersize,fileptr);
	if ( count != headersize ){
		fprintf(stderr,"Error! Could not read header %d/%d\n",count,headersize);
		exit(1);
	}
	count = fwrite(block_array,1,headersize,outfile);
	if ( count != headersize ){
		fprintf(stderr,"Error! Could not write header\n");
		exit(1);
	}
	free(block_array);

	fprintf(stderr,"Skipping data...\n");
	count = 0;
	update_count = update_size;
	while ( count < bytes_to_skip ) { 
		fseek(fileptr,blocksize,SEEK_CUR);
		count += blocksize;
		update_count += blocksize;
		if ( update_count >= update_size ){
			update_count=0;
			fprintf(stderr,"\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
			fprintf(stderr,"\t% 8.1f s",tsamp*count/(float)bytes_per_sample);
		}
	}
	fprintf(stderr,"\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
	fprintf(stderr,"\t% 8.1f s",tsamp*count/(float)bytes_per_sample);


	fprintf(stderr,"\n\n");
	block_array = (char*) malloc(blocksize);
	
	fprintf(stderr,"Copying data...\n");
	count = 0;
	update_count = update_size;
	while ( count < bytes_to_read ) { 
		int read = fread(block_array,1,blocksize,fileptr);
		if ( read < 1 ) {
		   if (force_read){
			  fclose(fileptr);
			  fileptr = fopen("/dev/urandom","r");
			  fprintf(stderr,"\rPast end of file, reading from /dev/urandom\n");
			  continue;
		   } else {
			fprintf(stderr,"Error! Could not read enough data\n");
			exit(2);
		   }
		}
		read = fwrite(block_array,1,read,outfile);
		if ( read < 1 ) {
			fprintf(stderr,"Error! Could not write enough data\n");
			exit(2);
		}
		count += read;
		update_count += read;
		if ( update_count >= update_size ){
			update_count=0;
			fprintf(stderr,"\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
			fprintf(stderr,"\t% 8.1f s",tsamp*count/(float)bytes_per_sample);
		}
	}
	fprintf(stderr,"\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
	fprintf(stderr,"\t% 8.1f s",tsamp*count/(float)bytes_per_sample);

	fprintf(stderr,"\nDone\n");

	free(block_array);

	exit(0);
}
Пример #17
0
int main(int argc, char ** argv) {
	check();

	// Передан файл базы как параметр
	if (argc == 2) {
		db_filename = argv[1];
	}
	// Файл не передан, используется имя по умолчанию
	else if (argc == 1) {
		db_filename = "default.db";
	}
	// Неправильное использование
	else {
		fprintf( stderr, "Usage: dictionary [words.db]\n");
		exit( EXIT_WRONG_USAGE);
	}

	assert(NULL != db_filename);

	FILE * f = NULL;
	int code = access(db_filename, R_OK | W_OK);
	// Нет прав, не существует файл или что-нибудь ещё
	if (-1 == code) {
		// Нет файла, можно создавать
		if ( errno == ENOENT) {
			f = fopen(db_filename, "w+");
			fprintf( stderr, "INFO: Файл не существовал и теперь создан.\n");
		} else if ( errno == EACCES) {
			fprintf( stderr, "FATAL: Нет прав доступа к базе.\n");
			exit( EXIT_WRONG_RIGHTS);
		} else {
			printf("errno = %d\n", errno);
			exit( EXIT_WTF);
		}
	}
	// Есть права и файл существует
	else {
		f = fopen(db_filename, "r+");
		fprintf( stderr, "INFO: Существующий файл открыт для работы.\n");
	}
	assert(NULL != f);

	fseek(f, 0, SEEK_END);
	int length = ftell(f);
	fprintf( stderr, "DEBUG: Длина файла: %d\n", length);

	if (length < HEADER_SIZE) {
		// Длина файла заведомо меньше размера header. Пишем новый.
		write_new_header(&header, f);
	} else {
		// Читаем
		read_header(&header, f);

		// Проверяем
		if (header.version != 1 || header.actual_words > header.total_words) {
			fprintf( stderr,
					"FATAL: База данных (%s), вероятно, испорчена. Возможно, стоит её удалить.\n",
					db_filename);
			WTF();
		}
	}

	// Всё есть. Можно работать.
	printf("Введите help для справки, quit для выхода.\n");
	int working = 1;
	while (working) {
		printf("> ");

		char str[6];
		fgets(str, 6, stdin);
		remove_newline(str);
		if (strcmp(str, "help") == 0) {
			command_help();
		} else if (strcmp(str, "quit") == 0 || strcmp(str, "exit") == 0
				|| strcmp(str, "bye") == 0) {
			save_database(f);
			exit( EXIT_SUCCESS);
		} else if (strcmp(str, "add") == 0) {
			command_add(f);
		} else if (strcmp(str, "find") == 0) {
			command_find(f);
		} else if (strcmp(str, "del") == 0 || strcmp(str, "rm") == 0) {
			command_remove(f);
		} else if (strcmp(str, "frag") == 0) {
			command_defragment(f);
		} else {
			fprintf( stderr, "ERROR: Неизвестная команда '%s'\n", str);
		}
	}

	/*
	 Операции:
	 1. Добавить слово. Имя (128 байт), содержание (не ограничено) ->
	 2. Найти слово. Имя -> содержание
	 3. Удалить. Имя ->
	 */
	if (f != NULL)
		fclose(f);

	return EXIT_SUCCESS;
}
Пример #18
0
/* Implement the 'r' (add files to end of archive), and 'u' (add files to
   end of archive if they arent there, or are more up to date than the
   version in the archive.) commands.*/
void
update_archive ()
{
  int found_end = 0;
  int status = 3;
  int prev_status;
  char *p;
  struct name *name;
  extern void dump_file ();

  name_gather ();
  if (cmd_mode == CMD_UPDATE)
    name_expand ();
  open_archive (2);		/* Open for updating */

  do
    {
      prev_status = status;
      status = read_header ();
      switch (status)
	{
	case EOF:
	  found_end = 1;
	  break;

	case 0:		/* A bad record */
	  userec (head);
	  switch (prev_status)
	    {
	    case 3:
	      msg ("This doesn't look like a tar archive.");
	      /* FALL THROUGH */
	    case 2:
	    case 1:
	      msg ("Skipping to next header");
	    case 0:
	      break;
	    }
	  break;

	  /* A good record */
	case 1:
	  /* printf("File %s\n",head->header.name); */
	  /* head->header.name[NAMSIZ-1]='\0'; */
	  if (cmd_mode == CMD_UPDATE && (name = name_scan (current_file_name)))
	    {

	      /* struct stat hstat; */
	      struct stat nstat;
	      int head_standard;

	      decode_header (head, &hstat, &head_standard, 0);
	      if (stat (current_file_name, &nstat) < 0)
		{
		  msg_perror ("can't stat %s:", current_file_name);
		}
	      else
		{
		  if (hstat.st_mtime >= nstat.st_mtime)
		    name->found++;
		}
	    }
	  userec (head);
	  if (head->header.isextended)
	    skip_extended_headers ();
	  skip_file ((long) hstat.st_size);
	  break;

	case 2:
	  ar_record = head;
	  found_end = 1;
	  break;
	}
    }
  while (!found_end);

  reset_eof ();
  time_to_start_writing = 1;
  output_start = ar_record->charptr;

  while (p = name_from_list ())
    {
      if (f_confirm && !confirm ("add", p))
	continue;
      if (cmd_mode == CMD_CAT)
	append_file (p);
      else
	dump_file (p, -1, 1);
    }

  write_eot ();
  close_archive ();
  names_notfound ();
}
Пример #19
0
void execute_histogram(char * histogram_query, char * data_filename, FILE * output) {
    
    char * command;
    command = (char *)calloc(11, sizeof(char));
    char * header;
    header = (char *)calloc(17, sizeof(char));
    char * header_word_2;
    header_word_2 = (char *)calloc(4, sizeof(char));
    char * header_word_3;
    header_word_3 = (char *)calloc(2, sizeof(char));
    int bins;
    char * start_date;
    start_date = (char *)calloc(17, sizeof(char));
    char * end_date;
    end_date = (char *)calloc(19, sizeof(char));
    
    // count whitespace in query to determine if header is multiple words
    int query_length = (int)strlen(histogram_query);
    int num_spaces = 0;
    for (int i=0; i<query_length; i++) {
        if (histogram_query[i] == ' ') {
            num_spaces++;
        }
    }
    if (num_spaces == 6) {
        sscanf(histogram_query, "%s %s %s %s %d %s %s", command, header, header_word_2, header_word_3, &bins, start_date, end_date);
        for (int i=0; i<40; i++) {
            if (header[i] == '\0') {
                header[i] = ' ';
                for (int k=0; k<40; k++) {
                    if (header_word_2[k] != '\0') {
                        header[i+k+1] = header_word_2[k];
                    } else {
                        header[i+k+1] = ' ';
                        header[i+k+2] = header_word_3 [0];
                        header[i+k+3] = '\0';
                        break;
                    }
                }
                break;
            }
        }
    } else if (num_spaces == 5) {
        sscanf(histogram_query, "%s %s %s %d %s %s", command, header, header_word_2, &bins, start_date, end_date);
        for (int i=0; i<40; i++) {
            if (header[i] == '\0') {
                header[i] = ' ';
                for (int k=0; k<40; k++) {
                    if (header_word_2[k] != '\0') {
                        header[i+k+1] = header_word_2[k];
                    } else {
                        break;
                    }
                }
                break;
            }
        }
    } else {
        sscanf(histogram_query, "%s %s %d %s %s", command, header, &bins, start_date, end_date);
    }
    
    Type_t data_type;
    data_type = column_type(header);
    
    int num_data_columns = header_columns(data_filename);
    char * column_headers[num_data_columns];
    read_header(data_filename, column_headers);
    
    int data_column_index = -1;
    int date_index = -1;
    int time_index = -1;
    
    char  date[] = "Date";
    char time[] = "HrMn";
    
    //date is LONG time is INT
    
    for (int i = 0; i<num_data_columns; i++) {
        if (strcmp(column_headers[i], header) == 0) {
            data_column_index = i;
        }
    }
    for (int i = 0; i<num_data_columns; i++) {
        if (strcmp(column_headers[i], date) == 0) {
            date_index = i;
        }
    }
    for (int i = 0; i<num_data_columns; i++) {
        if (strcmp(column_headers[i], time) == 0) {
            time_index = i;
        }
    }
    
    FILE * data_file = NULL;
    data_file = fopen(data_filename, "r");
    if (data_file == NULL) {
        printf("ERROR invalid data file: %s/n", data_filename);
    }
    
    void * row_data[num_data_columns];
    
    int ivalue; int imax; int imin;
    long lvalue ; long lmax; long lmin;
    float fvalue; float fmax;  float fmin; float maximum; float minimum;
    int row_count = 0;
    
    long * data_date;
    //    data_date = calloc(9, sizeof(char));
    
    int * data_time;
    //    data_time = calloc(5, sizeof(char));
    
    
    char * row;
    row = (char *)calloc(200,sizeof(char));
    int status = 0;
    // read file for maximum
    fgets(row, 200, data_file);
    while(fscanf(data_file, "*") != EOF) {
        status = read_row(data_file, column_headers, row_data);
        data_date = ((long*)row_data[date_index]);
        data_time = ((int*)row_data[time_index]);
        
        
        int in_time_range = is_in_range(start_date, end_date, data_date, data_time);
        if (in_time_range == 1) {
            if (data_type==FLOAT) {
                fvalue = *((float*)row_data[data_column_index]);
                if(row_count == 0) {
                    fmax = fvalue;
                } else if (fvalue > fmax) {
                    fmax = fvalue;
                }
            }
            if (data_type==INT) {
                ivalue = *((int*)row_data[data_column_index]);
                if(row_count == 0) {
                    imax = ivalue;
                } else if (ivalue > imax) {
                    imax = ivalue;
                }
            }
            if (data_type==LONG) {
                lvalue = *((long*)row_data[data_column_index]);
                if(row_count == 0) {
                    lmax = lvalue;
                } else if (lvalue > lmax) {
                    lmax = lvalue;
                }
            }
        }
        row_count++;
    }
    if (data_type==FLOAT) {
        printf("Maximum = %f\n",fmax);
        maximum = fmax;
    }else if (data_type==INT) {
        printf("Maximum = %d\n",imax);
        maximum = (float)imax;
    } else if (data_type==LONG) {
        printf("Maximum = %ld\n",lmax);
        maximum = (float)lmax;
    }
    
    rewind(data_file);
    
    fgets(row, 200, data_file);
    while(fscanf(data_file, "*") != EOF) {
        status = read_row(data_file, column_headers, row_data);
        data_date = ((long*)row_data[date_index]);
        data_time = ((int*)row_data[time_index]);
        
        
        int in_time_range = is_in_range(start_date, end_date, data_date, data_time);
        if (in_time_range == 1) {
            if (data_type==FLOAT) {
                fvalue = *((float*)row_data[data_column_index]);
                if(row_count == 0) {
                    fmin = fvalue;
                } else if (fvalue < fmin) {
                    fmin = fvalue;
                }
            }
            if (data_type==INT) {
                ivalue = *((int*)row_data[data_column_index]);
                if(row_count == 0) {
                    imin = ivalue;
                } else if (ivalue < imin) {
                    imin = ivalue;
                }
            }
            if (data_type==LONG) {
                lvalue = *((long*)row_data[data_column_index]);
                if(row_count == 0) {
                    lmin = lvalue;
                } else if (lvalue < lmin) {
                    lmin = lvalue;
                }
            }
        }
        row_count++;
    }
    if (data_type==FLOAT) {
        printf("Minimum = %f\n",fmin);
        minimum = fmin;
    }else if (data_type==INT) {
        printf("Minimum = %d\n",imin);
        minimum = (float)imin;
    } else if (data_type==LONG) {
        printf("Minimum = %ld\n",lmin);
        minimum = (float)lmin;
    }

}
Пример #20
0
/*---------------------------------------------------------------------------*/
static int
merge_log(coffee_page_t file_page, int extend)
{
  struct file_header hdr, hdr2;
  int fd, n;
  cfs_offset_t offset;
  coffee_page_t max_pages;
  struct file *new_file;
  int i;

  read_header(&hdr, file_page);

  fd = cfs_open(hdr.name, CFS_READ);
  if(fd < 0) {
    return -1;
  }

  /*
   * The reservation function adds extra space for the header, which has
   * already been calculated with in the previous reservation.
   */
  max_pages = hdr.max_pages << extend;
  new_file = reserve(hdr.name, max_pages, 1, 0);
  if(new_file == NULL) {
    cfs_close(fd);
    return -1;
  }

  offset = 0;
  do {
    char buf[COFFEE_PAGE_SIZE];
    n = cfs_read(fd, buf, sizeof(buf));
    if(n < 0) {
      remove_by_page(new_file->page, !REMOVE_LOG, !CLOSE_FDS, ALLOW_GC);
      cfs_close(fd);
      return -1;
    } else if(n > 0) {
      COFFEE_WRITE(buf, n, absolute_offset(new_file->page, offset));
      offset += n;
    }
  } while(n != 0);

  for(i = 0; i < COFFEE_FD_SET_SIZE; i++) {
    if(coffee_fd_set[i].flags != COFFEE_FD_FREE && 
       coffee_fd_set[i].file->page == file_page) {
      coffee_fd_set[i].file = new_file;
      new_file->references++;
    }
  }

  if(remove_by_page(file_page, REMOVE_LOG, !CLOSE_FDS, !ALLOW_GC) < 0) {
    remove_by_page(new_file->page, !REMOVE_LOG, !CLOSE_FDS, !ALLOW_GC);
    cfs_close(fd);
    return -1;
  }

  /* Copy the log configuration and the EOF hint. */
  read_header(&hdr2, new_file->page);
  hdr2.log_record_size = hdr.log_record_size;
  hdr2.log_records = hdr.log_records;
  write_header(&hdr2, new_file->page);

  new_file->flags &= ~COFFEE_FILE_MODIFIED;
  new_file->end = offset;

  cfs_close(fd);

  return 0;
}
Пример #21
0
float execute_avg(char * avg_query, char * data_filename, FILE * output) {
    
    char * command;
    command = (char *)calloc(11, sizeof(char));
    char * header;
    header = (char *)calloc(17, sizeof(char));
    char * header_word_2;
    header_word_2 = (char *)calloc(4, sizeof(char));
    char * header_word_3;
    header_word_3 = (char *)calloc(2, sizeof(char));
    char * start_date;
    start_date = (char *)calloc(17, sizeof(char));
    char * end_date;
    end_date = (char *)calloc(19, sizeof(char));
    
    // count whitespace in query to determine if header is multiple words
    int query_length = (int)strlen(avg_query);
    int num_spaces = 0;
    for (int i=0; i<query_length; i++) {
        if (avg_query[i] == ' ') {
            num_spaces++;
        }
    }
    if (num_spaces == 5) {
        sscanf(avg_query, "%s %s %s %s %s %s", command, header, header_word_2, header_word_3, start_date, end_date);
        for (int i=0; i<40; i++) {
            if (header[i] == '\0') {
                header[i] = ' ';
                for (int k=0; k<40; k++) {
                    if (header_word_2[k] != '\0') {
                        header[i+k+1] = header_word_2[k];
                    } else {
                        header[i+k+1] = ' ';
                        header[i+k+2] = header_word_3 [0];
                        header[i+k+3] = '\0';
                        break;
                    }
                }
                break;
            }
        }
    } else if (num_spaces == 4) {
        sscanf(avg_query, "%s %s %s %s %s", command, header, header_word_2, start_date, end_date);
        for (int i=0; i<40; i++) {
            if (header[i] == '\0') {
                header[i] = ' ';
                for (int k=0; k<40; k++) {
                    if (header_word_2[k] != '\0') {
                        header[i+k+1] = header_word_2[k];
                    } else {
                        break;
                    }
                }
                break;
            }
        }
    } else {
        sscanf(avg_query, "%s %s %s %s", command, header, start_date, end_date);
    }
    
    Type_t data_type;
    data_type = column_type(header);
    
    int num_data_columns = header_columns(data_filename);
    char * column_headers[num_data_columns];
    read_header(data_filename, column_headers);
    
    int data_column_index = -1;
    int date_index = -1;
    int time_index = -1;
    
    char  date[] = "Date";
    char time[] = "HrMn";
    
    //date is LONG time is INT
    
    for (int i = 0; i<num_data_columns; i++) {
        if (strcmp(column_headers[i], header) == 0) {
            data_column_index = i;
        }
    }
    for (int i = 0; i<num_data_columns; i++) {
        if (strcmp(column_headers[i], date) == 0) {
            date_index = i;
        }
    }
    for (int i = 0; i<num_data_columns; i++) {
        if (strcmp(column_headers[i], time) == 0) {
            time_index = i;
        }
    }
    
    if (data_column_index == -1) {
        printf("ERROR header %s not found in data file\n Query: %s\n", header, avg_query);
        return 0;
    }
    if (time_index == -1) {
        printf("ERROR header HrMn not found in data file\n Query: %s\n", avg_query);
        return 0;
    }
    if (date_index == -1) {
        printf("ERROR header Date not found in data file\n Query: %s\n", avg_query);
        return 0;
    }
    
    FILE * data_file = NULL;
    data_file = fopen(data_filename, "r");
    if (data_file == NULL) {
        printf("ERROR invalid data file: %s/n", data_filename);
    }
    
    void * row_data[num_data_columns];
    
    int ivalue = 0;
    long lvalue = 0;
    float fvalue = 0; float avg = 0;
    int data_count = 0;
    int row_count = 0;
    
    long * data_date;
    //    data_date = calloc(9, sizeof(char));
    
    int * data_time;
    //    data_time = calloc(5, sizeof(char));
    
    char * row;
    row = (char *)calloc(200,sizeof(char));
    int status = 0;
    // read file
    fgets(row, 200, data_file);
    while(fscanf(data_file, "*") != EOF) {
        status = read_row(data_file, column_headers, row_data);
        data_date = ((long*)row_data[date_index]);
        data_time = ((int*)row_data[time_index]);
        
        
        int in_time_range = is_in_range(start_date, end_date, data_date, data_time);
        if (in_time_range == 1) {
            data_count++;
            if (data_type==FLOAT) {
                fvalue = fvalue + *((float*)row_data[data_column_index]);
            }
            if (data_type==INT) {
                ivalue = ivalue + *((int*)row_data[data_column_index]);
            }
            if (data_type==LONG) {
                lvalue = lvalue + *((long*)row_data[data_column_index]);
            }
        }
        row_count++;
    }
    if (data_type==FLOAT) {
        if (output == NULL) {
            avg = fvalue/data_count;
            printf("Average = %f\n",avg);
        } else {
            fprintf(output, "Average = %f\n",avg);
        }
        
    }else if (data_type==INT) {
        if(output == NULL) {
            avg = (float) ivalue/data_count;
            printf("Average = %d\n",(int)avg);
        }else {
            fprintf(output, "Average = %d\n",(int)avg);
        }
    } else if (data_type==LONG) {
        if(output == NULL) {
            avg = (float) lvalue/data_count;
            printf("Average = %ld\n",(long)avg);
        }else {
            fprintf(output, "Average = %ld\n",(long)avg);
        }
    }
    return avg;
}
Пример #22
0
void opt_d(int argc, char **argv,int *arch, int *filecount, int *fcalled, file *info){
	int fbyte_max=1;
	int fbyte=0;
	int size = 0;
	int tempfile=0;
	int temparch =0;
	char cur_name[16];
	char *null_cur_name;
	char *null_info_name;
	char *str_buf;
	struct stat archinfo;
	struct stat temparch_info;
	

	fstat((*arch),&archinfo);

	temparch = create_tempfile();
	write(temparch,"!<arch>\n",8);
	fstat(temparch,&temparch_info);

	fbyte_max = archinfo.st_size;
	
	fbyte = 0;
	lseek((*arch),8,SEEK_SET);
	read_filename(argv,filecount,4,fcalled,info);

	for(fbyte=0; fbyte < fbyte_max; fbyte++){
		read((*arch),cur_name,16);
		null_cur_name = null_str(cur_name,16);
		null_cur_name = shrt_str(null_cur_name);
		null_info_name= null_str(info->name,16);
		null_info_name = shrt_str(null_info_name);

		(fbyte) += 60+atoi(info->size);

		if(fbyte < fbyte_max){
			if(!strcmp(null_cur_name,null_info_name)){
				iter_arch((*arch), &fbyte, info);

				if(atoi(info->size)%2!=0){
					lseek((*arch),1,SEEK_CUR);
					(fbyte)++;
				}
			}else{
				read_header(argc, argv, filecount, 4, fcalled, info);
				tempfile = create_tempfile();
				write_file_header(tempfile,info);
				info->desc = (*arch);
				write_file_content(tempfile,info);
				all_in_arch(tempfile,temparch,fcalled,info);
				close(tempfile);
			}
		}
	}

	remove(argv[1]);
	(*arch) = open_file(argv[1],1);
	size = temparch_info.st_size;
	str_buf = malloc(sizeof(char)*size);
	read(temparch,str_buf,size);
	close(temparch);
}
Пример #23
0
struct stormdata *read_stormdata_hurdat(struct stormdata *storms,
                                        struct storm_arg *args)
{
    FILE *hurdat;
    char *line, buf[10240];
    int t = 0, s = 0, e = 0, l = 0;
    int lineno = 0;
    struct storm storm;
    int count = 0;

    hurdat = fopen(args->input, "r");

    if (!hurdat) {
        fprintf(stderr, "Couldn't open file '%s': %s\n",
                args->input, strerror(errno));
        return NULL;
    }

    while ((line = fgets(buf, sizeof(buf), hurdat))) {
        lineno++;
        if (is_header_line(line)) {
            init_storm(&storm);
            storm.header = read_header(line);
#if 0
            printf("Beginning %s.\n", storm.header.name);
#endif

            line[11] = 0;
            line[8] = 0;
            storm.header.month = atoi(line + 6);
            storm.header.day = atoi(line + 9); /* estimate */

            count++;
        } else if (!isdigit(line[7])) {
            /* Some storms (like Andrew/1992) have an extra line at the
             * end.  I don't know what it does.  This skips it. */
            if (count > 0) {
                save_storm(args, storms, &storm);
            }
        } else {
            int i;

            for (i = 0; i < 4; i++) {
                struct pos pos;
                char subline[18];

#if 0
                printf("%s", line);
#endif

                pos.month = 10 * (line[6] - '0') + (line[7] - '0');
                pos.day = 10 * (line[9] - '0') + (line[10] - '0');
                pos.hour = i * 6;

                strncpy(subline, line + 11 + i * 17, 17);
                subline[17] = 0;

                switch (subline[0]) {
                case '*':
                case 'D': /* depression? */
                case 'd':
                    pos.type = TROPICAL;
                    t++;
                    break;
                case 'E':
                case 'e':
                case 'X':
                case 'x':
                    pos.type = EXTRATROPICAL;
                    e++;
                    break;
                case 'S':
                case 's':
                    pos.type = SUBTROPICAL;
                    s++;
                    break;
                case 'L': /* low */
                case 'l':
                case 'W': /* "wave" */
                case 'w':
                    pos.type = LOW;
                    l++;
                    break;
                case ' ':
                    continue;
                default:
                    fprintf(stderr, "Unknown line : %d : '%s'\n", lineno, subline);
                    break;
                }

                subline[12] = 0;
                subline[8] = 0;
                pos.lon = atoi(subline + 4) / 10.0;
                subline[4] = 0;
                pos.lat = atoi(subline + 1) / 10.0;
                pos.wind = atoi(subline + 9);
                pos.pres = atoi(subline + 13);

                save_pos(args, storms, &storm, &pos);
            }
        }
    }
    fclose(hurdat);

#if 0
    printf("Longitude: %d, %d\n", minlon, maxlon);
    printf("Latitude: %d, %d\n", minlat, maxlat);

    printf("%d %d %d %d\n", t, s, e, l);
#endif

    return storms;
}
Пример #24
0
int main()
{
    printf("welcome ! \n");

    signal(SIGCHLD, sigfunc_callback);
    signal(SIGINT, sigfunc_callback);
    //signal(SIGPIPE, SIG_IGN);   // 由于没有做连接符删除,发送到一个已关闭链接会触发SIGPIPE信号,这里需要屏蔽该信号

    init_llink(&client_vector);     //初始化客户端连接集合

    struct sockaddr_in serv_addr;
	serv_sock_f = socket(AF_INET, SOCK_STREAM, 0);

    serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(PORT);
	inet_pton( AF_INET, IP, &serv_addr.sin_addr.s_addr);


    int flag=1 ;

    // SO_REUSEADDR 设置端口重用,否则中断程序重启会提示端口被使用,需要过一段时间才能使用
    int len=sizeof(int);
    if( setsockopt(serv_sock_f, SOL_SOCKET, SO_REUSEADDR, &flag, len) == -1)
    {
       perror("setsockopt");
       exit( -1 );
    }
    //发现设置端口重用有个问题,如果中断了该端口通信(通信正在进行中),重用的端口的新程序会继续接收上次未完成的数据(然后就杯具了%>_<%)

	flag = bind(serv_sock_f, (struct sockaddr *)&serv_addr, sizeof(serv_addr));


    if(flag == -1)
	{
        perror("bind");
		exit( -1 );
	}

	flag = listen(serv_sock_f, 5);
	if(flag == -1)
	{
		perror("listen");
		exit( -1 );
	}

    struct sockaddr_in client_addr;
	socklen_t client_sock_l = 0;
	int client_sock_f = -1;


    //lx@0109 增加epoll代码
    ep_servf = epoll_create(5);
    ep_clients = epoll_create(5);

	struct epoll_event _event;
	_event.data.fd = serv_sock_f;
    _event.events = EPOLLIN ;

	flag = epoll_ctl(ep_servf, EPOLL_CTL_ADD, serv_sock_f, &_event);
    if (flag == -1) {
		//elog(E_ERROR, "epoll_ctl failed error num is %d", errno);
        perror("epoll_ctl");
        exit( -1 );
    }

	event_ok = (struct epoll_event *)calloc( 1, sizeof(struct epoll_event));

    flag = pthread_create(&thread_c, NULL, thread_func, NULL);
	if(flag != 0)
	{
		//elog(E_ERROR, "run child thread failed error num is %d", errno);
        perror("pthread_create");
		exit( -1 );
	}
    //end

    int client_len = 0;
    while(1)
	{
        int isok=epoll_wait(ep_servf, event_ok, 1, -1) ;
        if(isok>0 && event_ok[0].data.fd == serv_sock_f)
        {
            if(client_len >= EP_LIMIT){
                printf("warning");
            }

            client_sock_f = accept(serv_sock_f, (struct sockaddr *)&client_addr, &client_sock_l);
            //for login
            read_header(client_sock_f);
            response(client_sock_f);
            //login done  begin msg ...

            // record to client pool
            client_heap[client_len] = client_sock_f ;
            client_len++ ;

            /* 添加到客户端epoll */
            cli_vertor[cli_counter] = client_sock_f;
            cli_counter++;
            append_data_llink(&client_vector, client_sock_f);
			_event.data.fd = client_sock_f;
    		_event.events = EPOLLIN | EPOLLOUT ;
			epoll_ctl(ep_clients, EPOLL_CTL_ADD, client_sock_f, &_event);
        }
    }

    exit(0);
}
Пример #25
0
void process_requests(int server_s, struct soap *soap)/*by SeanHou*/
{
    /* :TODO:Monday, December 01, 2014 11:17:36 HKT:SeanHou:  */
    int OnvifEN = 0;
    int lookupindex = 0;
    char service_uri[100] = "";

    memset((void*)&soap->peer, 0, sizeof(soap->peer));
    soap->socket = SOAP_INVALID_SOCKET;
    soap->error  = SOAP_OK;
    soap->errmode = 0;
    soap->keep_alive = 0;

    fprintf(stderr, "Warning:" \
            "(==>%s).\n", __func__);

    /* :TODO:End---  */
    int retval = 0;
    request *current, *trailer;

    if (pending_requests) {
        get_request(server_s);
#ifdef ORIGINAL_BEHAVIOR
        pending_requests = 0;
#endif
    }

    current = request_ready;

    while (current) {
        /* :TODO:Monday, December 01, 2014 11:18:42 HKT:SeanHou: juge is onvif */
        OnvifEN = isonvif(current->client_stream, service_uri, &lookupindex);
        if(OnvifEN == 1)
        {
            fprintf(stderr, "[boa:onvif] Warning: is onvif line[%d]remote port[%d]h2ns[%d]remote ip[%s]\n", __LINE__, current->remote_port, htons(current->remote_port), current->remote_ip_addr);
            struct sockaddr_in onvif_client_addr;
            memset(&onvif_client_addr, 0, sizeof(onvif_client_addr));
            onvif_client_addr.sin_family = AF_INET;
            onvif_client_addr.sin_port = htons(current->remote_port);//随机端口
            onvif_client_addr.sin_addr.s_addr = inet_addr(current->remote_ip_addr);//

            soap->socket = current->fd;
            soap->peer = onvif_client_addr;
            if (soap_valid_socket(soap->socket))
            {
                soap->ip = ntohl(soap->peer.sin_addr.s_addr);
                soap->port = (int)ntohs(soap->peer.sin_port);
                soap->keep_alive = (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) != 0);
            }


            g_onvif_buffer = (char *)soap_malloc(soap, sizeof(current->client_stream));
            strcpy(g_onvif_buffer, current->client_stream);//mark

            soap_begin_recv(soap);
            if (soap_envelope_begin_in(soap))
            {
                soap_send_fault(soap);
            }
            if (soap_recv_header(soap))
            {
                soap_send_fault(soap);
            }
            if (soap_body_begin_in(soap))
            {
                soap_send_fault(soap);
            }

            int errorCode = 0;
            if (errorCode = soap_serve_request(soap))
            {
                fprintf(stderr, "[boa:onvif]soap_serve_request fail, errorCode %d \n", errorCode);
                soap_send_fault(soap);
            }

            memset(current->client_stream, 0, CLIENT_STREAM_SIZE );

            soap_dealloc(soap, NULL);
            soap_destroy(soap);      
            soap_end(soap);
            current->status = DONE;
            close(soap->socket);
            continue;
        }
        /* :TODO:End---  */
        time(&current_time);
        if (current->buffer_end && /* there is data in the buffer */
                current->status != DEAD && current->status != DONE) {
            retval = req_flush(current);
            /*
             * retval can be -2=error, -1=blocked, or bytes left
             */
            if (retval == -2) { /* error */
                current->status = DEAD;
                retval = 0;
            } else if (retval >= 0) {
                /* notice the >= which is different from below?
                   Here, we may just be flushing headers.
                   We don't want to return 0 because we are not DONE
                   or DEAD */

                retval = 1;
            }
        } else {
            switch (current->status) {
                case READ_HEADER:
                case ONE_CR:
                case ONE_LF:
                case TWO_CR:
                    retval = read_header(current);
                    break;
                case BODY_READ:
                    retval = read_body(current);
                    break;
                case BODY_WRITE:
                    retval = write_body(current);
                    break;
                case WRITE:
                    retval = process_get(current);
                    break;
                case PIPE_READ:
                    retval = read_from_pipe(current);
                    break;
                case PIPE_WRITE:
                    retval = write_from_pipe(current);
                    break;
                case DONE:
                    /* a non-status that will terminate the request */
                    retval = req_flush(current);
                    /*
                     * retval can be -2=error, -1=blocked, or bytes left
                     */
                    if (retval == -2) { /* error */
                        current->status = DEAD;
                        retval = 0;
                    } else if (retval > 0) {
                        retval = 1;
                    }
                    break;
                case DEAD:
                    retval = 0;
                    current->buffer_end = 0;
                    SQUASH_KA(current);
                    break;
                default:
                    retval = 0;
                    fprintf(stderr, "Unknown status (%d), "
                            "closing!\n", current->status);
                    current->status = DEAD;
                    break;
            }

        }

        if (sigterm_flag)
            SQUASH_KA(current);

        /* we put this here instead of after the switch so that
         * if we are on the last request, and get_request is successful,
         * current->next is valid!
         */
        if (pending_requests)
            get_request(server_s);

        switch (retval) {
            case -1:               /* request blocked */
                trailer = current;
                current = current->next;
                block_request(trailer);
                break;
            case 0:                /* request complete */
                current->time_last = current_time;
                trailer = current;
                current = current->next;
                free_request(&request_ready, trailer);
                break;
            case 1:                /* more to do */
                current->time_last = current_time;
                current = current->next;
                break;
            default:
                log_error_time();
                fprintf(stderr, "Unknown retval in process.c - "
                        "Status: %d, retval: %d\n", current->status, retval);
                current = current->next;
                break;
        }
    }
}