예제 #1
0
void TSConstructObject::Build(Lexer::TTokenPos* source, std::vector<TExpressionResult>& params_result, std::vector<TSOperation*>& params, std::vector<TFormalParameter>& params_formals, TGlobalBuildContext build_context)
{
	TSMethod* constructor = NULL;
	if (params_result.size() > 0)
	{
		std::vector<TSMethod*> constructors;
		object_type->GetCopyConstructors(constructors);
		constructor = FindMethod(source, constructors, params_result);
		
		if (constructor == NULL)
			source->Error(" оструктора с такими парметрами не существует!");
	}
	else
	{
		constructor = object_type->GetDefConstr();
	}

	TSMethod* destructor = object_type->GetDestructor();
	if (destructor != NULL)
	{
		ValidateAccess(source, owner, destructor);
	}

	if (constructor != NULL)
	{
		constructor_call.reset(new TSExpression_TMethodCall(TSExpression_TMethodCall::ObjectConstructor));
		constructor_call->Build(params, constructor);
		ValidateAccess(source, owner, constructor);
	}
}
예제 #2
0
	void Visit(SyntaxApi::IOperations::IUnaryOp* operation_node)
	{
		std::vector<TSOperation*> param_expressions;
		TSOperation *left;
		left = VisitNode(operation_node->GetLeft());

		param_expressions.push_back(left);

		std::vector<TExpressionResult> param;

		param.resize(1);
		param[0] = left->GetFormalParameter();

		SemanticApi::ISMethod *unary_operator = nullptr;

		if (param[0].GetClass() == nullptr)
			syntax_node->Error("К данному операнду нельзя применить унарный оператор (нужен тип отличающийся от void)!");

		std::vector<SemanticApi::ISMethod*> operators;
		param[0].GetClass()->GetOperators(operators, operation_node->GetOp());

		unary_operator = FindMethod(syntax_node, operators, param);

		if (unary_operator != nullptr)
		{
			ValidateAccess(syntax_node, owner, unary_operator);

			TSExpression_TMethodCall* method_call = new TSExpression_TMethodCall(SemanticApi::TMethodCallType::Operator);
			method_call->Build(param_expressions, dynamic_cast<TSMethod*>(unary_operator));
			Return(method_call);
		}
		else
			syntax_node->Error("Унарного оператора для данного типа не существует!");
	}
