#
#httpd for system web api
#
user root root;
worker_processes  1;
worker_rlimit_nofile 512;
worker_priority -5;
#
#/etc/init.d/sysapihttpd
#
#error log will send to stdout and save by syslog
#
daemon on;

#nginx connect()  failed (128: Unknown error) is Destination Net Unreachable
#debug | info | notice | warn | error | crit
error_log stderr warn;

#pid    logs/nginx.pid;

events {
  use epoll;
  worker_connections  256;
}

http {
  #
  include     mime.types;
  default_type  application/octet-stream;

  #\t"$upstream_cache_status" replaced by \t"$sent_http_ MiCGI_Cache_Status"
  log_format main '"$server_addr"\t"$host"\t"$remote_addr"\t"$time_local"\t"$request_method $request_uri"\t"$status"\t"$request_length"\t"$bytes_sent"\t"$request_time"\t"$sent_http_ MiCGI_Cache_Status"\t"$upstream_addr"\t"$upstream_response_time"\t"$http_referer"\t"$http_user_agent"';

  #access_log /userdisk/sysapihttpd/log/access.log  main;
  access_log off;

  sendfile    on;
  #tcp_nopush   on;

  #http://wiki.nginx.org/HttpCoreModule#server_tokens
  server_tokens off;

  #disable keepalive for webinitrdr
  keepalive_timeout  0;

  # zeor for no max limit
  client_max_body_size 0;
  #
  proxy_buffering off;
  proxy_max_temp_file_size 2m;

  proxy_buffer_size  256k;
  proxy_buffers   32 32k;
  proxy_busy_buffers_size 256k;

  server_names_hash_bucket_size 64;
  proxy_headers_hash_bucket_size 128;
  proxy_headers_hash_max_size 8192;

  #https://groups.google.com/forum/#!msg/openresty/sgNvuGk0tlQ/lFxfl-mg9HMJ
  #2013/08/08 11:50:03 [error] 3971#0: wrong ident 16756 response for www.youtube.com, expect 35660

  proxy_connect_timeout  186;
  proxy_read_timeout     1200;
  proxy_send_timeout     1200;

  #gzip  on;
  #gzip_min_length  1024;
  #gzip_proxied     expired no-cache no-store private auth no_last_modified no_etag;
  #gzip_types     application/json application/x-json text/css text/xml text/plain application/xml;
  #gzip_disable     "MSIE [1-6]\.";

  fastcgi_connect_timeout 300;
  fastcgi_read_timeout 300;
  fastcgi_send_timeout 300;
  #fastcgi_buffering off;
  fastcgi_buffer_size 64k;
  fastcgi_buffers   4 32k;
  fastcgi_busy_buffers_size 64k;
  fastcgi_temp_file_write_size 64k;
  #fastcgi_max_temp_file_size 0;

  limit_conn_zone $binary_remote_addr zone=addr_zone:256k;

  server {
    #
    #server for sysapi
    #
    listen 80;
    listen 8098;
    server_name  _;
    access_log  off;
    #access_log /userdisk/sysapihttpd/log/luaroot.access.log  main;

    log_not_found off;
    limit_conn addr_zone 8;

    #
    keepalive_timeout  0;
    
    #set the send_timeout as 60 minutes
    send_timeout 60m;
    #
    root /www;
    index index.html index.htm;

    # 0.0.0.1:65535 no avaible
    #redirect 0.0.0.1:65535 127.0.0.1:5081;

    #disable proxy errors handle
    proxy_intercept_errors off;

    #http://wiki.nginx.org/HttpCoreModule#reset_timedout_connection
    reset_timedout_connection on;

    expires epoch;
    #
    include 'miwifi-webinitrd.conf';
    #

    location = /miwifi.html
    {
        root /etc/sysapihttpd/htdocs/;
    }
    location = /stat/proxy.shtml {
      #
      keepalive_timeout  0;
      access_log  off;
      #
      add_header  MiCGI-StatChain STAT;
      proxy_set_header Host miwifi.com;
      proxy_pass http://127.0.0.1:5081;
      #
    }
    location /backup/log {
      alias /tmp/syslogbackup/;
    }
    location /api/service/plugin {
      rewrite ^/api/service/plugin/control /api-third-party/download/private/$arg_appid/control.html? permanent;
    }
    location /api-third-party/download/public {
      alias /userdisk/data/;
    }     
    location /api-third-party/download/private {
      alias /userdisk/appdata/;
    }          
    location /api-third-party/download/extdisks {
      alias /extdisks/;
    }          
    location /api-third-party/service {
      #
      add_header MiCGI-Switch "$finalvar";
      add_header  MiCGI-Client-Ip $remote_addr;
      add_header  MiCGI-Host $host;
      add_header  MiCGI-Http-Host $http_host;
      add_header  MiCGI-Server-Ip $server_addr;
      add_header  MiCGI-Server-Port $server_port;
      add_header  MiCGI-Status CGI;
      add_header  MiCGI-Preload no;
      #
      include 'fastcgi-proxy-tcp.conf';
      #
    }
    location ^~ /uploadfile/cgi-bin {
      #
      #for POST /uploadfile/cgi-bin/luci/;stok=42822adbabf606fe7946cd2e9b98d9a5/api/xqsystem/upload_rom
      #
      add_header MiCGI-Switch "$finalvar";
      add_header  MiCGI-Client-Ip $remote_addr;
      add_header  MiCGI-Host $host;
      add_header  MiCGI-Http-Host $http_host;
      add_header  MiCGI-Server-Ip $server_addr;
      add_header  MiCGI-Server-Port $server_port;
      add_header  MiCGI-Status CGI;
      add_header  MiCGI-Preload no;
      add_header  MiCGI-Upload-File yes;
      # for upload roms only [start]
      client_body_temp_path /tmp/uploadfiles/;
      client_body_in_file_only on;
      client_body_buffer_size 16k;
      proxy_pass_request_headers on;
      proxy_set_body off;
      proxy_redirect off;
      fastcgi_param  UPLOADFILE $request_body_file;
      client_max_body_size 20M;
      #TODO: upload_multipart_cut
      #upload_multipart_cut on;
      fastcgi_max_temp_file_size 0;
      # for upload rom only [end]
      #
      include 'fastcgi-proxy-tcp.conf';
      #
    }
    location /cgi-bin/upload {
	  internal;
      include 'fastcgi-proxy-tcp.conf';
	}
    location /cgi-bin {
      #
      add_header MiCGI-Switch "$finalvar";
      add_header  MiCGI-Client-Ip $remote_addr;
      add_header  MiCGI-Host $host;
      add_header  MiCGI-Http-Host $http_host;
      add_header  MiCGI-Server-Ip $server_addr;
      add_header  MiCGI-Server-Port $server_port;
      add_header  MiCGI-Status CGI;
      add_header  MiCGI-Preload no;
      #
      include 'fastcgi-proxy-tcp.conf';
      #
    }

    location ^~ /download-userdisk/ {
      internal;
      alias /userdisk/data/;
    }
    location ^~ /download-extdisks/ {
      internal;
      alias /extdisks/;
    }
    location ^~ /download-pridisk/ {
      internal;
      alias /userdisk/privacyData/;
    }
    #
    location / {
      #
      add_header MiCGI-Switch "$finalvar";
      add_header MiCGI-TproxyInfo "$dst_addr:$dst_port";
      add_header MiCGI-Upstream "$target_upstream";
      add_header  MiCGI-Client-Ip $remote_addr;
      add_header  MiCGI-Host $host;
      add_header  MiCGI-Http-Host $http_host;
      add_header  MiCGI-Server-Ip $server_addr;
      add_header  MiCGI-Server-Port $server_port;
      add_header  MiCGI-Status LUAROOT;
      add_header  MiCGI-Preload no;
      #
      root /www;
      index index.html index.htm;
      #
    }
    #
    #**#error_page  404    /err/404.html;
    #**#error_page  500    /err/500.html;
    #**#error_page  501    /err/502.html;
    #**#error_page  502    /err/502.html;
    #**#error_page  503    /err/503.html;
    #**#error_page  504    /err/504.html;
    #
    location ~ /err/ {
      #
      internal;
      #
      access_log  off;
      keepalive_timeout  0;
      #
      add_header  MiCGI-Client-Ip $remote_addr;
      add_header  MiCGI-Host $host;
      add_header  MiCGI-Http-Host $http_host;
      add_header  MiCGI-Server-Ip $server_addr;
      add_header  MiCGI-Server-Port $server_port;
      add_header  MiCGI-Preload no;
      #
      add_header  MiCGI-Status ERR-HTML;
      add_header Cache-Control  'private,max-age=0';
      expires epoch;
      add_header Content-Type "text/html;charset=utf-8";
      #
      root   /www/;
    }
    #
  }
  server {
    #request info/stat server
    listen 5081;
    server_name  _;
    access_log  off;

    log_not_found off;
    keepalive_timeout  0;

    #
    root /etc/nginx/htdocs/;
    index index.html index.htm;
    #
    #
    include 'stat.conf';
    #
  }

  ad_filter_zone zone=ad_filter_zone:16k;
  server {
    listen 8195;
    #error_log /userdisk/sysapihttpd/log/error.log info;
    ad_filter_statistics ad_filter_zone;
  }

  preload_zone zone=web_preload_zone:16k;
  server {
    listen 8193;
    server_name  _;
    error_log /userdisk/sysapihttpd/log/error.log info;
    access_log  off;

    location / {
      add_header  Cache-Mark 'xiaomi';
      preload /userdisk/cachecenter/cache_dir/ /http_proxy/ web_preload_zone;
    }

    resolver 127.0.0.1 valid=30s;
    location /http_proxy {
      internal;
      add_header  Proxy-Mark 'xiaomi';
      rewrite /http_proxy/ / break;
      proxy_pass http://$http_host$request_uri;
    }
  }


  server {
    listen 8196;
    # resolver 8.8.8.8;
    resolver 127.0.0.1 valid=30s;
    log_format proxy_log '"$server_addr"\t"$host"\t"$remote_addr"\t"$time_local"\t"$request_method $request_uri"\t"$status"\t"$request_length"\t"$bytes_sent"\t"$request_time"\t"$sent_http_ MiCGI_Cache_Status"\t"$upstream_addr"\t"$upstream_response_time"\t"$http_referer"\t"$http_user_agent"';
    access_log off;
    #access_log /userdisk/data/proxy_8194.log  proxy_log;
    #error_log /userdisk/sysapihttpd/log/error.log info;

    location / {
      add_header  AD-Mark 'xiaomi';
      ad_filter /proxy/ ad_filter_zone;
    }
    location /proxy {
      internal;
      add_header  Proxy-Mark 'xq-proxy';
      rewrite /proxy/ / break;
      proxy_pass http://$http_host$request_uri;
    }
  }
    server {
            listen 8197;
            # resolver 8.8.8.8;
            resolver 127.0.0.1 valid=30s;
            log_format log_subfilter '"$server_addr"\t"$host"\t"$remote_addr"\t"$time_local"\t"$request_method $request_uri"\t"$status"\t"$request_length"\t"$bytes_sent"\t"$request_time"\t"$sent_http_ MiCGI_Cache_Status"\t"$upstream_addr"\t"$upstream_response_time"\t"$http_referer"\t"$http_user_agent"';
            access_log off;
            #access_log /userdisk/data/proxy_8197.log  log_subfilter;
            #error_log /userdisk/sysapihttpd/log/error.log info;

            location / {
                    proxy_set_header Accept-Encoding "";
                    proxy_pass http://$http_host$request_uri;
                    add_header  XQ-Mark 'subfilter';
                    proxy_connect_timeout 600;
                    proxy_read_timeout 600;
                    proxy_send_timeout 600;
                    #sub_filter '</body>' '<div style="display:none">XQ Sub-Filter</div></body>';
                    sub_filter '</head>' '<script type="text/javascript"></script></head>';
            }
    }

    server {
        listen 8192;
        add_header  Safe-Mark 'xiaomi';
        server_name  _;
        access_log  off;
        resolver 127.0.0.1 valid=30s;
        set $rrd "RR_D_STUB";
        if ( -f "/tmp/state/security_page_baidu") {
            set $vend "baidu";
        }
        if ( -f "/tmp/state/security_page_tencent") {
            set $vend "tencent";
        }
        location / {
          set_escape_uri $http_url $scheme://$host$request_uri;
          set $args "d=$rrd&error_type=4&sc=&url=$http_url&vendor=$vend";
          proxy_pass http://api.miwifi.com/rr/e$is_args$args;
        }
    }

    server {
        listen 8191;
        add_header  Error-Mark 'xiaomi';
        server_name  _;
        access_log  off;
        resolver 127.0.0.1 valid=30s;
        set $rrd "RR_D_STUB";
        location /error-page {
            set $args "d=$rrd&error_type=$arg_error_type&sc=$arg_sc";
            proxy_pass https://api.miwifi.com/rr/e$is_args$args;
        }
    }
    # for nxdomain resolve result
    server {
        listen 8190;
        add_header  Error-Mark 'xiaomi';
        server_name  _;
        access_log  off;
        resolver 127.0.0.1 valid=30s;
        set $rrd "RR_D_STUB";
        location / {
            set $args "d=$rrd&error_type=2";
            proxy_pass https://api.miwifi.com/rr/e$is_args$args;
        }
    }

    rr_config rr_zone 2M "RR_PATH_STUB";
    server {
        listen 8380;
        resolver localhost;
        location / {
            rr_filter rr_zone;
            toolbar_config on;
            proxy_pass $scheme://$host$request_uri;
            proxy_ignore_client_abort off;
            proxy_connect_timeout 30s;
            proxy_read_timeout 30s;
            proxy_send_timeout 30s;
            proxy_buffering off;
            proxy_set_header Accept-Encoding '';
            proxy_max_temp_file_size 0;
            proxy_set_header Host $http_host;
        }
    }

    server {
        listen 8382;
        resolver localhost;
        location / {
            rr_filter rr_zone;
            upgrade_config on;
            proxy_pass $scheme://$host$request_uri;
            proxy_ignore_client_abort off;
            proxy_connect_timeout 30s;
            proxy_read_timeout 30s;
            proxy_send_timeout 30s;
            proxy_buffering off;
            proxy_set_header Accept-Encoding '';
            proxy_max_temp_file_size 0;
            proxy_set_header Host $http_host;
        }
    }

    server {
        listen 8383;
        resolver localhost;
        location / {
            rr_filter rr_zone;
            event_config on;
            proxy_pass $scheme://$host$request_uri;
            proxy_ignore_client_abort off;
            proxy_connect_timeout 30s;
            proxy_read_timeout 30s;
            proxy_send_timeout 30s;
            proxy_buffering off;
            proxy_set_header Accept-Encoding '';
            proxy_max_temp_file_size 0;
            proxy_set_header Host $http_host;
        }
    }

    # for security dl
    server {
        listen 8381;
        server_name _;
        resolver 127.0.0.1 valid=30s;
        location / {
            add_header REAP-Mark 'xiaomi';
            if ($http_reap_url ~ ^http)
            {
                return 302 $http_reap_url;
            }
            if ($http_reap_url !~ ^http)
            {
                return 302 http://$http_reap_url;
            }
        }
    }
    server {
        listen 8384;
        add_header  Error-Mark 'xiaomi';
        server_name  _;
        access_log  off;
        resolver 127.0.0.1 valid=30s;
        set $rrd "DEV_ID_STUB";
        location / {
            set $args "deviceId=$rrd";
            proxy_pass https://api.miwifi.com/thirdparty/yyb/proxy$is_args$args;
        }
    }

    # for guest portal, set a sepcial server for portal page's link.
    server {
        listen 8999 default_server;
        server_name  _;
        access_log  off;
        resolver 127.0.0.1 valid=30s;
        set $did "DEV_ID_STUB";
        location / {
            if ($request_method != GET) {
                return 405;
            }
            set $args "did=$did";
            proxy_pass https://api.miwifi.com/sns/portal$is_args$args;
        }
    }

    server {
        listen 8999;
        server_name  miwifi.com *.miwifi.com *.xiaomi.net *.xiaomi.com *.mi.com;
        access_log  off;
        resolver 127.0.0.1 valid=30s;

        location / {
            proxy_pass $scheme://$host$request_uri;
            proxy_set_header X-Forwarded-For $remote_addr;
        }

	# for portal page polling access status
	location /cgi-bin/luci/api/misns/authorization_status {
	    proxy_pass http://miwifi.com$request_uri;
	    proxy_set_header X-Forwarded-For $remote_addr;
	}

	location /cgi-bin/luci/api/misns/sns_init {
	    proxy_pass http://miwifi.com$request_uri;
	    proxy_set_header X-Forwarded-For $remote_addr;
	}

	location /cgi-bin/luci/api/misns/prepare {
	    proxy_pass http://miwifi.com$request_uri;
	    proxy_set_header X-Forwarded-For $remote_addr;
	}

	location /cgi-bin/luci {
	    deny  all;
	}
   }


   #for supporting wifishare dnsd-mode
   server {
        listen 8899 default_server;
        server_name  _;
        access_log  off;
        resolver 127.0.0.1 valid=30s;
        set $did "DEV_ID_STUB";
        location / {
            if ($request_method != GET) {
                return 405;
            }
            set $args "did=$did";
            proxy_pass https://api.miwifi.com/sns/portal$is_args$args;
        }
   }

   #ensure ios hotspots-detect reachable
   server {
        listen 8899;
        server_name captive.apple.com;
        resolver 127.0.0.1 valid=30s;
        location / {
            proxy_pass $scheme://captive.apple.com$request_uri;
        }
   }

   server {
        listen 8899;
        server_name  miwifi.com *.miwifi.com *.xiaomi.net *.xiaomi.com *.mi.com;
        access_log  off;
        resolver 127.0.0.1 valid=30s;
        location / {
            proxy_pass $scheme://$host$request_uri;
            proxy_set_header X-Forwarded-For $remote_addr;
        }

        # for portal page polling access status
        location /cgi-bin/luci/api/misns/authorization_status {
            proxy_pass http://miwifi.com$request_uri;
            proxy_set_header X-Forwarded-For $remote_addr;
        }

        location /cgi-bin/luci/api/misns/sns_init {
            proxy_pass http://miwifi.com$request_uri;
            proxy_set_header X-Forwarded-For $remote_addr;
        }

        location /cgi-bin/luci/api/misns/prepare {
            proxy_pass http://miwifi.com$request_uri;
            proxy_set_header X-Forwarded-For $remote_addr;
        }

        location /cgi-bin/luci {
            deny  all;
        }
   }
}

#