예제 #3
0
int main( int argc, char *argv[] )
{
  if ( access(ZM_CONFIG, R_OK) != 0 )
  {
    fprintf( stderr, "Can't open %s: %s\n", ZM_CONFIG, strerror(errno) );
    exit( -1 );
  }

  self = argv[0];

  srand( getpid() * time( 0 ) );

  static struct option long_options[] = {
    {"device", 2, 0, 'd'},
    {"monitor", 1, 0, 'm'},
    {"verbose", 0, 0, 'v'},
    {"image", 2, 0, 'i'},
    {"scale", 1, 0, 'S'},
    {"timestamp", 2, 0, 't'},
    {"state", 0, 0, 's'},
    {"brightness", 2, 0, 'B'},
    {"contrast", 2, 0, 'C'},
    {"hue", 2, 0, 'H'},
    {"contrast", 2, 0, 'O'},
    {"read_index", 0, 0, 'R'},
    {"write_index", 0, 0, 'W'},
    {"event", 0, 0, 'e'},
    {"fps", 0, 0, 'f'},
    {"zones", 2, 0, 'z'},
    {"alarm", 0, 0, 'a'},
    {"noalarm", 0, 0, 'n'},
    {"cancel", 0, 0, 'c'},
    {"reload", 0, 0, 'L'},
    {"enable", 0, 0, 'E'},
    {"disable", 0, 0, 'D'},
    {"suspend", 0, 0, 'u'},
    {"resume", 0, 0, 'r'},
    {"query", 0, 0, 'q'},
    {"username", 1, 0, 'U'},
    {"password", 1, 0, 'P'},
    {"auth", 1, 0, 'A'},
    {"version", 1, 0, 'V'},
    {"help", 0, 0, 'h'},
    {"list", 0, 0, 'l'},
    {0, 0, 0, 0}
  };

  const char *device = 0;
  int mon_id = 0;
  bool verbose = false;
  int function = ZMU_BOGUS;

  int image_idx = -1;
  int scale = -1;
  int brightness = -1;
  int contrast = -1;
  int hue = -1;
  int colour = -1;
  char *zoneString = 0;
  char *username = 0;
  char *password = 0;
  char *auth = 0;
#if ZM_HAS_V4L
#if ZM_HAS_V4L2
  int v4lVersion = 2;
#elif ZM_HAS_V4L1
  int v4lVersion = 1;
#endif // ZM_HAS_V4L2/1
#endif // ZM_HAS_V4L
  while (1)
  {
    int option_index = 0;

    int c = getopt_long (argc, argv, "d:m:vsEDLurwei::S:t::fz::ancqhlB::C::H::O::U:P:A:V:", long_options, &option_index);
    if (c == -1)
    {
      break;
    }

    switch (c)
    {
      case 'd':
        if ( optarg )
          device = optarg;
        break;
      case 'm':
        mon_id = atoi(optarg);
        break;
      case 'v':
        verbose = true;
        break;
      case 's':
        function |= ZMU_STATE;
        break;
      case 'i':
        function |= ZMU_IMAGE;
        if ( optarg )
          image_idx = atoi( optarg );
        break;
      case 'S':
        scale = atoi(optarg);
        break;
      case 't':
        function |= ZMU_TIME;
        if ( optarg )
          image_idx = atoi( optarg );
        break;
      case 'R':
        function |= ZMU_READ_IDX;
        break;
      case 'W':
        function |= ZMU_WRITE_IDX;
        break;
      case 'e':
        function |= ZMU_EVENT;
        break;
      case 'f':
        function |= ZMU_FPS;
        break;
      case 'z':
        function |= ZMU_ZONES;
        if ( optarg )
          zoneString = optarg;
        break;
      case 'a':
        function |= ZMU_ALARM;
        break;
      case 'n':
        function |= ZMU_NOALARM;
        break;
      case 'c':
        function |= ZMU_CANCEL;
        break;
      case 'L':
        function |= ZMU_RELOAD;
        break;
      case 'E':
        function |= ZMU_ENABLE;
        break;
      case 'D':
        function |= ZMU_DISABLE;
        break;
      case 'u':
        function |= ZMU_SUSPEND;
        break;
      case 'r':
        function |= ZMU_RESUME;
        break;
      case 'q':
        function |= ZMU_QUERY;
        break;
      case 'B':
        function |= ZMU_BRIGHTNESS;
        if ( optarg )
          brightness = atoi( optarg );
        break;
      case 'C':
        function |= ZMU_CONTRAST;
        if ( optarg )
          contrast = atoi( optarg );
        break;
      case 'H':
        function |= ZMU_HUE;
        if ( optarg )
          hue = atoi( optarg );
        break;
      case 'O':
        function |= ZMU_COLOUR;
        if ( optarg )
          colour = atoi( optarg );
        break;
      case 'U':
        username = optarg;
        break;
      case 'P':
        password = optarg;
        break;
      case 'A':
        auth = optarg;
        break;
#if ZM_HAS_V4L
      case 'V':
        v4lVersion = (atoi(optarg)==1)?1:2;
        break;
#endif // ZM_HAS_V4L
      case 'h':
        Usage( 0 );
        break;
      case 'l':
        function |= ZMU_LIST;
        break;
      case '?':
        Usage();
        break;
      default:
        //fprintf( stderr, "?? getopt returned character code 0%o ??\n", c );
        break;
    }
  }

  if (optind < argc)
  {
    fprintf( stderr, "Extraneous options, " );
    while (optind < argc)
      fprintf( stderr, "%s ", argv[optind++]);
    fprintf( stderr, "\n");
    Usage();
  }

  if ( device && !(function&ZMU_QUERY) )
  {
    fprintf( stderr, "Error, -d option cannot be used with this option\n" );
    Usage();
  }
  if ( scale != -1 && !(function&ZMU_IMAGE) )
  {
    fprintf( stderr, "Error, -S option cannot be used with this option\n" );
    Usage();
  }
  //printf( "Monitor %d, Function %d\n", mon_id, function );

  zmLoadConfig();

  logInit( "zmu" );

  zmSetDefaultTermHandler();
  zmSetDefaultDieHandler();

  User *user = 0;

  if ( config.opt_use_auth )
  {
    if ( strcmp( config.auth_relay, "none" ) == 0 )
    {
      if ( !username )
      {
        fprintf( stderr, "Error, username must be supplied\n" );
        exit( -1 );
      }

      if ( username )
      {
        user = zmLoadUser( username );
      }
    }
    else
    {
      if ( !(username && password) && !auth )
      {
        fprintf( stderr, "Error, username and password or auth string must be supplied\n" );
        exit( -1 );
      }

      //if ( strcmp( config.auth_relay, "hashed" ) == 0 )
      {
        if ( auth )
        {
          user = zmLoadAuthUser( auth, false );
        }
      }
      //else if ( strcmp( config.auth_relay, "plain" ) == 0 )
      {
        if ( username && password )
        {
          user = zmLoadUser( username, password );
        }
      }
    }
    if ( !user )
    {
      fprintf( stderr, "Error, unable to authenticate user\n" );
      exit( -1 );
    }
    ValidateAccess( user, mon_id, function );
  }
  

  if ( mon_id > 0 )
  {
    Monitor *monitor = Monitor::Load( mon_id, function&(ZMU_QUERY|ZMU_ZONES), Monitor::QUERY );
    if ( monitor )
    {
      if ( verbose )
      {
        printf( "Monitor %d(%s)\n", monitor->Id(), monitor->Name() );
      }
      if ( ! monitor->connect() ) {
        Error( "Can't connect to capture daemon: %d %s", monitor->Id(), monitor->Name() );
        exit( -1 );
      } 

      char separator = ' ';
      bool have_output = false;
      if ( function & ZMU_STATE )
      {
        Monitor::State state = monitor->GetState();
        if ( verbose )
          printf( "Current state: %s\n", state==Monitor::ALARM?"Alarm":(state==Monitor::ALERT?"Alert":"Idle") );
        else
        {
          if ( have_output ) printf( "%c", separator );
          printf( "%d", state );
          have_output = true;
        }
      }
      if ( function & ZMU_TIME )
      {
        struct timeval timestamp = monitor->GetTimestamp( image_idx );
        if ( verbose )
        {
          char timestamp_str[64] = "None";
          if ( timestamp.tv_sec )
            strftime( timestamp_str, sizeof(timestamp_str), "%Y-%m-%d %H:%M:%S", localtime( &timestamp.tv_sec ) );
          if ( image_idx == -1 )
            printf( "Time of last image capture: %s.%02ld\n", timestamp_str, timestamp.tv_usec/10000 );
          else
            printf( "Time of image %d capture: %s.%02ld\n", image_idx, timestamp_str, timestamp.tv_usec/10000 );
        }
        else
        {
          if ( have_output ) printf( "%c", separator );
          printf( "%ld.%02ld", timestamp.tv_sec, timestamp.tv_usec/10000 );
          have_output = true;
        }
      }
      if ( function & ZMU_READ_IDX )
      {
        if ( verbose )
          printf( "Last read index: %d\n", monitor->GetLastReadIndex() );
        else
        {
          if ( have_output ) printf( "%c", separator );
          printf( "%d", monitor->GetLastReadIndex() );
          have_output = true;
        }
      }
      if ( function & ZMU_WRITE_IDX )
      {
        if ( verbose )
          printf( "Last write index: %d\n", monitor->GetLastWriteIndex() );
        else
        {
          if ( have_output ) printf( "%c", separator );
          printf( "%d", monitor->GetLastWriteIndex() );
          have_output = true;
        }
      }
      if ( function & ZMU_EVENT )
      {
        if ( verbose )
          printf( "Last event id: %d\n", monitor->GetLastEvent() );
        else
        {
          if ( have_output ) printf( "%c", separator );
          printf( "%d", monitor->GetLastEvent() );
          have_output = true;
        }
      }
      if ( function & ZMU_FPS )
      {
        if ( verbose )
          printf( "Current capture rate: %.2f frames per second\n", monitor->GetFPS() );
        else
        {
          if ( have_output ) printf( "%c", separator );
          printf( "%.2f", monitor->GetFPS() );
          have_output = true;
        }
      }
      if ( function & ZMU_IMAGE )
      {
        if ( verbose )
        {
          if ( image_idx == -1 )
            printf( "Dumping last image captured to Monitor%d.jpg", monitor->Id() );
          else
            printf( "Dumping buffer image %d to Monitor%d.jpg", image_idx, monitor->Id() );
          if ( scale != -1 )
            printf( ", scaling by %d%%", scale );
          printf( "\n" );
        }
        monitor->GetImage( image_idx, scale>0?scale:100 );
      }
      if ( function & ZMU_ZONES )
      {
        if ( verbose )
          printf( "Dumping zone image to Zones%d.jpg\n", monitor->Id() );
        monitor->DumpZoneImage( zoneString );
      }
      if ( function & ZMU_ALARM )
      {
        if ( verbose )
          printf( "Forcing alarm on\n" );
        monitor->ForceAlarmOn( config.forced_alarm_score, "Forced Web" );
      }
      if ( function & ZMU_NOALARM )
      {
        if ( verbose )
          printf( "Forcing alarm off\n" );
        monitor->ForceAlarmOff();
      }
      if ( function & ZMU_CANCEL )
      {
        if ( verbose )
          printf( "Cancelling forced alarm on/off\n" );
        monitor->CancelForced();
      }
      if ( function & ZMU_RELOAD )
      {
        if ( verbose )
          printf( "Reloading monitor settings\n" );
        monitor->actionReload();
      }
      if ( function & ZMU_ENABLE )
      {
        if ( verbose )
          printf( "Enabling event generation\n" );
        monitor->actionEnable();
      }
      if ( function & ZMU_DISABLE )
      {
        if ( verbose )
          printf( "Disabling event generation\n" );
        monitor->actionDisable();
      }
      if ( function & ZMU_SUSPEND )
      {
        if ( verbose )
          printf( "Suspending event generation\n" );
        monitor->actionSuspend();
      }
      if ( function & ZMU_RESUME )
      {
        if ( verbose )
          printf( "Resuming event generation\n" );
        monitor->actionResume();
      }
      if ( function & ZMU_QUERY )
      {
        char monString[16382] = "";
        monitor->DumpSettings( monString, verbose );
        printf( "%s\n", monString );
      }
      if ( function & ZMU_BRIGHTNESS )
      {
        if ( verbose )
        {
          if ( brightness >= 0 )
            printf( "New brightness: %d\n", monitor->actionBrightness( brightness ) );
          else
            printf( "Current brightness: %d\n", monitor->actionBrightness() );
        }
        else
        {
          if ( have_output ) printf( "%c", separator );
          if ( brightness >= 0 )
            printf( "%d", monitor->actionBrightness( brightness ) );
          else
            printf( "%d", monitor->actionBrightness() );
          have_output = true;
        }
      }
      if ( function & ZMU_CONTRAST )
      {
        if ( verbose )
        {
          if ( contrast >= 0 )
            printf( "New brightness: %d\n", monitor->actionContrast( contrast ) );
          else
            printf( "Current contrast: %d\n", monitor->actionContrast() );
        }
        else
        {
          if ( have_output ) printf( "%c", separator );
          if ( contrast >= 0 )
            printf( "%d", monitor->actionContrast( contrast ) );
          else
            printf( "%d", monitor->actionContrast() );
          have_output = true;
        }
      }
      if ( function & ZMU_HUE )
      {
        if ( verbose )
        {
          if ( hue >= 0 )
            printf( "New hue: %d\n", monitor->actionHue( hue ) );
          else
            printf( "Current hue: %d\n", monitor->actionHue() );
        }
        else
        {
          if ( have_output ) printf( "%c", separator );
          if ( hue >= 0 )
            printf( "%d", monitor->actionHue( hue ) );
          else
            printf( "%d", monitor->actionHue() );
          have_output = true;
        }
      }
      if ( function & ZMU_COLOUR )
      {
        if ( verbose )
        {
          if ( colour >= 0 )
            printf( "New colour: %d\n", monitor->actionColour( colour ) );
          else
            printf( "Current colour: %d\n", monitor->actionColour() );
        }
        else
        {
          if ( have_output ) printf( "%c", separator );
          if ( colour >= 0 )
            printf( "%d", monitor->actionColour( colour ) );
          else
            printf( "%d", monitor->actionColour() );
          have_output = true;
        }
      }
      if ( have_output )
      {
        printf( "\n" );
      }
      if ( !function )
      {
        Usage();
      }
      delete monitor;
    }
    else
    {
      fprintf( stderr, "Error, invalid monitor id %d\n", mon_id );
      exit( -1 );
    }
  }
  else
  {
    if ( function & ZMU_QUERY )
    {
#if ZM_HAS_V4L
      char vidString[0x10000] = "";
      bool ok = LocalCamera::GetCurrentSettings( device, vidString, v4lVersion, verbose );
      printf( "%s", vidString );
      exit( ok?0:-1 );
#else // ZM_HAS_V4L
      fprintf( stderr, "Error, video4linux is required for device querying\n" );
      exit( -1 );
#endif // ZM_HAS_V4L
    }

    if ( function & ZMU_LIST )
    {
      std::string sql = "select Id, Function+0 from Monitors";
      if ( !verbose )
      {
        sql += "where Function != 'None'";
      }
      sql += " order by Id asc";

      if ( mysql_query( &dbconn, sql.c_str() ) )
      {
        Error( "Can't run query: %s", mysql_error( &dbconn ) );
        exit( mysql_errno( &dbconn ) );
      }

      MYSQL_RES *result = mysql_store_result( &dbconn );
      if ( !result )
      {
        Error( "Can't use query result: %s", mysql_error( &dbconn ) );
        exit( mysql_errno( &dbconn ) );
      }
      int n_monitors = mysql_num_rows( result );
      Debug( 1, "Got %d monitors", n_monitors );

      printf( "%4s%5s%6s%9s%14s%6s%6s%8s%8s\n", "Id", "Func", "State", "TrgState", "LastImgTim", "RdIdx", "WrIdx", "LastEvt", "FrmRate" );
      for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row( result ); i++ )
      {
        int mon_id = atoi(dbrow[0]);
        int function = atoi(dbrow[1]);
        if ( !user || user->canAccess( mon_id ) )
        {
          if ( function > 1 )
          {
            Monitor *monitor = Monitor::Load( mon_id, false, Monitor::QUERY );
            if ( monitor && monitor->connect() )
            {
              struct timeval tv = monitor->GetTimestamp();
              printf( "%4d%5d%6d%9d%11ld.%02ld%6d%6d%8d%8.2f\n",
                monitor->Id(),
                function,
                monitor->GetState(),
                monitor->GetTriggerState(),
                tv.tv_sec, tv.tv_usec/10000,
                monitor->GetLastReadIndex(),
                monitor->GetLastWriteIndex(),
                monitor->GetLastEvent(),
                monitor->GetFPS()
              );
              delete monitor;
            }
          }
          else
          {
            struct timeval tv = { 0, 0 };
            printf( "%4d%5d%6d%9d%11ld.%02ld%6d%6d%8d%8.2f\n",
              mon_id,
              function,
              0,
              0,
              tv.tv_sec, tv.tv_usec/10000,
              0,
              0,
              0,
              0.0
            );
          }
        }
      }
      mysql_free_result( result );
    }
  }
  delete user;

  logTerm();
  zmDbClose();

  return( 0 );
}
예제 #4
0
int main( int argc, const char *argv[] )
{
  self = argv[0];

  srand( getpid() * time( 0 ) );

  enum { ZMS_MONITOR, ZMS_EVENT } source = ZMS_MONITOR;
  enum { ZMS_JPEG, ZMS_MPEG, ZMS_RAW, ZMS_ZIP, ZMS_SINGLE } mode = ZMS_JPEG;
  char format[32] = "";
  int monitor_id = 0;
  time_t event_time = 0;
  int event_id = 0;
  unsigned int frame_id = 1;
  unsigned int scale = 100;
  unsigned int rate = 100;
  double maxfps = 10.0;
  unsigned int bitrate = 100000;
  unsigned int ttl = 0;
  EventStream::StreamMode replay = EventStream::MODE_SINGLE;
  char username[64] = "";
  char password[64] = "";
  char auth[64] = "";
  unsigned int connkey = 0;
  unsigned int playback_buffer = 0;

  bool nph = false;
  const char *basename = strrchr( argv[0], '/' );
  if (basename) //if we found a / lets skip past it
    basename++;
  else //argv[0] will not always contain the full path, but rather just the script name
    basename = argv[0];
  const char *nph_prefix = "nph-";
  if ( basename && !strncmp( basename, nph_prefix, strlen(nph_prefix) ) )
  {
    nph = true;
  }
  
  zmLoadConfig();

  logInit( "zms" );
  
  ssedetect();

  zmSetDefaultTermHandler();
  zmSetDefaultDieHandler();

  const char *query = getenv( "QUERY_STRING" );
  if ( query )
  {
    Debug( 1, "Query: %s", query );
  
    char temp_query[1024];
    strncpy( temp_query, query, sizeof(temp_query) );
    char *q_ptr = temp_query;
    char *parms[16]; // Shouldn't be more than this
    int parm_no = 0;
    while( (parm_no < 16) && (parms[parm_no] = strtok( q_ptr, "&" )) )
    {
      parm_no++;
      q_ptr = NULL;
    }
  
    for ( int p = 0; p < parm_no; p++ )
    {
      char *name = strtok( parms[p], "=" );
      char *value = strtok( NULL, "=" );
      if ( !value )
        value = (char *)"";
      if ( !strcmp( name, "source" ) )
      {
        source = !strcmp( value, "event" )?ZMS_EVENT:ZMS_MONITOR;
      }
      else if ( !strcmp( name, "mode" ) )
      {
        mode = !strcmp( value, "jpeg" )?ZMS_JPEG:ZMS_MPEG;
        mode = !strcmp( value, "raw" )?ZMS_RAW:mode;
        mode = !strcmp( value, "zip" )?ZMS_ZIP:mode;
        mode = !strcmp( value, "single" )?ZMS_SINGLE:mode;
      }
      else if ( !strcmp( name, "format" ) )
        strncpy( format, value, sizeof(format) );
      else if ( !strcmp( name, "monitor" ) )
        monitor_id = atoi( value );
      else if ( !strcmp( name, "time" ) )
        event_time = atoi( value );
      else if ( !strcmp( name, "event" ) )
        event_id = strtoull( value, (char **)NULL, 10 );
      else if ( !strcmp( name, "frame" ) )
        frame_id = strtoull( value, (char **)NULL, 10 );
      else if ( !strcmp( name, "scale" ) )
        scale = atoi( value );
      else if ( !strcmp( name, "rate" ) )
        rate = atoi( value );
      else if ( !strcmp( name, "maxfps" ) )
        maxfps = atof( value );
      else if ( !strcmp( name, "bitrate" ) )
        bitrate = atoi( value );
      else if ( !strcmp( name, "ttl" ) )
        ttl = atoi(value);
      else if ( !strcmp( name, "replay" ) )
      {
        replay = !strcmp( value, "gapless" )?EventStream::MODE_ALL_GAPLESS:EventStream::MODE_SINGLE;
        replay = !strcmp( value, "all" )?EventStream::MODE_ALL:replay;
      }
      else if ( !strcmp( name, "connkey" ) )
        connkey = atoi(value);
      else if ( !strcmp( name, "buffer" ) )
        playback_buffer = atoi(value);
      else if ( config.opt_use_auth )
      {
        if ( strcmp( config.auth_relay, "none" ) == 0 )
        {
          if ( !strcmp( name, "user" ) )
          {
            strncpy( username, value, sizeof(username) );
          }
        }
        else
        {
          //if ( strcmp( config.auth_relay, "hashed" ) == 0 )
          {
            if ( !strcmp( name, "auth" ) )
            {
              strncpy( auth, value, sizeof(auth) );
            }
          }
          //else if ( strcmp( config.auth_relay, "plain" ) == 0 )
          {
            if ( !strcmp( name, "user" ) )
            {
              strncpy( username, value, sizeof(username) );
            }
            if ( !strcmp( name, "pass" ) )
            {
              strncpy( password, value, sizeof(password) );
            }
          }
        }
      }
    }
  }

  if ( config.opt_use_auth )
  {
    User *user = 0;

    if ( strcmp( config.auth_relay, "none" ) == 0 )
    {
      if ( *username )
      {
        user = zmLoadUser( username );
      }
    }
    else
    {
      //if ( strcmp( config.auth_relay, "hashed" ) == 0 )
      {
        if ( *auth )
        {
          user = zmLoadAuthUser( auth, config.auth_hash_ips );
        }
      }
      //else if ( strcmp( config.auth_relay, "plain" ) == 0 )
      {
        if ( *username && *password )
        {
          user = zmLoadUser( username, password );
        }
      }
    }
    if ( !user )
    {
      Error( "Unable to authenticate user" );
      logTerm();
      zmDbClose();
      return( -1 );
    }
    ValidateAccess( user, monitor_id );
  }

  setbuf( stdout, 0 );
  if ( nph )
  {
    fprintf( stdout, "HTTP/1.0 200 OK\r\n" );
  }
  fprintf( stdout, "Server: ZoneMinder Video Server/%s\r\n", ZM_VERSION );
        
  time_t now = time( 0 );
  char date_string[64];
  strftime( date_string, sizeof(date_string)-1, "%a, %d %b %Y %H:%M:%S GMT", gmtime( &now ) );

  fprintf( stdout, "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n" );
  fprintf( stdout, "Last-Modified: %s\r\n", date_string );
  fprintf( stdout, "Cache-Control: no-store, no-cache, must-revalidate\r\n" );
  fprintf( stdout, "Cache-Control: post-check=0, pre-check=0\r\n" );
  fprintf( stdout, "Pragma: no-cache\r\n");
  // Removed as causing more problems than it fixed.
  //if ( !nph )
  //{
    //fprintf( stdout, "Content-Length: 0\r\n");
  //}

  if ( source == ZMS_MONITOR )
  {
    MonitorStream stream;
    stream.setStreamScale( scale );
    stream.setStreamReplayRate( rate );
    stream.setStreamMaxFPS( maxfps );
    stream.setStreamTTL( ttl );
    stream.setStreamQueue( connkey );
    stream.setStreamBuffer( playback_buffer );
    if ( ! stream.setStreamStart( monitor_id ) ) {
      Error( "Unable to connect to zmc process for monitor %d", monitor_id );
      fprintf( stderr, "Unable to connect to zmc process.  Please ensure that it is running." );
      logTerm();
      zmDbClose();
      return( -1 );
    } 

    if ( mode == ZMS_JPEG )
    {
      stream.setStreamType( MonitorStream::STREAM_JPEG );
    }
    else if ( mode == ZMS_RAW )
    {
      stream.setStreamType( MonitorStream::STREAM_RAW );
    }
    else if ( mode == ZMS_ZIP )
    {
      stream.setStreamType( MonitorStream::STREAM_ZIP );
    }
    else if ( mode == ZMS_SINGLE )
    {
      stream.setStreamType( MonitorStream::STREAM_SINGLE );
    }
    else
    {
#if HAVE_LIBAVCODEC
      stream.setStreamFormat( format );
      stream.setStreamBitrate( bitrate );
      stream.setStreamType( MonitorStream::STREAM_MPEG );
#else // HAVE_LIBAVCODEC
      Error( "MPEG streaming of '%s' attempted while disabled", query );
      fprintf( stderr, "MPEG streaming is disabled.\nYou should configure with the --with-ffmpeg option and rebuild to use this functionality.\n" );
      logTerm();
      zmDbClose();
      return( -1 );
#endif // HAVE_LIBAVCODEC
    }
    stream.runStream();
  }
  else if ( source == ZMS_EVENT )
  {
    EventStream stream;
    stream.setStreamScale( scale );
    stream.setStreamReplayRate( rate );
    stream.setStreamMaxFPS( maxfps );
    stream.setStreamMode( replay );
    stream.setStreamQueue( connkey );
    if ( monitor_id && event_time )
    {
      stream.setStreamStart( monitor_id, event_time );
    }
    else
    {
      stream.setStreamStart( event_id, frame_id );
    }
    if ( mode == ZMS_JPEG )
    {
      stream.setStreamType( EventStream::STREAM_JPEG );
    }
    else
    {
#if HAVE_LIBAVCODEC
      stream.setStreamFormat( format );
      stream.setStreamBitrate( bitrate );
      stream.setStreamType( EventStream::STREAM_MPEG );
#else // HAVE_LIBAVCODEC
      Error( "MPEG streaming of '%s' attempted while disabled", query );
      fprintf( stderr, "MPEG streaming is disabled.\nYou should ensure the ffmpeg libraries are installed and detected and rebuild to use this functionality.\n" );
      logTerm();
      zmDbClose();
      return( -1 );
#endif // HAVE_LIBAVCODEC
    }
    stream.runStream();
  }

  logTerm();
  zmDbClose();

  return( 0 );
}
예제 #5
0
	void Visit(SyntaxApi::IOperations::IId* operation_node)
	{
		SemanticApi::IVariable* var = parent->GetVar(operation_node->GetName());
		if (var != nullptr)
		{
			switch (var->GetVariableType())
			{
			case SemanticApi::VariableType::ClassField:
			{
				ValidateAccess(syntax_node, owner, (TSClassField*)var);
				auto var_field = dynamic_cast<TSClassField*>(var);
				if ((!var_field->GetSyntax()->IsStatic()) && method->GetSyntax()->IsStatic())
					syntax_node->Error("К нестатическому полю класса нельзя обращаться из статического метода!");
				TSExpression::TGetClassField* result = new TSExpression::TGetClassField(
					nullptr, TExpressionResult(dynamic_cast<TSClass*>(var_field->GetClass()), true), var_field);
				Return(result);
			}break;
			case SemanticApi::VariableType::Local:
			{
				TSExpression::TGetLocal* result = new TSExpression::TGetLocal(dynamic_cast<TSLocalVar*>(var));
				Return(result);
			}break;
			case SemanticApi::VariableType::Parameter:
			{
				TSExpression::TGetParameter* result = new TSExpression::TGetParameter(dynamic_cast<TSParameter*>(var));
				Return(result);
			}break;
			default:
				assert(false);//ошибка в поиске переменной
			}
		}
		else
		{
			std::vector<SemanticApi::ISMethod*> methods;
			if (method->GetSyntax()->IsStatic())
			{
				owner->GetMethods(methods, operation_node->GetName(), SemanticApi::Filter::True);
				if (methods.size() == 0)
				{
					std::vector<SemanticApi::ISMethod*> temp;
					if (owner->GetMethods(temp, operation_node->GetName(), SemanticApi::Filter::False))
					{
						syntax_node->Error("К нестатическому методу класса нельзя обращаться из статического метода!");
					}
				}
			}
			else
			{
				owner->GetMethods(methods, operation_node->GetName());
			}
			if (methods.size() != 0)
			{
				TSExpression::TGetMethods* result = new TSExpression::TGetMethods(nullptr, TExpressionResult(), TExpressionResult(methods, method->GetSyntax()->IsStatic()));
				Return(result);
			}
			else
			{
					syntax_node->Error("Неизвестный идентификатор!");
			}
		}
	}
예제 #6
0
	void Visit(SyntaxApi::IOperations::IGetMemberOp* operation_node)
	{
		TSOperation *left;
		left = VisitNode(operation_node->GetLeft());

		TExpressionResult left_result = left->GetFormalParameter();

		auto left_class = dynamic_cast<TSClass*>(left_result.GetClass());

		if (left_result.IsMethods())
			syntax_node->Error("Оператор доступа к члену класса нельзя применить к методу!");
		if (left_result.IsType())
		{
			auto left_result_class = dynamic_cast<TSClass*>(left_result.GetType());
			if (left_result_class->GetSyntax()->IsEnumeration())
			{
				int id = left_result_class->GetSyntax()->GetEnumId(operation_node->GetName());
				//TODO ввести спец функции min max count
				if (id == -1)
					syntax_node->Error("Перечислимого типа с таким именем не существует!");
				else
				{
					delete left;
					TSExpression::TEnumValue* result = new TSExpression::TEnumValue(owner, dynamic_cast<TSClass*>(left_result.GetType()));
					result->val = id;
					Return(result);
				}
			}
			else
			{
				TSClassField* static_member = left_result_class->GetField(operation_node->GetName(), true, true);
				if (static_member != nullptr)
				{
					TSExpression::TGetClassField* result = new TSExpression::TGetClassField(
						left, left_result, static_member);
					Return(result);
				}
				else
				{
					std::vector<SemanticApi::ISMethod*> methods;
					if (left_result_class->GetMethods(methods, operation_node->GetName(), SemanticApi::Filter::True))
					{
						TSExpression::TGetMethods* result = new TSExpression::TGetMethods(
							left, left_result, TExpressionResult(methods, method->GetSyntax()->IsStatic()));
						Return(result);
					}
					else
						syntax_node->Error("Статического поля или метода с таким именем не существует!");
				}
			}
		}
		else
		{
			TSClassField* member = (left_class != nullptr)
				? left_class->GetField(operation_node->GetName(), true)
				: nullptr;
			if (member != nullptr)
			{
				if (member->GetSyntax()->IsStatic())
					syntax_node->Error("Оператор доступа к члену класса нельзя применить к объекту для доступа к статическому члену, \nвместо объекта следует использовать имя класса!");
				ValidateAccess(syntax_node, owner, member);

				TSExpression::TGetClassField* result = new TSExpression::TGetClassField(
					left, left_result, member);
				Return(result);
			}
			else
			{
				std::vector<SemanticApi::ISMethod*> methods;
				if (left_class->GetMethods(methods, operation_node->GetName(), SemanticApi::Filter::False))
				{
					TSExpression::TGetMethods* result = new TSExpression::TGetMethods(
						left, left_result, TExpressionResult(methods, false));
					Return(result);
				}
				else
					syntax_node->Error("Члена класса с таким именем не существует!");
			}
		}
	}
예제 #7
0
	void Visit(SyntaxApi::IOperations::ICallParamsOp* operation_node)
	{
		TSOperation *left;
		left = VisitNode(operation_node->GetLeft());

		TExpressionResult left_result = left->GetFormalParameter();
		
		std::vector<TExpressionResult> params_result;
		std::vector<TSOperation*> param_expressions;
		std::vector<SemanticApi::TFormalParameter> params_formals;
		auto param = operation_node->GetParam();
		for (size_t i = 0; i < param.size(); i++)
		{
			TSOperation* return_new_operation = VisitNode(param[i]);
			param_expressions.push_back(return_new_operation);
			params_result.push_back(return_new_operation->GetFormalParameter());
			params_formals.push_back(SemanticApi::TFormalParameter(params_result.back().GetClass(), params_result.back().IsRef()));
		}
		
		if (left_result.IsMethods())
		{
			//вызов метода
			if (operation_node->IsBracket())
				assert(false);//при вызове метода используются круглые скобки
			SemanticApi::ISMethod* invoke = nullptr;
			SemanticApi::ISMethod* method = FindMethod(syntax_node, left_result.GetMethods(), params_result);
			if (method != nullptr)
			{
				ValidateAccess(syntax_node, owner, method);
				invoke = method;
			}
			else 
				syntax_node->Error("Метода с такими параметрами не существует");

			TSExpression_TMethodCall* method_call = new TSExpression_TMethodCall(SemanticApi::TMethodCallType::Method);
			method_call->Build(param_expressions, dynamic_cast<TSMethod*>(invoke));
			method_call->left.reset(left);
			//method_call->construct_temp_object->Build()
			Return(method_call);
		}
		else if (left_result.IsType())
		{
			//if(left_result.GetType()->GetType()==TYPE_ENUM)
			//	Error("Для перечислений нельзя использовать оператор вызова параметров!");
			int conv_need = -1;
			std::vector<TSMethod*> constructors;
			TSClass* constr_class = dynamic_cast<TSClass*>(left_result.GetType());

			auto construct_object = new TSConstructObject(owner, method, parent->GetParentStatements(), constr_class);
			construct_object->Build(operation_node->GetOperationSource(), params_result, param_expressions, params_formals, build_context);

			TSExpression_TCreateTempObject* create_temp_obj = new TSExpression_TCreateTempObject(
				(TSExpression_TypeDecl*)left,
				construct_object
			);
			Return(create_temp_obj);
		}
		else
			//иначе вызов оператора () или []
		{
			//т.к. все операторы статические - первым параметром передаем ссылку на объект
			param_expressions.insert(param_expressions.begin(), left);
			params_result.insert(params_result.begin(), left_result);
			
			left = nullptr;
			SemanticApi::ISMethod* invoke = nullptr;
			std::vector<SemanticApi::ISMethod*> operators;
			left_result.GetClass()->GetOperators(operators, operation_node->IsBracket() ? (Lexer::TOperator::GetArrayElement) : (Lexer::TOperator::ParamsCall));
			SemanticApi::ISMethod* method = FindMethod(syntax_node, operators, params_result);
			if (method != nullptr)
			{
				ValidateAccess(syntax_node, owner, method);
				invoke = method;
			}
			else
				syntax_node->Error("Оператора с такими параметрами не существует!");

			TSExpression_TMethodCall* method_call = new TSExpression_TMethodCall(SemanticApi::TMethodCallType::Operator);
			method_call->Build(param_expressions, dynamic_cast<TSMethod*>(invoke));

			Return(method_call);
		}		
	}